From f6096aa4b89f021241557ac47b0a2f3b936099e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?G=C3=A1bor=20Cs=C3=A1rdi?= Date: Thu, 22 Feb 2024 17:27:54 +0100 Subject: [PATCH] [setup-pandoc] fix build [ci skip] --- .github/workflows/setup-pandoc-test.yaml | 2 +- setup-pandoc/node_modules/.package-lock.json | 212 +- .../@sindresorhus/is/dist/index.d.ts | 465 +-- .../@sindresorhus/is/dist/index.js | 1474 ++-------- .../@sindresorhus/is/dist/types.d.ts | 34 +- .../@sindresorhus/is/dist/types.js | 3 +- .../@sindresorhus/is/package.json | 67 +- .../node_modules/@sindresorhus/is/readme.md | 89 +- .../@szmarczak/http-timer/README.md | 4 +- .../http-timer/dist/source/index.d.ts | 2 +- .../http-timer/dist/source/index.js | 64 +- .../@szmarczak/http-timer/package.json | 53 +- .../@types/cacheable-request/LICENSE | 21 + .../@types/cacheable-request/README.md | 16 + .../@types/cacheable-request/index.d.ts | 137 + .../@types/cacheable-request/package.json | 35 + setup-pandoc/node_modules/@types/keyv/LICENSE | 21 + .../node_modules/@types/keyv/README.md | 16 + .../node_modules/@types/keyv/index.d.ts | 90 + .../node_modules/@types/keyv/package.json | 32 + .../node_modules/@types/responselike/LICENSE | 21 + .../@types/responselike/README.md | 48 + .../@types/responselike/index.d.ts | 29 + .../@types/responselike/package.json | 27 + .../node_modules/cacheable-lookup/LICENSE | 0 .../node_modules/cacheable-lookup/README.md | 57 +- .../node_modules/cacheable-lookup/index.d.ts | 15 +- .../cacheable-lookup/package.json | 34 +- .../cacheable-lookup/source/index.js | 104 +- .../license => cacheable-request/LICENSE} | 4 +- .../node_modules/cacheable-request/README.md | 167 +- .../cacheable-request/dist/index.d.ts | 17 - .../cacheable-request/dist/index.d.ts.map | 1 - .../cacheable-request/dist/index.js | 275 -- .../cacheable-request/dist/index.js.map | 1 - .../cacheable-request/dist/types.d.ts | 106 - .../cacheable-request/dist/types.d.ts.map | 1 - .../cacheable-request/dist/types.js | 19 - .../cacheable-request/dist/types.js.map | 1 - .../node_modules/get-stream/index.d.ts | 5 +- .../node_modules/get-stream/index.js | 23 +- .../node_modules/get-stream/package.json | 13 +- .../node_modules/get-stream/readme.md | 2 +- .../cacheable-request/package.json | 119 +- .../cacheable-request/src/index.js | 251 ++ .../node_modules/clone-response/LICENSE | 21 + .../node_modules/clone-response/README.md | 62 + .../node_modules/clone-response/package.json | 41 + .../node_modules/clone-response/src/index.js | 17 + .../form-data-encoder/lib/index.cjs | 393 --- .../form-data-encoder/lib/index.d.cts | 277 -- .../form-data-encoder/lib/index.d.ts | 277 -- .../form-data-encoder/lib/index.js | 365 --- .../form-data-encoder/package.json | 84 - .../node_modules/form-data-encoder/readme.md | 369 --- .../source/as-promise/create-rejection.d.ts | 2 + .../source/as-promise/create-rejection.js | 30 + .../got/dist/source/as-promise/index.d.ts | 6 +- .../got/dist/source/as-promise/index.js | 160 +- .../as-promise/normalize-arguments.d.ts | 3 + .../source/as-promise/normalize-arguments.js | 78 + .../dist/source/as-promise/parse-body.d.ts | 3 + .../got/dist/source/as-promise/parse-body.js | 25 + .../got/dist/source/as-promise/types.d.ts | 268 +- .../got/dist/source/as-promise/types.js | 35 +- .../source/core/calculate-retry-delay.d.ts | 5 +- .../dist/source/core/calculate-retry-delay.js | 18 +- .../got/dist/source/core/errors.d.ts | 90 - .../got/dist/source/core/errors.js | 139 - .../got/dist/source/core/index.d.ts | 1160 +++++++- .../got/dist/source/core/index.js | 1821 +++++++----- .../got/dist/source/core/options.d.ts | 1255 -------- .../got/dist/source/core/options.js | 1635 ----------- .../dist/source/core/parse-link-header.d.ts | 4 - .../got/dist/source/core/parse-link-header.js | 33 - .../got/dist/source/core/response.d.ts | 108 - .../got/dist/source/core/response.js | 41 - .../got/dist/source/core/timed-out.d.ts | 31 - .../got/dist/source/core/timed-out.js | 129 - .../source/core/utils/dns-ip-version.d.ts | 5 + .../dist/source/core/utils/dns-ip-version.js | 17 + .../dist/source/core/utils/get-body-size.d.ts | 6 +- .../dist/source/core/utils/get-body-size.js | 30 +- .../dist/source/core/utils/get-buffer.d.ts | 4 + .../got/dist/source/core/utils/get-buffer.js | 16 + .../source/core/utils/is-client-request.d.ts | 6 - .../source/core/utils/is-client-request.js | 4 - .../dist/source/core/utils/is-form-data.d.ts | 12 +- .../dist/source/core/utils/is-form-data.js | 8 +- .../source/core/utils/is-response-ok.d.ts | 2 + .../dist/source/core/utils/is-response-ok.js | 8 + .../source/core/utils/is-unix-socket-url.d.ts | 1 - .../source/core/utils/is-unix-socket-url.js | 4 - .../source/core/utils/options-to-url.d.ts | 8 +- .../dist/source/core/utils/options-to-url.js | 15 +- .../dist/source/core/utils/proxy-events.d.ts | 6 +- .../dist/source/core/utils/proxy-events.js | 16 +- .../got/dist/source/core/utils/timed-out.d.ts | 29 + .../got/dist/source/core/utils/timed-out.js | 121 + .../got/dist/source/core/utils/unhandle.d.ts | 18 +- .../got/dist/source/core/utils/unhandle.js | 8 +- .../source/core/utils/url-to-options.d.ts | 10 +- .../dist/source/core/utils/url-to-options.js | 14 +- .../dist/source/core/utils/weakable-map.js | 7 +- .../node_modules/got/dist/source/create.d.ts | 4 +- .../node_modules/got/dist/source/create.js | 265 +- .../node_modules/got/dist/source/index.d.ts | 17 +- .../node_modules/got/dist/source/index.js | 149 +- .../node_modules/got/dist/source/types.d.ts | 235 +- .../node_modules/got/dist/source/types.js | 3 +- .../got/dist/source/utils/deep-freeze.d.ts | 1 + .../got/dist/source/utils/deep-freeze.js | 12 + .../source/utils/deprecation-warning.d.ts | 2 + .../dist/source/utils/deprecation-warning.js | 13 + setup-pandoc/node_modules/got/license | 2 +- .../got/node_modules/get-stream/license | 9 - .../got/node_modules/get-stream/package.json | 53 - .../got/node_modules/get-stream/readme.md | 291 -- .../get-stream/source/array-buffer.js | 84 - .../node_modules/get-stream/source/array.js | 32 - .../node_modules/get-stream/source/buffer.js | 20 - .../get-stream/source/contents.js | 101 - .../node_modules/get-stream/source/index.d.ts | 119 - .../node_modules/get-stream/source/index.js | 5 - .../node_modules/get-stream/source/string.js | 36 - .../node_modules/get-stream/source/utils.js | 11 - setup-pandoc/node_modules/got/package.json | 137 +- setup-pandoc/node_modules/got/readme.md | 2569 +++++++++++++++-- .../node_modules/http2-wrapper/README.md | 263 +- .../node_modules/http2-wrapper/index.d.ts | 141 - .../node_modules/http2-wrapper/package.json | 55 +- .../http2-wrapper/source/agent.js | 634 ++-- .../node_modules/http2-wrapper/source/auto.js | 210 +- .../http2-wrapper/source/client-request.js | 328 +-- .../http2-wrapper/source/incoming-message.js | 23 +- .../http2-wrapper/source/index.js | 40 +- .../source/proxies/get-auth-headers.js | 17 - .../source/proxies/h1-over-h2.js | 90 - .../source/proxies/h2-over-h1.js | 48 - .../source/proxies/h2-over-h2.js | 32 - .../source/proxies/h2-over-hx.js | 40 - .../source/proxies/initialize.js | 21 - .../proxies/unexpected-status-code-error.js | 11 - .../source/utils/calculate-server-name.js | 36 +- .../http2-wrapper/source/utils/check-type.js | 20 - .../source/utils/delay-async-destroy.js | 33 - .../http2-wrapper/source/utils/errors.js | 44 +- .../source/utils/js-stream-socket.js | 8 - .../source/utils/proxy-socket-handler.js | 102 - .../source/utils/url-to-options.js | 25 + .../source/utils/validate-header-name.js | 11 - .../source/utils/validate-header-value.js | 17 - .../node_modules/lowercase-keys/index.d.ts | 6 +- .../node_modules/lowercase-keys/index.js | 13 +- .../node_modules/lowercase-keys/license | 2 +- .../node_modules/lowercase-keys/package.json | 15 +- .../node_modules/lowercase-keys/readme.md | 16 +- .../node_modules/mimic-response/index.d.ts | 29 - .../node_modules/mimic-response/index.js | 77 +- .../node_modules/mimic-response/license | 2 +- .../node_modules/mimic-response/package.json | 77 +- .../node_modules/mimic-response/readme.md | 48 +- .../node_modules/normalize-url/index.d.ts | 468 ++- .../node_modules/normalize-url/index.js | 156 +- .../node_modules/normalize-url/license | 2 +- .../node_modules/normalize-url/package.json | 21 +- .../node_modules/normalize-url/readme.md | 74 +- .../node_modules/p-cancelable/index.d.ts | 85 +- .../node_modules/p-cancelable/index.js | 100 +- .../node_modules/p-cancelable/license | 2 +- .../node_modules/p-cancelable/package.json | 17 +- .../node_modules/p-cancelable/readme.md | 61 +- .../node_modules/responselike/index.d.ts | 86 - .../node_modules/responselike/license | 23 +- .../node_modules/responselike/package.json | 74 +- .../node_modules/responselike/readme.md | 62 +- .../responselike/{ => src}/index.js | 33 +- setup-pandoc/package-lock.json | 214 +- setup-pandoc/package.json | 3 +- setup-pandoc/tsconfig.json | 2 +- 180 files changed, 8951 insertions(+), 12773 deletions(-) create mode 100755 setup-pandoc/node_modules/@types/cacheable-request/LICENSE create mode 100755 setup-pandoc/node_modules/@types/cacheable-request/README.md create mode 100755 setup-pandoc/node_modules/@types/cacheable-request/index.d.ts create mode 100755 setup-pandoc/node_modules/@types/cacheable-request/package.json create mode 100755 setup-pandoc/node_modules/@types/keyv/LICENSE create mode 100755 setup-pandoc/node_modules/@types/keyv/README.md create mode 100755 setup-pandoc/node_modules/@types/keyv/index.d.ts create mode 100755 setup-pandoc/node_modules/@types/keyv/package.json create mode 100644 setup-pandoc/node_modules/@types/responselike/LICENSE create mode 100644 setup-pandoc/node_modules/@types/responselike/README.md create mode 100644 setup-pandoc/node_modules/@types/responselike/index.d.ts create mode 100644 setup-pandoc/node_modules/@types/responselike/package.json mode change 100644 => 100755 setup-pandoc/node_modules/cacheable-lookup/LICENSE mode change 100644 => 100755 setup-pandoc/node_modules/cacheable-lookup/README.md mode change 100644 => 100755 setup-pandoc/node_modules/cacheable-lookup/index.d.ts mode change 100644 => 100755 setup-pandoc/node_modules/cacheable-lookup/package.json mode change 100644 => 100755 setup-pandoc/node_modules/cacheable-lookup/source/index.js rename setup-pandoc/node_modules/{form-data-encoder/license => cacheable-request/LICENSE} (94%) delete mode 100644 setup-pandoc/node_modules/cacheable-request/dist/index.d.ts delete mode 100644 setup-pandoc/node_modules/cacheable-request/dist/index.d.ts.map delete mode 100644 setup-pandoc/node_modules/cacheable-request/dist/index.js delete mode 100644 setup-pandoc/node_modules/cacheable-request/dist/index.js.map delete mode 100644 setup-pandoc/node_modules/cacheable-request/dist/types.d.ts delete mode 100644 setup-pandoc/node_modules/cacheable-request/dist/types.d.ts.map delete mode 100644 setup-pandoc/node_modules/cacheable-request/dist/types.js delete mode 100644 setup-pandoc/node_modules/cacheable-request/dist/types.js.map create mode 100644 setup-pandoc/node_modules/cacheable-request/src/index.js create mode 100644 setup-pandoc/node_modules/clone-response/LICENSE create mode 100644 setup-pandoc/node_modules/clone-response/README.md create mode 100644 setup-pandoc/node_modules/clone-response/package.json create mode 100644 setup-pandoc/node_modules/clone-response/src/index.js delete mode 100644 setup-pandoc/node_modules/form-data-encoder/lib/index.cjs delete mode 100644 setup-pandoc/node_modules/form-data-encoder/lib/index.d.cts delete mode 100644 setup-pandoc/node_modules/form-data-encoder/lib/index.d.ts delete mode 100644 setup-pandoc/node_modules/form-data-encoder/lib/index.js delete mode 100644 setup-pandoc/node_modules/form-data-encoder/package.json delete mode 100644 setup-pandoc/node_modules/form-data-encoder/readme.md create mode 100644 setup-pandoc/node_modules/got/dist/source/as-promise/create-rejection.d.ts create mode 100644 setup-pandoc/node_modules/got/dist/source/as-promise/create-rejection.js create mode 100644 setup-pandoc/node_modules/got/dist/source/as-promise/normalize-arguments.d.ts create mode 100644 setup-pandoc/node_modules/got/dist/source/as-promise/normalize-arguments.js create mode 100644 setup-pandoc/node_modules/got/dist/source/as-promise/parse-body.d.ts create mode 100644 setup-pandoc/node_modules/got/dist/source/as-promise/parse-body.js delete mode 100644 setup-pandoc/node_modules/got/dist/source/core/errors.d.ts delete mode 100644 setup-pandoc/node_modules/got/dist/source/core/errors.js delete mode 100644 setup-pandoc/node_modules/got/dist/source/core/options.d.ts delete mode 100644 setup-pandoc/node_modules/got/dist/source/core/options.js delete mode 100644 setup-pandoc/node_modules/got/dist/source/core/parse-link-header.d.ts delete mode 100644 setup-pandoc/node_modules/got/dist/source/core/parse-link-header.js delete mode 100644 setup-pandoc/node_modules/got/dist/source/core/response.d.ts delete mode 100644 setup-pandoc/node_modules/got/dist/source/core/response.js delete mode 100644 setup-pandoc/node_modules/got/dist/source/core/timed-out.d.ts delete mode 100644 setup-pandoc/node_modules/got/dist/source/core/timed-out.js create mode 100644 setup-pandoc/node_modules/got/dist/source/core/utils/dns-ip-version.d.ts create mode 100644 setup-pandoc/node_modules/got/dist/source/core/utils/dns-ip-version.js create mode 100644 setup-pandoc/node_modules/got/dist/source/core/utils/get-buffer.d.ts create mode 100644 setup-pandoc/node_modules/got/dist/source/core/utils/get-buffer.js delete mode 100644 setup-pandoc/node_modules/got/dist/source/core/utils/is-client-request.d.ts delete mode 100644 setup-pandoc/node_modules/got/dist/source/core/utils/is-client-request.js create mode 100644 setup-pandoc/node_modules/got/dist/source/core/utils/is-response-ok.d.ts create mode 100644 setup-pandoc/node_modules/got/dist/source/core/utils/is-response-ok.js delete mode 100644 setup-pandoc/node_modules/got/dist/source/core/utils/is-unix-socket-url.d.ts delete mode 100644 setup-pandoc/node_modules/got/dist/source/core/utils/is-unix-socket-url.js create mode 100644 setup-pandoc/node_modules/got/dist/source/core/utils/timed-out.d.ts create mode 100644 setup-pandoc/node_modules/got/dist/source/core/utils/timed-out.js create mode 100644 setup-pandoc/node_modules/got/dist/source/utils/deep-freeze.d.ts create mode 100644 setup-pandoc/node_modules/got/dist/source/utils/deep-freeze.js create mode 100644 setup-pandoc/node_modules/got/dist/source/utils/deprecation-warning.d.ts create mode 100644 setup-pandoc/node_modules/got/dist/source/utils/deprecation-warning.js delete mode 100644 setup-pandoc/node_modules/got/node_modules/get-stream/license delete mode 100644 setup-pandoc/node_modules/got/node_modules/get-stream/package.json delete mode 100644 setup-pandoc/node_modules/got/node_modules/get-stream/readme.md delete mode 100644 setup-pandoc/node_modules/got/node_modules/get-stream/source/array-buffer.js delete mode 100644 setup-pandoc/node_modules/got/node_modules/get-stream/source/array.js delete mode 100644 setup-pandoc/node_modules/got/node_modules/get-stream/source/buffer.js delete mode 100644 setup-pandoc/node_modules/got/node_modules/get-stream/source/contents.js delete mode 100644 setup-pandoc/node_modules/got/node_modules/get-stream/source/index.d.ts delete mode 100644 setup-pandoc/node_modules/got/node_modules/get-stream/source/index.js delete mode 100644 setup-pandoc/node_modules/got/node_modules/get-stream/source/string.js delete mode 100644 setup-pandoc/node_modules/got/node_modules/get-stream/source/utils.js delete mode 100644 setup-pandoc/node_modules/http2-wrapper/index.d.ts delete mode 100644 setup-pandoc/node_modules/http2-wrapper/source/proxies/get-auth-headers.js delete mode 100644 setup-pandoc/node_modules/http2-wrapper/source/proxies/h1-over-h2.js delete mode 100644 setup-pandoc/node_modules/http2-wrapper/source/proxies/h2-over-h1.js delete mode 100644 setup-pandoc/node_modules/http2-wrapper/source/proxies/h2-over-h2.js delete mode 100644 setup-pandoc/node_modules/http2-wrapper/source/proxies/h2-over-hx.js delete mode 100644 setup-pandoc/node_modules/http2-wrapper/source/proxies/initialize.js delete mode 100644 setup-pandoc/node_modules/http2-wrapper/source/proxies/unexpected-status-code-error.js delete mode 100644 setup-pandoc/node_modules/http2-wrapper/source/utils/check-type.js delete mode 100644 setup-pandoc/node_modules/http2-wrapper/source/utils/delay-async-destroy.js delete mode 100644 setup-pandoc/node_modules/http2-wrapper/source/utils/js-stream-socket.js delete mode 100644 setup-pandoc/node_modules/http2-wrapper/source/utils/proxy-socket-handler.js create mode 100644 setup-pandoc/node_modules/http2-wrapper/source/utils/url-to-options.js delete mode 100644 setup-pandoc/node_modules/http2-wrapper/source/utils/validate-header-name.js delete mode 100644 setup-pandoc/node_modules/http2-wrapper/source/utils/validate-header-value.js delete mode 100644 setup-pandoc/node_modules/mimic-response/index.d.ts delete mode 100644 setup-pandoc/node_modules/responselike/index.d.ts rename setup-pandoc/node_modules/responselike/{ => src}/index.js (58%) diff --git a/.github/workflows/setup-pandoc-test.yaml b/.github/workflows/setup-pandoc-test.yaml index 51352d724..3fa92118e 100644 --- a/.github/workflows/setup-pandoc-test.yaml +++ b/.github/workflows/setup-pandoc-test.yaml @@ -10,7 +10,7 @@ on: version: description: | Pandoc version, may be "latest". - required: false + required: true default: '3.1.11' type: string diff --git a/setup-pandoc/node_modules/.package-lock.json b/setup-pandoc/node_modules/.package-lock.json index d6f21dfab..6ff8be41b 100644 --- a/setup-pandoc/node_modules/.package-lock.json +++ b/setup-pandoc/node_modules/.package-lock.json @@ -1299,11 +1299,11 @@ "dev": true }, "node_modules/@sindresorhus/is": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-6.1.0.tgz", - "integrity": "sha512-BuvU07zq3tQ/2SIgBsEuxKYDyDjC0n7Zir52bpHy2xnBbW81+po43aLFPLbeV3HRAheFbGud1qgcqSYfhtHMAg==", + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-4.6.0.tgz", + "integrity": "sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw==", "engines": { - "node": ">=16" + "node": ">=10" }, "funding": { "url": "https://github.com/sindresorhus/is?sponsor=1" @@ -1328,14 +1328,14 @@ } }, "node_modules/@szmarczak/http-timer": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/@szmarczak/http-timer/-/http-timer-5.0.1.tgz", - "integrity": "sha512-+PmQX0PiAYPMeVYe237LJAYvOMYW1j2rH5YROyS3b4CTVJum34HfRvKvAzozHAQG0TnHNdUfY9nCeUyRAs//cw==", + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/@szmarczak/http-timer/-/http-timer-4.0.6.tgz", + "integrity": "sha512-4BAffykYOgO+5nzBWYwE3W90sBgLJoUPRWWcL8wlyiM8IB8ipJz3UMJ9KXQd1RKQXpKp8Tutn80HZtWsu2u76w==", "dependencies": { - "defer-to-connect": "^2.0.1" + "defer-to-connect": "^2.0.0" }, "engines": { - "node": ">=14.16" + "node": ">=10" } }, "node_modules/@types/babel__core": { @@ -1379,6 +1379,17 @@ "@babel/types": "^7.20.7" } }, + "node_modules/@types/cacheable-request": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/@types/cacheable-request/-/cacheable-request-6.0.3.tgz", + "integrity": "sha512-IQ3EbTzGxIigb1I3qPZc1rWJnH0BmSKv5QYTalEwweFvyBDLSAe24zP0le/hyi7ecGfZVlIVAg4BZqb8WBwKqw==", + "dependencies": { + "@types/http-cache-semantics": "*", + "@types/keyv": "^3.1.4", + "@types/node": "*", + "@types/responselike": "^1.0.0" + } + }, "node_modules/@types/graceful-fs": { "version": "4.1.9", "resolved": "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.9.tgz", @@ -1427,11 +1438,18 @@ "pretty-format": "^29.0.0" } }, + "node_modules/@types/keyv": { + "version": "3.1.4", + "resolved": "https://registry.npmjs.org/@types/keyv/-/keyv-3.1.4.tgz", + "integrity": "sha512-BQ5aZNSCpj7D6K2ksrRCTmKRLEpnPvWDiLPfoGyhZ++8YtiK9d/3DBKPJgry359X/P1PfruyYwvnvwFjuEiEIg==", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/node": { "version": "16.18.76", "resolved": "https://registry.npmjs.org/@types/node/-/node-16.18.76.tgz", - "integrity": "sha512-/GsO2uv1Z6R42lBr59dtem56gVF/yHKQaScggwU+gLU6DXE25sDmOar4c4IfWb3h+X/7OYZznPOFk7oGF3jQSA==", - "dev": true + "integrity": "sha512-/GsO2uv1Z6R42lBr59dtem56gVF/yHKQaScggwU+gLU6DXE25sDmOar4c4IfWb3h+X/7OYZznPOFk7oGF3jQSA==" }, "node_modules/@types/normalize-package-data": { "version": "2.4.4", @@ -1439,6 +1457,14 @@ "integrity": "sha512-37i+OaWTh9qeK4LSHPsyRC7NahnGotNuZvjLSgcPzblpHB3rrCJxAOgI5gCdKm7coonsaX1Of0ILiTcnZjbfxA==", "dev": true }, + "node_modules/@types/responselike": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@types/responselike/-/responselike-1.0.3.tgz", + "integrity": "sha512-H/+L+UkTV33uf49PH5pCAUBVPNj2nDBXTN+qS1dOwyyg24l3CcicicCA7ca+HMvJBZcFgl5r8e+RR6elsb4Lyw==", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/stack-utils": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.3.tgz", @@ -1783,36 +1809,39 @@ "dev": true }, "node_modules/cacheable-lookup": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/cacheable-lookup/-/cacheable-lookup-7.0.0.tgz", - "integrity": "sha512-+qJyx4xiKra8mZrcwhjMRMUhD5NR1R8esPkzIYxX96JiecFoxAXFuz/GpR3+ev4PE1WamHip78wV0vcmPQtp8w==", + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/cacheable-lookup/-/cacheable-lookup-5.0.4.tgz", + "integrity": "sha512-2/kNscPhpcxrOigMZzbiWF7dz8ilhb/nIHU3EyZiXWXpeq/au8qJ8VhdftMkty3n7Gj6HIGalQG8oiBNB3AJgA==", "engines": { - "node": ">=14.16" + "node": ">=10.6.0" } }, "node_modules/cacheable-request": { - "version": "10.2.14", - "resolved": "https://registry.npmjs.org/cacheable-request/-/cacheable-request-10.2.14.tgz", - "integrity": "sha512-zkDT5WAF4hSSoUgyfg5tFIxz8XQK+25W/TLVojJTMKBaxevLBBtLxgqguAuVQB8PVW79FVjHcU+GJ9tVbDZ9mQ==", + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/cacheable-request/-/cacheable-request-7.0.4.tgz", + "integrity": "sha512-v+p6ongsrp0yTGbJXjgxPow2+DL93DASP4kXCDKb8/bwRtt9OEF3whggkkDkGNzgcWy2XaF4a8nZglC7uElscg==", "dependencies": { - "@types/http-cache-semantics": "^4.0.2", - "get-stream": "^6.0.1", - "http-cache-semantics": "^4.1.1", - "keyv": "^4.5.3", - "mimic-response": "^4.0.0", - "normalize-url": "^8.0.0", - "responselike": "^3.0.0" + "clone-response": "^1.0.2", + "get-stream": "^5.1.0", + "http-cache-semantics": "^4.0.0", + "keyv": "^4.0.0", + "lowercase-keys": "^2.0.0", + "normalize-url": "^6.0.1", + "responselike": "^2.0.0" }, "engines": { - "node": ">=14.16" + "node": ">=8" } }, "node_modules/cacheable-request/node_modules/get-stream": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", - "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz", + "integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==", + "dependencies": { + "pump": "^3.0.0" + }, "engines": { - "node": ">=10" + "node": ">=8" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" @@ -1929,6 +1958,17 @@ "node": ">=12" } }, + "node_modules/clone-response": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/clone-response/-/clone-response-1.0.3.tgz", + "integrity": "sha512-ROoL94jJH2dUVML2Y/5PEDNaSHgeOdSDicUyS7izcF63G6sTc/FTjLub4b8Il9S8S0beOfYt0TaA5qvFK+w0wA==", + "dependencies": { + "mimic-response": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/co": { "version": "4.6.0", "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", @@ -2227,7 +2267,6 @@ "version": "1.4.4", "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz", "integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==", - "dev": true, "dependencies": { "once": "^1.4.0" } @@ -2355,14 +2394,6 @@ "node": ">=8" } }, - "node_modules/form-data-encoder": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/form-data-encoder/-/form-data-encoder-4.0.2.tgz", - "integrity": "sha512-KQVhvhK8ZkWzxKxOr56CPulAhH3dobtuQ4+hNQ+HekH/Wp5gSOafqRAeTphQUJAIk0GBvHZgJ2ZGRWd5kphMuw==", - "engines": { - "node": ">= 18" - } - }, "node_modules/fs.realpath": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", @@ -2470,40 +2501,29 @@ } }, "node_modules/got": { - "version": "14.2.0", - "resolved": "https://registry.npmjs.org/got/-/got-14.2.0.tgz", - "integrity": "sha512-dBq2KkHcQl3AwPoIWsLsQScCPpUgRulz1qZVthjPYKYOPmYfBnekR3vxecjZbm91Vc3JUGnV9mqFX7B+Fe2quw==", - "dependencies": { - "@sindresorhus/is": "^6.1.0", - "@szmarczak/http-timer": "^5.0.1", - "cacheable-lookup": "^7.0.0", - "cacheable-request": "^10.2.14", + "version": "11.8.6", + "resolved": "https://registry.npmjs.org/got/-/got-11.8.6.tgz", + "integrity": "sha512-6tfZ91bOr7bOXnK7PRDCGBLa1H4U080YHNaAQ2KsMGlLEzRbk44nsZF2E1IeRc3vtJHPVbKCYgdFbaGO2ljd8g==", + "dependencies": { + "@sindresorhus/is": "^4.0.0", + "@szmarczak/http-timer": "^4.0.5", + "@types/cacheable-request": "^6.0.1", + "@types/responselike": "^1.0.0", + "cacheable-lookup": "^5.0.3", + "cacheable-request": "^7.0.2", "decompress-response": "^6.0.0", - "form-data-encoder": "^4.0.2", - "get-stream": "^8.0.1", - "http2-wrapper": "^2.2.1", - "lowercase-keys": "^3.0.0", - "p-cancelable": "^4.0.1", - "responselike": "^3.0.0" + "http2-wrapper": "^1.0.0-beta.5.2", + "lowercase-keys": "^2.0.0", + "p-cancelable": "^2.0.0", + "responselike": "^2.0.0" }, "engines": { - "node": ">=20" + "node": ">=10.19.0" }, "funding": { "url": "https://github.com/sindresorhus/got?sponsor=1" } }, - "node_modules/got/node_modules/get-stream": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-8.0.1.tgz", - "integrity": "sha512-VaUJspBffn/LMCJVoMvSAdmscJyS1auj5Zulnn5UoYcY531UWmdwhRWkcGKnGU93m5HSXP9LP2usOryrBtQowA==", - "engines": { - "node": ">=16" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/graceful-fs": { "version": "4.2.11", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", @@ -2549,12 +2569,12 @@ "integrity": "sha512-er295DKPVsV82j5kw1Gjt+ADA/XYHsajl82cGNQG2eyoPkvgUhX+nDIyelzhIWbbsXP39EHcI6l5tYs2FYqYXQ==" }, "node_modules/http2-wrapper": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/http2-wrapper/-/http2-wrapper-2.2.1.tgz", - "integrity": "sha512-V5nVw1PAOgfI3Lmeaj2Exmeg7fenjhRUgz1lPSezy1CuhPYbgQtbQj4jZfEAEMlaL+vupsvhjqCyjzob0yxsmQ==", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/http2-wrapper/-/http2-wrapper-1.0.3.tgz", + "integrity": "sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg==", "dependencies": { "quick-lru": "^5.1.1", - "resolve-alpn": "^1.2.0" + "resolve-alpn": "^1.0.0" }, "engines": { "node": ">=10.19.0" @@ -4700,14 +4720,11 @@ "dev": true }, "node_modules/lowercase-keys": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-3.0.0.tgz", - "integrity": "sha512-ozCC6gdQ+glXOQsveKD0YsDy8DSQFjDTz4zyzEHNV5+JP5D62LmfDZ6o1cycFx9ouG940M5dE8C8CTewdj2YWQ==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-2.0.0.tgz", + "integrity": "sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA==", "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "node": ">=8" } }, "node_modules/lru-cache": { @@ -4811,14 +4828,11 @@ } }, "node_modules/mimic-response": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-4.0.0.tgz", - "integrity": "sha512-e5ISH9xMYU0DzrT+jl8q2ze9D6eWBto+I8CNpe+VI+K2J/F/k3PdkdTdz4wvGVH4NTpo+NRYTVIuMQEMMcsLqg==", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-1.0.1.tgz", + "integrity": "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ==", "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "node": ">=4" } }, "node_modules/minimatch": { @@ -4894,11 +4908,11 @@ } }, "node_modules/normalize-url": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-8.0.0.tgz", - "integrity": "sha512-uVFpKhj5MheNBJRTiMZ9pE/7hD1QTeEvugSJW/OmLzAp78PB5O6adfMNTvmfKhXBkvCzC+rqifWcVYpGFwTjnw==", + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-6.1.0.tgz", + "integrity": "sha512-DlL+XwOy3NxAQ8xuC0okPgK46iuVNAK01YN7RueYBqqFeGsBjV9XmCAzAdgt+667bCl5kPh9EqKKDwnaPG1I7A==", "engines": { - "node": ">=14.16" + "node": ">=10" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" @@ -4920,7 +4934,6 @@ "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "dev": true, "dependencies": { "wrappy": "1" } @@ -4950,11 +4963,11 @@ } }, "node_modules/p-cancelable": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-4.0.1.tgz", - "integrity": "sha512-wBowNApzd45EIKdO1LaU+LrMBwAcjfPaYtVzV3lmfM3gf8Z4CHZsiIqlM8TZZ8okYvh5A1cP6gTfCRQtwUpaUg==", + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-2.1.1.tgz", + "integrity": "sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg==", "engines": { - "node": ">=14.16" + "node": ">=8" } }, "node_modules/p-finally": { @@ -5166,7 +5179,6 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz", "integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==", - "dev": true, "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" @@ -5318,14 +5330,11 @@ } }, "node_modules/responselike": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/responselike/-/responselike-3.0.0.tgz", - "integrity": "sha512-40yHxbNcl2+rzXvZuVkrYohathsSJlMTXKryG5y8uciHv1+xDLHQpgjG64JUO9nrEq2jGLH6IZ8BcZyw3wrweg==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/responselike/-/responselike-2.0.1.tgz", + "integrity": "sha512-4gl03wn3hj1HP3yzgdI7d3lCkF95F21Pz4BPGvKHinyQzALR5CapwC8yIi0Rh58DEMQ/SguC03wFj2k0M/mHhw==", "dependencies": { - "lowercase-keys": "^3.0.0" - }, - "engines": { - "node": ">=14.16" + "lowercase-keys": "^2.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" @@ -5885,8 +5894,7 @@ "node_modules/wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", - "dev": true + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==" }, "node_modules/write-file-atomic": { "version": "4.0.2", diff --git a/setup-pandoc/node_modules/@sindresorhus/is/dist/index.d.ts b/setup-pandoc/node_modules/@sindresorhus/is/dist/index.d.ts index 2c857bd74..dbb8cbd41 100644 --- a/setup-pandoc/node_modules/@sindresorhus/is/dist/index.d.ts +++ b/setup-pandoc/node_modules/@sindresorhus/is/dist/index.d.ts @@ -1,224 +1,158 @@ -/// -import type { Buffer } from 'node:buffer'; -import type { ArrayLike, Class, Falsy, NodeStream, NonEmptyString, ObservableLike, Predicate, Primitive, TypedArray, WeakRef } from './types.js'; -declare const objectTypeNames: readonly ["Function", "Generator", "AsyncGenerator", "GeneratorFunction", "AsyncGeneratorFunction", "AsyncFunction", "Observable", "Array", "Buffer", "Blob", "Object", "RegExp", "Date", "Error", "Map", "Set", "WeakMap", "WeakSet", "WeakRef", "ArrayBuffer", "SharedArrayBuffer", "DataView", "Promise", "URL", "FormData", "URLSearchParams", "HTMLElement", "NaN", "Int8Array", "Uint8Array", "Uint8ClampedArray", "Int16Array", "Uint16Array", "Int32Array", "Uint32Array", "Float32Array", "Float64Array", "BigInt64Array", "BigUint64Array"]; -type ObjectTypeName = typeof objectTypeNames[number]; +/// +/// +/// +import { Class, Falsy, TypedArray, ObservableLike, Primitive } from './types'; +declare const objectTypeNames: readonly ["Function", "Generator", "AsyncGenerator", "GeneratorFunction", "AsyncGeneratorFunction", "AsyncFunction", "Observable", "Array", "Buffer", "Blob", "Object", "RegExp", "Date", "Error", "Map", "Set", "WeakMap", "WeakSet", "ArrayBuffer", "SharedArrayBuffer", "DataView", "Promise", "URL", "FormData", "URLSearchParams", "HTMLElement", ...("Int8Array" | "Uint8Array" | "Uint8ClampedArray" | "Int16Array" | "Uint16Array" | "Int32Array" | "Uint32Array" | "Float32Array" | "Float64Array" | "BigInt64Array" | "BigUint64Array")[]]; +declare type ObjectTypeName = typeof objectTypeNames[number]; declare const primitiveTypeNames: readonly ["null", "undefined", "string", "number", "bigint", "boolean", "symbol"]; -type PrimitiveTypeName = typeof primitiveTypeNames[number]; -export type TypeName = ObjectTypeName | PrimitiveTypeName; -declare const assertionTypeDescriptions: readonly ["positive number", "negative number", "Class", "string with a number", "null or undefined", "Iterable", "AsyncIterable", "native Promise", "EnumCase", "string with a URL", "truthy", "falsy", "primitive", "integer", "plain object", "TypedArray", "array-like", "tuple-like", "Node.js Stream", "infinite number", "empty array", "non-empty array", "empty string", "empty string or whitespace", "non-empty string", "non-empty string and not whitespace", "empty object", "non-empty object", "empty set", "non-empty set", "empty map", "non-empty map", "PropertyKey", "even integer", "odd integer", "T", "in range", "predicate returns truthy for any value", "predicate returns truthy for all values", "valid length", "whitespace string", "Function", "Generator", "AsyncGenerator", "GeneratorFunction", "AsyncGeneratorFunction", "AsyncFunction", "Observable", "Array", "Buffer", "Blob", "Object", "RegExp", "Date", "Error", "Map", "Set", "WeakMap", "WeakSet", "WeakRef", "ArrayBuffer", "SharedArrayBuffer", "DataView", "Promise", "URL", "FormData", "URLSearchParams", "HTMLElement", "NaN", "Int8Array", "Uint8Array", "Uint8ClampedArray", "Int16Array", "Uint16Array", "Int32Array", "Uint32Array", "Float32Array", "Float64Array", "BigInt64Array", "BigUint64Array", "null", "undefined", "string", "number", "bigint", "boolean", "symbol"]; -export type AssertionTypeDescription = typeof assertionTypeDescriptions[number]; -declare function detect(value: unknown): TypeName; -declare const is: typeof detect & { - all: typeof isAll; - any: typeof isAny; - array: typeof isArray; - arrayBuffer: typeof isArrayBuffer; - arrayLike: typeof isArrayLike; - asyncFunction: typeof isAsyncFunction; - asyncGenerator: typeof isAsyncGenerator; - asyncGeneratorFunction: typeof isAsyncGeneratorFunction; - asyncIterable: typeof isAsyncIterable; - bigint: typeof isBigint; - bigInt64Array: typeof isBigInt64Array; - bigUint64Array: typeof isBigUint64Array; - blob: typeof isBlob; - boolean: typeof isBoolean; - boundFunction: typeof isBoundFunction; - buffer: typeof isBuffer; - class: typeof isClass; - /** @deprecated Renamed to `class`. */ - class_: typeof isClass; - dataView: typeof isDataView; - date: typeof isDate; - detect: typeof detect; - directInstanceOf: typeof isDirectInstanceOf; - /** @deprecated Renamed to `htmlElement` */ - domElement: typeof isHtmlElement; - emptyArray: typeof isEmptyArray; - emptyMap: typeof isEmptyMap; - emptyObject: typeof isEmptyObject; - emptySet: typeof isEmptySet; - emptyString: typeof isEmptyString; - emptyStringOrWhitespace: typeof isEmptyStringOrWhitespace; - enumCase: typeof isEnumCase; - error: typeof isError; - evenInteger: typeof isEvenInteger; - falsy: typeof isFalsy; - float32Array: typeof isFloat32Array; - float64Array: typeof isFloat64Array; - formData: typeof isFormData; - function: typeof isFunction; - /** @deprecated Renamed to `function`. */ - function_: typeof isFunction; - generator: typeof isGenerator; - generatorFunction: typeof isGeneratorFunction; - htmlElement: typeof isHtmlElement; - infinite: typeof isInfinite; - inRange: typeof isInRange; - int16Array: typeof isInt16Array; - int32Array: typeof isInt32Array; - int8Array: typeof isInt8Array; - integer: typeof isInteger; - iterable: typeof isIterable; - map: typeof isMap; - nan: typeof isNan; - nativePromise: typeof isNativePromise; - negativeNumber: typeof isNegativeNumber; - nodeStream: typeof isNodeStream; - nonEmptyArray: typeof isNonEmptyArray; - nonEmptyMap: typeof isNonEmptyMap; - nonEmptyObject: typeof isNonEmptyObject; - nonEmptySet: typeof isNonEmptySet; - nonEmptyString: typeof isNonEmptyString; - nonEmptyStringAndNotWhitespace: typeof isNonEmptyStringAndNotWhitespace; - null: typeof isNull; - /** @deprecated Renamed to `null`. */ - null_: typeof isNull; - nullOrUndefined: typeof isNullOrUndefined; - number: typeof isNumber; - numericString: typeof isNumericString; - object: typeof isObject; - observable: typeof isObservable; - oddInteger: typeof isOddInteger; - plainObject: typeof isPlainObject; - positiveNumber: typeof isPositiveNumber; - primitive: typeof isPrimitive; - promise: typeof isPromise; - propertyKey: typeof isPropertyKey; - regExp: typeof isRegExp; - safeInteger: typeof isSafeInteger; - set: typeof isSet; - sharedArrayBuffer: typeof isSharedArrayBuffer; - string: typeof isString; - symbol: typeof isSymbol; - truthy: typeof isTruthy; - tupleLike: typeof isTupleLike; - typedArray: typeof isTypedArray; - uint16Array: typeof isUint16Array; - uint32Array: typeof isUint32Array; - uint8Array: typeof isUint8Array; - uint8ClampedArray: typeof isUint8ClampedArray; - undefined: typeof isUndefined; - urlInstance: typeof isUrlInstance; - urlSearchParams: typeof isUrlSearchParams; - urlString: typeof isUrlString; - validLength: typeof isValidLength; - weakMap: typeof isWeakMap; - weakRef: typeof isWeakRef; - weakSet: typeof isWeakSet; - whitespaceString: typeof isWhitespaceString; -}; -export declare function isAll(predicate: Predicate, ...values: unknown[]): boolean; -export declare function isAny(predicate: Predicate | Predicate[], ...values: unknown[]): boolean; -export declare function isArray(value: unknown, assertion?: (value: T) => value is T): value is T[]; -export declare function isArrayBuffer(value: unknown): value is ArrayBuffer; -export declare function isArrayLike(value: unknown): value is ArrayLike; -export declare function isAsyncFunction(value: unknown): value is ((...args: any[]) => Promise); -export declare function isAsyncGenerator(value: unknown): value is AsyncGenerator; -export declare function isAsyncGeneratorFunction(value: unknown): value is ((...args: any[]) => Promise); -export declare function isAsyncIterable(value: unknown): value is AsyncIterable; -export declare function isBigint(value: unknown): value is bigint; -export declare function isBigInt64Array(value: unknown): value is BigInt64Array; -export declare function isBigUint64Array(value: unknown): value is BigUint64Array; -export declare function isBlob(value: unknown): value is Blob; -export declare function isBoolean(value: unknown): value is boolean; -export declare function isBoundFunction(value: unknown): value is Function; -export declare function isBuffer(value: unknown): value is Buffer; -export declare function isClass(value: unknown): value is Class; -export declare function isDataView(value: unknown): value is DataView; -export declare function isDate(value: unknown): value is Date; -export declare function isDirectInstanceOf(instance: unknown, class_: Class): instance is T; -export declare function isEmptyArray(value: unknown): value is never[]; -export declare function isEmptyMap(value: unknown): value is Map; -export declare function isEmptyObject(value: unknown): value is Record; -export declare function isEmptySet(value: unknown): value is Set; -export declare function isEmptyString(value: unknown): value is ''; -export declare function isEmptyStringOrWhitespace(value: unknown): value is string; -export declare function isEnumCase(value: unknown, targetEnum: T): boolean; -export declare function isError(value: unknown): value is Error; -export declare function isEvenInteger(value: unknown): value is number; -export declare function isFalsy(value: unknown): value is Falsy; -export declare function isFloat32Array(value: unknown): value is Float32Array; -export declare function isFloat64Array(value: unknown): value is Float64Array; -export declare function isFormData(value: unknown): value is FormData; -export declare function isFunction(value: unknown): value is Function; -export declare function isGenerator(value: unknown): value is Generator; -export declare function isGeneratorFunction(value: unknown): value is GeneratorFunction; -export declare function isHtmlElement(value: unknown): value is HTMLElement; -export declare function isInfinite(value: unknown): value is number; -export declare function isInRange(value: number, range: number | [number, number]): value is number; -export declare function isInt16Array(value: unknown): value is Int16Array; -export declare function isInt32Array(value: unknown): value is Int32Array; -export declare function isInt8Array(value: unknown): value is Int8Array; -export declare function isInteger(value: unknown): value is number; -export declare function isIterable(value: unknown): value is Iterable; -export declare function isMap(value: unknown): value is Map; -export declare function isNan(value: unknown): boolean; -export declare function isNativePromise(value: unknown): value is Promise; -export declare function isNegativeNumber(value: unknown): value is number; -export declare function isNodeStream(value: unknown): value is NodeStream; -export declare function isNonEmptyArray(value: T | Item[]): value is [Item, ...Item[]]; -export declare function isNonEmptyMap(value: unknown): value is Map; -export declare function isNonEmptyObject(value: unknown): value is Record; -export declare function isNonEmptySet(value: unknown): value is Set; -export declare function isNonEmptyString(value: unknown): value is NonEmptyString; -export declare function isNonEmptyStringAndNotWhitespace(value: unknown): value is NonEmptyString; -export declare function isNull(value: unknown): value is null; -export declare function isNullOrUndefined(value: unknown): value is null | undefined; -export declare function isNumber(value: unknown): value is number; -export declare function isNumericString(value: unknown): value is `${number}`; -export declare function isObject(value: unknown): value is object; -export declare function isObservable(value: unknown): value is ObservableLike; -export declare function isOddInteger(value: unknown): value is number; -export declare function isPlainObject(value: unknown): value is Record; -export declare function isPositiveNumber(value: unknown): value is number; -export declare function isPrimitive(value: unknown): value is Primitive; -export declare function isPromise(value: unknown): value is Promise; -export declare function isPropertyKey(value: unknown): value is PropertyKey; -export declare function isRegExp(value: unknown): value is RegExp; -export declare function isSafeInteger(value: unknown): value is number; -export declare function isSet(value: unknown): value is Set; -export declare function isSharedArrayBuffer(value: unknown): value is SharedArrayBuffer; -export declare function isString(value: unknown): value is string; -export declare function isSymbol(value: unknown): value is symbol; -export declare function isTruthy(value: T | Falsy): value is T; -type TypeGuard = (value: unknown) => value is T; -type ResolveTypesOfTypeGuardsTuple = TypeGuardsOfT extends [TypeGuard, ...infer TOthers] ? ResolveTypesOfTypeGuardsTuple : TypeGuardsOfT extends undefined[] ? ResultOfT : never; -export declare function isTupleLike>>(value: unknown, guards: [...T]): value is ResolveTypesOfTypeGuardsTuple; -export declare function isTypedArray(value: unknown): value is TypedArray; -export declare function isUint16Array(value: unknown): value is Uint16Array; -export declare function isUint32Array(value: unknown): value is Uint32Array; -export declare function isUint8Array(value: unknown): value is Uint8Array; -export declare function isUint8ClampedArray(value: unknown): value is Uint8ClampedArray; -export declare function isUndefined(value: unknown): value is undefined; -export declare function isUrlInstance(value: unknown): value is URL; -export declare function isUrlSearchParams(value: unknown): value is URLSearchParams; -export declare function isUrlString(value: unknown): value is string; -export declare function isValidLength(value: unknown): value is number; -export declare function isWeakMap(value: unknown): value is WeakMap; -export declare function isWeakRef(value: unknown): value is WeakRef; -export declare function isWeakSet(value: unknown): value is WeakSet; -export declare function isWhitespaceString(value: unknown): value is string; -type Assert = { +declare type PrimitiveTypeName = typeof primitiveTypeNames[number]; +export declare type TypeName = ObjectTypeName | PrimitiveTypeName; +declare function is(value: unknown): TypeName; +declare namespace is { + var undefined: (value: unknown) => value is undefined; + var string: (value: unknown) => value is string; + var number: (value: unknown) => value is number; + var bigint: (value: unknown) => value is bigint; + var function_: (value: unknown) => value is Function; + var null_: (value: unknown) => value is null; + var class_: (value: unknown) => value is Class; + var boolean: (value: unknown) => value is boolean; + var symbol: (value: unknown) => value is symbol; + var numericString: (value: unknown) => value is string; + var array: (value: unknown, assertion?: ((value: T) => value is T) | undefined) => value is T[]; + var buffer: (value: unknown) => value is Buffer; + var blob: (value: unknown) => value is Blob; + var nullOrUndefined: (value: unknown) => value is null | undefined; + var object: (value: unknown) => value is object; + var iterable: (value: unknown) => value is Iterable; + var asyncIterable: (value: unknown) => value is AsyncIterable; + var generator: (value: unknown) => value is Generator; + var asyncGenerator: (value: unknown) => value is AsyncGenerator; + var nativePromise: (value: unknown) => value is Promise; + var promise: (value: unknown) => value is Promise; + var generatorFunction: (value: unknown) => value is GeneratorFunction; + var asyncGeneratorFunction: (value: unknown) => value is (...args: any[]) => Promise; + var asyncFunction: (value: unknown) => value is (...args: any[]) => Promise; + var boundFunction: (value: unknown) => value is Function; + var regExp: (value: unknown) => value is RegExp; + var date: (value: unknown) => value is Date; + var error: (value: unknown) => value is Error; + var map: (value: unknown) => value is Map; + var set: (value: unknown) => value is Set; + var weakMap: (value: unknown) => value is WeakMap; + var weakSet: (value: unknown) => value is WeakSet; + var int8Array: (value: unknown) => value is Int8Array; + var uint8Array: (value: unknown) => value is Uint8Array; + var uint8ClampedArray: (value: unknown) => value is Uint8ClampedArray; + var int16Array: (value: unknown) => value is Int16Array; + var uint16Array: (value: unknown) => value is Uint16Array; + var int32Array: (value: unknown) => value is Int32Array; + var uint32Array: (value: unknown) => value is Uint32Array; + var float32Array: (value: unknown) => value is Float32Array; + var float64Array: (value: unknown) => value is Float64Array; + var bigInt64Array: (value: unknown) => value is BigInt64Array; + var bigUint64Array: (value: unknown) => value is BigUint64Array; + var arrayBuffer: (value: unknown) => value is ArrayBuffer; + var sharedArrayBuffer: (value: unknown) => value is SharedArrayBuffer; + var dataView: (value: unknown) => value is DataView; + var enumCase: (value: unknown, targetEnum: T) => boolean; + var directInstanceOf: (instance: unknown, class_: Class) => instance is T; + var urlInstance: (value: unknown) => value is URL; + var urlString: (value: unknown) => value is string; + var truthy: (value: false | "" | 0 | 0n | T | null | undefined) => value is T; + var falsy: (value: false | "" | 0 | 0n | T | null | undefined) => value is Falsy; + var nan: (value: unknown) => boolean; + var primitive: (value: unknown) => value is Primitive; + var integer: (value: unknown) => value is number; + var safeInteger: (value: unknown) => value is number; + var plainObject: (value: unknown) => value is Record; + var typedArray: (value: unknown) => value is TypedArray; + var arrayLike: (value: unknown) => value is ArrayLike; + var inRange: (value: number, range: number | number[]) => value is number; + var domElement: (value: unknown) => value is HTMLElement; + var observable: (value: unknown) => value is ObservableLike; + var nodeStream: (value: unknown) => value is NodeStream; + var infinite: (value: unknown) => value is number; + var evenInteger: (value: number) => value is number; + var oddInteger: (value: number) => value is number; + var emptyArray: (value: unknown) => value is never[]; + var nonEmptyArray: (value: unknown) => value is unknown[]; + var emptyString: (value: unknown) => value is ""; + var emptyStringOrWhitespace: (value: unknown) => value is string; + var nonEmptyString: (value: unknown) => value is string; + var nonEmptyStringAndNotWhitespace: (value: unknown) => value is string; + var emptyObject: (value: unknown) => value is Record; + var nonEmptyObject: (value: unknown) => value is Record; + var emptySet: (value: unknown) => value is Set; + var nonEmptySet: (value: unknown) => value is Set; + var emptyMap: (value: unknown) => value is Map; + var nonEmptyMap: (value: unknown) => value is Map; + var propertyKey: (value: unknown) => value is string | number | symbol; + var formData: (value: unknown) => value is FormData; + var urlSearchParams: (value: unknown) => value is URLSearchParams; + var any: (predicate: Predicate | Predicate[], ...values: unknown[]) => boolean; + var all: (predicate: Predicate, ...values: unknown[]) => boolean; +} +export interface ArrayLike { + readonly [index: number]: T; + readonly length: number; +} +export interface NodeStream extends NodeJS.EventEmitter { + pipe(destination: T, options?: { + end?: boolean; + }): T; +} +export declare type Predicate = (value: unknown) => boolean; +export declare const enum AssertionTypeDescription { + class_ = "Class", + numericString = "string with a number", + nullOrUndefined = "null or undefined", + iterable = "Iterable", + asyncIterable = "AsyncIterable", + nativePromise = "native Promise", + urlString = "string with a URL", + truthy = "truthy", + falsy = "falsy", + nan = "NaN", + primitive = "primitive", + integer = "integer", + safeInteger = "integer", + plainObject = "plain object", + arrayLike = "array-like", + typedArray = "TypedArray", + domElement = "HTMLElement", + nodeStream = "Node.js Stream", + infinite = "infinite number", + emptyArray = "empty array", + nonEmptyArray = "non-empty array", + emptyString = "empty string", + emptyStringOrWhitespace = "empty string or whitespace", + nonEmptyString = "non-empty string", + nonEmptyStringAndNotWhitespace = "non-empty string and not whitespace", + emptyObject = "empty object", + nonEmptyObject = "non-empty object", + emptySet = "empty set", + nonEmptySet = "non-empty set", + emptyMap = "empty map", + nonEmptyMap = "non-empty map", + evenInteger = "even integer", + oddInteger = "odd integer", + directInstanceOf = "T", + inRange = "in range", + any = "predicate returns truthy for any value", + all = "predicate returns truthy for all values" +} +interface Assert { undefined: (value: unknown) => asserts value is undefined; string: (value: unknown) => asserts value is string; number: (value: unknown) => asserts value is number; - positiveNumber: (value: unknown) => asserts value is number; - negativeNumber: (value: unknown) => asserts value is number; bigint: (value: unknown) => asserts value is bigint; - function: (value: unknown) => asserts value is Function; - /** @deprecated Renamed to `function`. */ function_: (value: unknown) => asserts value is Function; - null: (value: unknown) => asserts value is null; - /** @deprecated Renamed to `null`. */ null_: (value: unknown) => asserts value is null; - class: (value: unknown) => asserts value is Class; - /** @deprecated Renamed to `class`. */ class_: (value: unknown) => asserts value is Class; boolean: (value: unknown) => asserts value is boolean; symbol: (value: unknown) => asserts value is symbol; - numericString: (value: unknown) => asserts value is `${number}`; + numericString: (value: unknown) => asserts value is string; array: (value: unknown, assertion?: (element: unknown) => asserts element is T) => asserts value is T[]; buffer: (value: unknown) => asserts value is Buffer; blob: (value: unknown) => asserts value is Blob; @@ -241,7 +175,6 @@ type Assert = { set: (value: unknown) => asserts value is Set; weakMap: (value: unknown) => asserts value is WeakMap; weakSet: (value: unknown) => asserts value is WeakSet; - weakRef: (value: unknown) => asserts value is WeakRef; int8Array: (value: unknown) => asserts value is Int8Array; uint8Array: (value: unknown) => asserts value is Uint8Array; uint8ClampedArray: (value: unknown) => asserts value is Uint8ClampedArray; @@ -259,24 +192,21 @@ type Assert = { enumCase: (value: unknown, targetEnum: T) => asserts value is T[keyof T]; urlInstance: (value: unknown) => asserts value is URL; urlString: (value: unknown) => asserts value is string; - truthy: (value: T | Falsy) => asserts value is T; - falsy: (value: unknown) => asserts value is Falsy; - nan: (value: unknown) => asserts value is number; + truthy: (value: unknown) => asserts value is unknown; + falsy: (value: unknown) => asserts value is unknown; + nan: (value: unknown) => asserts value is unknown; primitive: (value: unknown) => asserts value is Primitive; integer: (value: unknown) => asserts value is number; safeInteger: (value: unknown) => asserts value is number; plainObject: (value: unknown) => asserts value is Record; typedArray: (value: unknown) => asserts value is TypedArray; arrayLike: (value: unknown) => asserts value is ArrayLike; - tupleLike: >>(value: unknown, guards: [...T]) => asserts value is ResolveTypesOfTypeGuardsTuple; - /** @deprecated Renamed to `htmlElement` */ domElement: (value: unknown) => asserts value is HTMLElement; - htmlElement: (value: unknown) => asserts value is HTMLElement; observable: (value: unknown) => asserts value is ObservableLike; nodeStream: (value: unknown) => asserts value is NodeStream; infinite: (value: unknown) => asserts value is number; emptyArray: (value: unknown) => asserts value is never[]; - nonEmptyArray: (value: T | Item[]) => asserts value is [Item, ...Item[]]; + nonEmptyArray: (value: unknown) => asserts value is unknown[]; emptyString: (value: unknown) => asserts value is ''; emptyStringOrWhitespace: (value: unknown) => asserts value is string; nonEmptyString: (value: unknown) => asserts value is string; @@ -290,104 +220,13 @@ type Assert = { propertyKey: (value: unknown) => asserts value is PropertyKey; formData: (value: unknown) => asserts value is FormData; urlSearchParams: (value: unknown) => asserts value is URLSearchParams; - validLength: (value: unknown) => asserts value is number; - whitespaceString: (value: unknown) => asserts value is string; evenInteger: (value: number) => asserts value is number; oddInteger: (value: number) => asserts value is number; directInstanceOf: (instance: unknown, class_: Class) => asserts instance is T; - inRange: (value: number, range: number | [number, number]) => asserts value is number; + inRange: (value: number, range: number | number[]) => asserts value is number; any: (predicate: Predicate | Predicate[], ...values: unknown[]) => void | never; all: (predicate: Predicate, ...values: unknown[]) => void | never; -}; +} export declare const assert: Assert; -export declare function assertAll(predicate: Predicate, ...values: unknown[]): void | never; -export declare function assertAny(predicate: Predicate | Predicate[], ...values: unknown[]): void | never; -export declare function assertArray(value: unknown, assertion?: (element: unknown) => asserts element is T): asserts value is T[]; -export declare function assertArrayBuffer(value: unknown): asserts value is ArrayBuffer; -export declare function assertArrayLike(value: unknown): asserts value is ArrayLike; -export declare function assertAsyncFunction(value: unknown): asserts value is Function; -export declare function assertAsyncGenerator(value: unknown): asserts value is AsyncGenerator; -export declare function assertAsyncGeneratorFunction(value: unknown): asserts value is AsyncGeneratorFunction; -export declare function assertAsyncIterable(value: unknown): asserts value is AsyncIterable; -export declare function assertBigint(value: unknown): asserts value is bigint; -export declare function assertBigInt64Array(value: unknown): asserts value is BigInt64Array; -export declare function assertBigUint64Array(value: unknown): asserts value is BigUint64Array; -export declare function assertBlob(value: unknown): asserts value is Blob; -export declare function assertBoolean(value: unknown): asserts value is boolean; -export declare function assertBoundFunction(value: unknown): asserts value is Function; -export declare function assertBuffer(value: unknown): asserts value is Buffer; -export declare function assertClass(value: unknown): asserts value is Class; -export declare function assertDataView(value: unknown): asserts value is DataView; -export declare function assertDate(value: unknown): asserts value is Date; -export declare function assertDirectInstanceOf(instance: unknown, class_: Class): asserts instance is T; -export declare function assertEmptyArray(value: unknown): asserts value is never[]; -export declare function assertEmptyMap(value: unknown): asserts value is Map; -export declare function assertEmptyObject(value: unknown): asserts value is Record; -export declare function assertEmptySet(value: unknown): asserts value is Set; -export declare function assertEmptyString(value: unknown): asserts value is ''; -export declare function assertEmptyStringOrWhitespace(value: unknown): asserts value is string; -export declare function assertEnumCase(value: unknown, targetEnum: T): asserts value is T[keyof T]; -export declare function assertError(value: unknown): asserts value is Error; -export declare function assertEvenInteger(value: number): asserts value is number; -export declare function assertFalsy(value: unknown): asserts value is Falsy; -export declare function assertFloat32Array(value: unknown): asserts value is Float32Array; -export declare function assertFloat64Array(value: unknown): asserts value is Float64Array; -export declare function assertFormData(value: unknown): asserts value is FormData; -export declare function assertFunction(value: unknown): asserts value is Function; -export declare function assertGenerator(value: unknown): asserts value is Generator; -export declare function assertGeneratorFunction(value: unknown): asserts value is GeneratorFunction; -export declare function assertHtmlElement(value: unknown): asserts value is HTMLElement; -export declare function assertInfinite(value: unknown): asserts value is number; -export declare function assertInRange(value: number, range: number | [number, number]): asserts value is number; -export declare function assertInt16Array(value: unknown): asserts value is Int16Array; -export declare function assertInt32Array(value: unknown): asserts value is Int32Array; -export declare function assertInt8Array(value: unknown): asserts value is Int8Array; -export declare function assertInteger(value: unknown): asserts value is number; -export declare function assertIterable(value: unknown): asserts value is Iterable; -export declare function assertMap(value: unknown): asserts value is Map; -export declare function assertNan(value: unknown): asserts value is number; -export declare function assertNativePromise(value: unknown): asserts value is Promise; -export declare function assertNegativeNumber(value: unknown): asserts value is number; -export declare function assertNodeStream(value: unknown): asserts value is NodeStream; -export declare function assertNonEmptyArray(value: T | Item[]): asserts value is [Item, ...Item[]]; -export declare function assertNonEmptyMap(value: unknown): asserts value is Map; -export declare function assertNonEmptyObject(value: unknown): asserts value is Record; -export declare function assertNonEmptySet(value: unknown): asserts value is Set; -export declare function assertNonEmptyString(value: unknown): asserts value is string; -export declare function assertNonEmptyStringAndNotWhitespace(value: unknown): asserts value is string; -export declare function assertNull(value: unknown): asserts value is null; -export declare function assertNullOrUndefined(value: unknown): asserts value is null | undefined; -export declare function assertNumber(value: unknown): asserts value is number; -export declare function assertNumericString(value: unknown): asserts value is `${number}`; -export declare function assertObject(value: unknown): asserts value is object; -export declare function assertObservable(value: unknown): asserts value is ObservableLike; -export declare function assertOddInteger(value: number): asserts value is number; -export declare function assertPlainObject(value: unknown): asserts value is Record; -export declare function assertPositiveNumber(value: unknown): asserts value is number; -export declare function assertPrimitive(value: unknown): asserts value is Primitive; -export declare function assertPromise(value: unknown): asserts value is Promise; -export declare function assertPropertyKey(value: unknown): asserts value is number; -export declare function assertRegExp(value: unknown): asserts value is RegExp; -export declare function assertSafeInteger(value: unknown): asserts value is number; -export declare function assertSet(value: unknown): asserts value is Set; -export declare function assertSharedArrayBuffer(value: unknown): asserts value is SharedArrayBuffer; -export declare function assertString(value: unknown): asserts value is string; -export declare function assertSymbol(value: unknown): asserts value is symbol; -export declare function assertTruthy(value: T | Falsy): asserts value is T; -export declare function assertTupleLike>>(value: unknown, guards: [...T]): asserts value is ResolveTypesOfTypeGuardsTuple; -export declare function assertTypedArray(value: unknown): asserts value is TypedArray; -export declare function assertUint16Array(value: unknown): asserts value is Uint16Array; -export declare function assertUint32Array(value: unknown): asserts value is Uint32Array; -export declare function assertUint8Array(value: unknown): asserts value is Uint8Array; -export declare function assertUint8ClampedArray(value: unknown): asserts value is Uint8ClampedArray; -export declare function assertUndefined(value: unknown): asserts value is undefined; -export declare function assertUrlInstance(value: unknown): asserts value is URL; -export declare function assertUrlSearchParams(value: unknown): asserts value is URLSearchParams; -export declare function assertUrlString(value: unknown): asserts value is string; -export declare function assertValidLength(value: unknown): asserts value is number; -export declare function assertWeakMap(value: unknown): asserts value is WeakMap; -export declare function assertWeakRef(value: unknown): asserts value is WeakRef; -export declare function assertWeakSet(value: unknown): asserts value is WeakSet; -export declare function assertWhitespaceString(value: unknown): asserts value is string; export default is; -export type { ArrayLike, Class, NodeStream, ObservableLike, Predicate, Primitive, TypedArray, } from './types.js'; +export { Class, TypedArray, ObservableLike, Primitive } from './types'; diff --git a/setup-pandoc/node_modules/@sindresorhus/is/dist/index.js b/setup-pandoc/node_modules/@sindresorhus/is/dist/index.js index 36b478a8a..a80df8730 100644 --- a/setup-pandoc/node_modules/@sindresorhus/is/dist/index.js +++ b/setup-pandoc/node_modules/@sindresorhus/is/dist/index.js @@ -1,3 +1,8 @@ +"use strict"; +/// +/// +/// +Object.defineProperty(exports, "__esModule", { value: true }); const typedArrayTypeNames = [ 'Int8Array', 'Uint8Array', @@ -9,7 +14,7 @@ const typedArrayTypeNames = [ 'Float32Array', 'Float64Array', 'BigInt64Array', - 'BigUint64Array', + 'BigUint64Array' ]; function isTypedArrayName(name) { return typedArrayTypeNames.includes(name); @@ -33,7 +38,6 @@ const objectTypeNames = [ 'Set', 'WeakMap', 'WeakSet', - 'WeakRef', 'ArrayBuffer', 'SharedArrayBuffer', 'DataView', @@ -42,8 +46,7 @@ const objectTypeNames = [ 'FormData', 'URLSearchParams', 'HTMLElement', - 'NaN', - ...typedArrayTypeNames, + ...typedArrayTypeNames ]; function isObjectTypeName(name) { return objectTypeNames.includes(name); @@ -55,59 +58,19 @@ const primitiveTypeNames = [ 'number', 'bigint', 'boolean', - 'symbol', + 'symbol' ]; function isPrimitiveTypeName(name) { return primitiveTypeNames.includes(name); } -const assertionTypeDescriptions = [ - 'positive number', - 'negative number', - 'Class', - 'string with a number', - 'null or undefined', - 'Iterable', - 'AsyncIterable', - 'native Promise', - 'EnumCase', - 'string with a URL', - 'truthy', - 'falsy', - 'primitive', - 'integer', - 'plain object', - 'TypedArray', - 'array-like', - 'tuple-like', - 'Node.js Stream', - 'infinite number', - 'empty array', - 'non-empty array', - 'empty string', - 'empty string or whitespace', - 'non-empty string', - 'non-empty string and not whitespace', - 'empty object', - 'non-empty object', - 'empty set', - 'non-empty set', - 'empty map', - 'non-empty map', - 'PropertyKey', - 'even integer', - 'odd integer', - 'T', - 'in range', - 'predicate returns truthy for any value', - 'predicate returns truthy for all values', - 'valid length', - 'whitespace string', - ...objectTypeNames, - ...primitiveTypeNames, -]; +// eslint-disable-next-line @typescript-eslint/ban-types +function isOfType(type) { + return (value) => typeof value === type; +} +const { toString } = Object.prototype; const getObjectType = (value) => { - const objectTypeName = Object.prototype.toString.call(value).slice(8, -1); - if (/HTML\w+Element/.test(objectTypeName) && isHtmlElement(value)) { + const objectTypeName = toString.call(value).slice(8, -1); + if (/HTML\w+Element/.test(objectTypeName) && is.domElement(value)) { return 'HTMLElement'; } if (isObjectTypeName(objectTypeName)) { @@ -115,41 +78,35 @@ const getObjectType = (value) => { } return undefined; }; -function detect(value) { +const isObjectOfType = (type) => (value) => getObjectType(value) === type; +function is(value) { if (value === null) { return 'null'; } switch (typeof value) { - case 'undefined': { + case 'undefined': return 'undefined'; - } - case 'string': { + case 'string': return 'string'; - } - case 'number': { - return Number.isNaN(value) ? 'NaN' : 'number'; - } - case 'boolean': { + case 'number': + return 'number'; + case 'boolean': return 'boolean'; - } - case 'function': { + case 'function': return 'Function'; - } - case 'bigint': { + case 'bigint': return 'bigint'; - } - case 'symbol': { + case 'symbol': return 'symbol'; - } default: } - if (isObservable(value)) { + if (is.observable(value)) { return 'Observable'; } - if (isArray(value)) { + if (is.array(value)) { return 'Array'; } - if (isBuffer(value)) { + if (is.buffer(value)) { return 'Buffer'; } const tagType = getObjectType(value); @@ -161,1134 +118,317 @@ function detect(value) { } return 'Object'; } -function hasPromiseApi(value) { - return isFunction(value?.then) && isFunction(value?.catch); -} -const is = Object.assign(detect, { - all: isAll, - any: isAny, - array: isArray, - arrayBuffer: isArrayBuffer, - arrayLike: isArrayLike, - asyncFunction: isAsyncFunction, - asyncGenerator: isAsyncGenerator, - asyncGeneratorFunction: isAsyncGeneratorFunction, - asyncIterable: isAsyncIterable, - bigint: isBigint, - bigInt64Array: isBigInt64Array, - bigUint64Array: isBigUint64Array, - blob: isBlob, - boolean: isBoolean, - boundFunction: isBoundFunction, - buffer: isBuffer, - class: isClass, - /** @deprecated Renamed to `class`. */ - class_: isClass, - dataView: isDataView, - date: isDate, - detect, - directInstanceOf: isDirectInstanceOf, - /** @deprecated Renamed to `htmlElement` */ - domElement: isHtmlElement, - emptyArray: isEmptyArray, - emptyMap: isEmptyMap, - emptyObject: isEmptyObject, - emptySet: isEmptySet, - emptyString: isEmptyString, - emptyStringOrWhitespace: isEmptyStringOrWhitespace, - enumCase: isEnumCase, - error: isError, - evenInteger: isEvenInteger, - falsy: isFalsy, - float32Array: isFloat32Array, - float64Array: isFloat64Array, - formData: isFormData, - function: isFunction, - /** @deprecated Renamed to `function`. */ - function_: isFunction, - generator: isGenerator, - generatorFunction: isGeneratorFunction, - htmlElement: isHtmlElement, - infinite: isInfinite, - inRange: isInRange, - int16Array: isInt16Array, - int32Array: isInt32Array, - int8Array: isInt8Array, - integer: isInteger, - iterable: isIterable, - map: isMap, - nan: isNan, - nativePromise: isNativePromise, - negativeNumber: isNegativeNumber, - nodeStream: isNodeStream, - nonEmptyArray: isNonEmptyArray, - nonEmptyMap: isNonEmptyMap, - nonEmptyObject: isNonEmptyObject, - nonEmptySet: isNonEmptySet, - nonEmptyString: isNonEmptyString, - nonEmptyStringAndNotWhitespace: isNonEmptyStringAndNotWhitespace, - null: isNull, - /** @deprecated Renamed to `null`. */ - null_: isNull, - nullOrUndefined: isNullOrUndefined, - number: isNumber, - numericString: isNumericString, - object: isObject, - observable: isObservable, - oddInteger: isOddInteger, - plainObject: isPlainObject, - positiveNumber: isPositiveNumber, - primitive: isPrimitive, - promise: isPromise, - propertyKey: isPropertyKey, - regExp: isRegExp, - safeInteger: isSafeInteger, - set: isSet, - sharedArrayBuffer: isSharedArrayBuffer, - string: isString, - symbol: isSymbol, - truthy: isTruthy, - tupleLike: isTupleLike, - typedArray: isTypedArray, - uint16Array: isUint16Array, - uint32Array: isUint32Array, - uint8Array: isUint8Array, - uint8ClampedArray: isUint8ClampedArray, - undefined: isUndefined, - urlInstance: isUrlInstance, - urlSearchParams: isUrlSearchParams, - urlString: isUrlString, - validLength: isValidLength, - weakMap: isWeakMap, - weakRef: isWeakRef, - weakSet: isWeakSet, - whitespaceString: isWhitespaceString, -}); -function isAbsoluteMod2(remainder) { - return (value) => isInteger(value) && Math.abs(value % 2) === remainder; -} -export function isAll(predicate, ...values) { - return predicateOnArray(Array.prototype.every, predicate, values); -} -export function isAny(predicate, ...values) { - const predicates = isArray(predicate) ? predicate : [predicate]; - return predicates.some(singlePredicate => predicateOnArray(Array.prototype.some, singlePredicate, values)); -} -export function isArray(value, assertion) { +is.undefined = isOfType('undefined'); +is.string = isOfType('string'); +const isNumberType = isOfType('number'); +is.number = (value) => isNumberType(value) && !is.nan(value); +is.bigint = isOfType('bigint'); +// eslint-disable-next-line @typescript-eslint/ban-types +is.function_ = isOfType('function'); +is.null_ = (value) => value === null; +is.class_ = (value) => is.function_(value) && value.toString().startsWith('class '); +is.boolean = (value) => value === true || value === false; +is.symbol = isOfType('symbol'); +is.numericString = (value) => is.string(value) && !is.emptyStringOrWhitespace(value) && !Number.isNaN(Number(value)); +is.array = (value, assertion) => { if (!Array.isArray(value)) { return false; } - if (!isFunction(assertion)) { + if (!is.function_(assertion)) { return true; } - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument - return value.every(element => assertion(element)); -} -export function isArrayBuffer(value) { - return getObjectType(value) === 'ArrayBuffer'; -} -export function isArrayLike(value) { - return !isNullOrUndefined(value) && !isFunction(value) && isValidLength(value.length); -} -export function isAsyncFunction(value) { - return getObjectType(value) === 'AsyncFunction'; -} -export function isAsyncGenerator(value) { - return isAsyncIterable(value) && isFunction(value.next) && isFunction(value.throw); -} -export function isAsyncGeneratorFunction(value) { - return getObjectType(value) === 'AsyncGeneratorFunction'; -} -export function isAsyncIterable(value) { - return isFunction(value?.[Symbol.asyncIterator]); -} -export function isBigint(value) { - return typeof value === 'bigint'; -} -export function isBigInt64Array(value) { - return getObjectType(value) === 'BigInt64Array'; -} -export function isBigUint64Array(value) { - return getObjectType(value) === 'BigUint64Array'; -} -export function isBlob(value) { - return getObjectType(value) === 'Blob'; -} -export function isBoolean(value) { - return value === true || value === false; -} -// eslint-disable-next-line @typescript-eslint/ban-types -export function isBoundFunction(value) { - return isFunction(value) && !Object.prototype.hasOwnProperty.call(value, 'prototype'); -} -export function isBuffer(value) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call - return value?.constructor?.isBuffer?.(value) ?? false; -} -export function isClass(value) { - return isFunction(value) && value.toString().startsWith('class '); -} -export function isDataView(value) { - return getObjectType(value) === 'DataView'; -} -export function isDate(value) { - return getObjectType(value) === 'Date'; -} -export function isDirectInstanceOf(instance, class_) { - if (instance === undefined || instance === null) { + return value.every(assertion); +}; +is.buffer = (value) => { var _a, _b, _c, _d; return (_d = (_c = (_b = (_a = value) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.isBuffer) === null || _c === void 0 ? void 0 : _c.call(_b, value)) !== null && _d !== void 0 ? _d : false; }; +is.blob = (value) => isObjectOfType('Blob')(value); +is.nullOrUndefined = (value) => is.null_(value) || is.undefined(value); +is.object = (value) => !is.null_(value) && (typeof value === 'object' || is.function_(value)); +is.iterable = (value) => { var _a; return is.function_((_a = value) === null || _a === void 0 ? void 0 : _a[Symbol.iterator]); }; +is.asyncIterable = (value) => { var _a; return is.function_((_a = value) === null || _a === void 0 ? void 0 : _a[Symbol.asyncIterator]); }; +is.generator = (value) => { var _a, _b; return is.iterable(value) && is.function_((_a = value) === null || _a === void 0 ? void 0 : _a.next) && is.function_((_b = value) === null || _b === void 0 ? void 0 : _b.throw); }; +is.asyncGenerator = (value) => is.asyncIterable(value) && is.function_(value.next) && is.function_(value.throw); +is.nativePromise = (value) => isObjectOfType('Promise')(value); +const hasPromiseAPI = (value) => { + var _a, _b; + return is.function_((_a = value) === null || _a === void 0 ? void 0 : _a.then) && + is.function_((_b = value) === null || _b === void 0 ? void 0 : _b.catch); +}; +is.promise = (value) => is.nativePromise(value) || hasPromiseAPI(value); +is.generatorFunction = isObjectOfType('GeneratorFunction'); +is.asyncGeneratorFunction = (value) => getObjectType(value) === 'AsyncGeneratorFunction'; +is.asyncFunction = (value) => getObjectType(value) === 'AsyncFunction'; +// eslint-disable-next-line no-prototype-builtins, @typescript-eslint/ban-types +is.boundFunction = (value) => is.function_(value) && !value.hasOwnProperty('prototype'); +is.regExp = isObjectOfType('RegExp'); +is.date = isObjectOfType('Date'); +is.error = isObjectOfType('Error'); +is.map = (value) => isObjectOfType('Map')(value); +is.set = (value) => isObjectOfType('Set')(value); +is.weakMap = (value) => isObjectOfType('WeakMap')(value); +is.weakSet = (value) => isObjectOfType('WeakSet')(value); +is.int8Array = isObjectOfType('Int8Array'); +is.uint8Array = isObjectOfType('Uint8Array'); +is.uint8ClampedArray = isObjectOfType('Uint8ClampedArray'); +is.int16Array = isObjectOfType('Int16Array'); +is.uint16Array = isObjectOfType('Uint16Array'); +is.int32Array = isObjectOfType('Int32Array'); +is.uint32Array = isObjectOfType('Uint32Array'); +is.float32Array = isObjectOfType('Float32Array'); +is.float64Array = isObjectOfType('Float64Array'); +is.bigInt64Array = isObjectOfType('BigInt64Array'); +is.bigUint64Array = isObjectOfType('BigUint64Array'); +is.arrayBuffer = isObjectOfType('ArrayBuffer'); +is.sharedArrayBuffer = isObjectOfType('SharedArrayBuffer'); +is.dataView = isObjectOfType('DataView'); +is.enumCase = (value, targetEnum) => Object.values(targetEnum).includes(value); +is.directInstanceOf = (instance, class_) => Object.getPrototypeOf(instance) === class_.prototype; +is.urlInstance = (value) => isObjectOfType('URL')(value); +is.urlString = (value) => { + if (!is.string(value)) { return false; } - return Object.getPrototypeOf(instance) === class_.prototype; -} -export function isEmptyArray(value) { - return isArray(value) && value.length === 0; -} -export function isEmptyMap(value) { - return isMap(value) && value.size === 0; -} -export function isEmptyObject(value) { - return isObject(value) && !isMap(value) && !isSet(value) && Object.keys(value).length === 0; -} -export function isEmptySet(value) { - return isSet(value) && value.size === 0; -} -export function isEmptyString(value) { - return isString(value) && value.length === 0; -} -export function isEmptyStringOrWhitespace(value) { - return isEmptyString(value) || isWhitespaceString(value); -} -export function isEnumCase(value, targetEnum) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument - return Object.values(targetEnum).includes(value); -} -export function isError(value) { - return getObjectType(value) === 'Error'; -} -export function isEvenInteger(value) { - return isAbsoluteMod2(0)(value); -} + try { + new URL(value); // eslint-disable-line no-new + return true; + } + catch (_a) { + return false; + } +}; +// Example: `is.truthy = (value: unknown): value is (not false | not 0 | not '' | not undefined | not null) => Boolean(value);` +is.truthy = (value) => Boolean(value); // Example: `is.falsy = (value: unknown): value is (not true | 0 | '' | undefined | null) => Boolean(value);` -export function isFalsy(value) { - return !value; -} -export function isFloat32Array(value) { - return getObjectType(value) === 'Float32Array'; -} -export function isFloat64Array(value) { - return getObjectType(value) === 'Float64Array'; -} -export function isFormData(value) { - return getObjectType(value) === 'FormData'; -} -// eslint-disable-next-line @typescript-eslint/ban-types -export function isFunction(value) { - return typeof value === 'function'; -} -export function isGenerator(value) { - return isIterable(value) && isFunction(value?.next) && isFunction(value?.throw); -} -export function isGeneratorFunction(value) { - return getObjectType(value) === 'GeneratorFunction'; -} -// eslint-disable-next-line @typescript-eslint/naming-convention +is.falsy = (value) => !value; +is.nan = (value) => Number.isNaN(value); +is.primitive = (value) => is.null_(value) || isPrimitiveTypeName(typeof value); +is.integer = (value) => Number.isInteger(value); +is.safeInteger = (value) => Number.isSafeInteger(value); +is.plainObject = (value) => { + // From: https://github.com/sindresorhus/is-plain-obj/blob/main/index.js + if (toString.call(value) !== '[object Object]') { + return false; + } + const prototype = Object.getPrototypeOf(value); + return prototype === null || prototype === Object.getPrototypeOf({}); +}; +is.typedArray = (value) => isTypedArrayName(getObjectType(value)); +const isValidLength = (value) => is.safeInteger(value) && value >= 0; +is.arrayLike = (value) => !is.nullOrUndefined(value) && !is.function_(value) && isValidLength(value.length); +is.inRange = (value, range) => { + if (is.number(range)) { + return value >= Math.min(0, range) && value <= Math.max(range, 0); + } + if (is.array(range) && range.length === 2) { + return value >= Math.min(...range) && value <= Math.max(...range); + } + throw new TypeError(`Invalid range: ${JSON.stringify(range)}`); +}; const NODE_TYPE_ELEMENT = 1; -// eslint-disable-next-line @typescript-eslint/naming-convention const DOM_PROPERTIES_TO_CHECK = [ 'innerHTML', 'ownerDocument', 'style', 'attributes', - 'nodeValue', + 'nodeValue' ]; -export function isHtmlElement(value) { - return isObject(value) - && value.nodeType === NODE_TYPE_ELEMENT - && isString(value.nodeName) - && !isPlainObject(value) - && DOM_PROPERTIES_TO_CHECK.every(property => property in value); -} -export function isInfinite(value) { - return value === Number.POSITIVE_INFINITY || value === Number.NEGATIVE_INFINITY; -} -export function isInRange(value, range) { - if (isNumber(range)) { - return value >= Math.min(0, range) && value <= Math.max(range, 0); - } - if (isArray(range) && range.length === 2) { - return value >= Math.min(...range) && value <= Math.max(...range); - } - throw new TypeError(`Invalid range: ${JSON.stringify(range)}`); -} -export function isInt16Array(value) { - return getObjectType(value) === 'Int16Array'; -} -export function isInt32Array(value) { - return getObjectType(value) === 'Int32Array'; -} -export function isInt8Array(value) { - return getObjectType(value) === 'Int8Array'; -} -export function isInteger(value) { - return Number.isInteger(value); -} -export function isIterable(value) { - return isFunction(value?.[Symbol.iterator]); -} -export function isMap(value) { - return getObjectType(value) === 'Map'; -} -export function isNan(value) { - return Number.isNaN(value); -} -export function isNativePromise(value) { - return getObjectType(value) === 'Promise'; -} -export function isNegativeNumber(value) { - return isNumber(value) && value < 0; -} -export function isNodeStream(value) { - return isObject(value) && isFunction(value.pipe) && !isObservable(value); -} -export function isNonEmptyArray(value) { - return isArray(value) && value.length > 0; -} -export function isNonEmptyMap(value) { - return isMap(value) && value.size > 0; -} -// TODO: Use `not` operator here to remove `Map` and `Set` from type guard: -// - https://github.com/Microsoft/TypeScript/pull/29317 -export function isNonEmptyObject(value) { - return isObject(value) && !isMap(value) && !isSet(value) && Object.keys(value).length > 0; -} -export function isNonEmptySet(value) { - return isSet(value) && value.size > 0; -} -// TODO: Use `not ''` when the `not` operator is available. -export function isNonEmptyString(value) { - return isString(value) && value.length > 0; -} -// TODO: Use `not ''` when the `not` operator is available. -export function isNonEmptyStringAndNotWhitespace(value) { - return isString(value) && !isEmptyStringOrWhitespace(value); -} -// eslint-disable-next-line @typescript-eslint/ban-types -export function isNull(value) { - return value === null; -} -// eslint-disable-next-line @typescript-eslint/ban-types -export function isNullOrUndefined(value) { - return isNull(value) || isUndefined(value); -} -export function isNumber(value) { - return typeof value === 'number' && !Number.isNaN(value); -} -export function isNumericString(value) { - return isString(value) && !isEmptyStringOrWhitespace(value) && !Number.isNaN(Number(value)); -} -// eslint-disable-next-line @typescript-eslint/ban-types -export function isObject(value) { - return !isNull(value) && (typeof value === 'object' || isFunction(value)); -} -export function isObservable(value) { +is.domElement = (value) => { + return is.object(value) && + value.nodeType === NODE_TYPE_ELEMENT && + is.string(value.nodeName) && + !is.plainObject(value) && + DOM_PROPERTIES_TO_CHECK.every(property => property in value); +}; +is.observable = (value) => { + var _a, _b, _c, _d; if (!value) { return false; } - // eslint-disable-next-line no-use-extend-native/no-use-extend-native, @typescript-eslint/no-unsafe-call - if (value === value[Symbol.observable]?.()) { + // eslint-disable-next-line no-use-extend-native/no-use-extend-native + if (value === ((_b = (_a = value)[Symbol.observable]) === null || _b === void 0 ? void 0 : _b.call(_a))) { return true; } - // eslint-disable-next-line @typescript-eslint/no-unsafe-call - if (value === value['@@observable']?.()) { + if (value === ((_d = (_c = value)['@@observable']) === null || _d === void 0 ? void 0 : _d.call(_c))) { return true; } return false; -} -export function isOddInteger(value) { - return isAbsoluteMod2(1)(value); -} -export function isPlainObject(value) { - // From: https://github.com/sindresorhus/is-plain-obj/blob/main/index.js - if (typeof value !== 'object' || value === null) { - return false; - } - // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment - const prototype = Object.getPrototypeOf(value); - return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value); -} -export function isPositiveNumber(value) { - return isNumber(value) && value > 0; -} -export function isPrimitive(value) { - return isNull(value) || isPrimitiveTypeName(typeof value); -} -export function isPromise(value) { - return isNativePromise(value) || hasPromiseApi(value); -} +}; +is.nodeStream = (value) => is.object(value) && is.function_(value.pipe) && !is.observable(value); +is.infinite = (value) => value === Infinity || value === -Infinity; +const isAbsoluteMod2 = (remainder) => (value) => is.integer(value) && Math.abs(value % 2) === remainder; +is.evenInteger = isAbsoluteMod2(0); +is.oddInteger = isAbsoluteMod2(1); +is.emptyArray = (value) => is.array(value) && value.length === 0; +is.nonEmptyArray = (value) => is.array(value) && value.length > 0; +is.emptyString = (value) => is.string(value) && value.length === 0; +const isWhiteSpaceString = (value) => is.string(value) && !/\S/.test(value); +is.emptyStringOrWhitespace = (value) => is.emptyString(value) || isWhiteSpaceString(value); +// TODO: Use `not ''` when the `not` operator is available. +is.nonEmptyString = (value) => is.string(value) && value.length > 0; +// TODO: Use `not ''` when the `not` operator is available. +is.nonEmptyStringAndNotWhitespace = (value) => is.string(value) && !is.emptyStringOrWhitespace(value); +is.emptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length === 0; +// TODO: Use `not` operator here to remove `Map` and `Set` from type guard: +// - https://github.com/Microsoft/TypeScript/pull/29317 +is.nonEmptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length > 0; +is.emptySet = (value) => is.set(value) && value.size === 0; +is.nonEmptySet = (value) => is.set(value) && value.size > 0; +is.emptyMap = (value) => is.map(value) && value.size === 0; +is.nonEmptyMap = (value) => is.map(value) && value.size > 0; // `PropertyKey` is any value that can be used as an object key (string, number, or symbol) -export function isPropertyKey(value) { - return isAny([isString, isNumber, isSymbol], value); -} -export function isRegExp(value) { - return getObjectType(value) === 'RegExp'; -} -export function isSafeInteger(value) { - return Number.isSafeInteger(value); -} -export function isSet(value) { - return getObjectType(value) === 'Set'; -} -export function isSharedArrayBuffer(value) { - return getObjectType(value) === 'SharedArrayBuffer'; -} -export function isString(value) { - return typeof value === 'string'; -} -export function isSymbol(value) { - return typeof value === 'symbol'; -} -// Example: `is.truthy = (value: unknown): value is (not false | not 0 | not '' | not undefined | not null) => Boolean(value);` -// eslint-disable-next-line unicorn/prefer-native-coercion-functions -export function isTruthy(value) { - return Boolean(value); -} -export function isTupleLike(value, guards) { - if (isArray(guards) && isArray(value) && guards.length === value.length) { - return guards.every((guard, index) => guard(value[index])); - } - return false; -} -export function isTypedArray(value) { - return isTypedArrayName(getObjectType(value)); -} -export function isUint16Array(value) { - return getObjectType(value) === 'Uint16Array'; -} -export function isUint32Array(value) { - return getObjectType(value) === 'Uint32Array'; -} -export function isUint8Array(value) { - return getObjectType(value) === 'Uint8Array'; -} -export function isUint8ClampedArray(value) { - return getObjectType(value) === 'Uint8ClampedArray'; -} -export function isUndefined(value) { - return value === undefined; -} -export function isUrlInstance(value) { - return getObjectType(value) === 'URL'; -} -// eslint-disable-next-line unicorn/prevent-abbreviations -export function isUrlSearchParams(value) { - return getObjectType(value) === 'URLSearchParams'; -} -export function isUrlString(value) { - if (!isString(value)) { - return false; - } - try { - new URL(value); // eslint-disable-line no-new - return true; - } - catch { - return false; - } -} -export function isValidLength(value) { - return isSafeInteger(value) && value >= 0; -} -// eslint-disable-next-line @typescript-eslint/ban-types -export function isWeakMap(value) { - return getObjectType(value) === 'WeakMap'; -} -// eslint-disable-next-line @typescript-eslint/ban-types -export function isWeakRef(value) { - return getObjectType(value) === 'WeakRef'; -} -// eslint-disable-next-line @typescript-eslint/ban-types -export function isWeakSet(value) { - return getObjectType(value) === 'WeakSet'; -} -export function isWhitespaceString(value) { - return isString(value) && /^\s+$/.test(value); -} -function predicateOnArray(method, predicate, values) { - if (!isFunction(predicate)) { +is.propertyKey = (value) => is.any([is.string, is.number, is.symbol], value); +is.formData = (value) => isObjectOfType('FormData')(value); +is.urlSearchParams = (value) => isObjectOfType('URLSearchParams')(value); +const predicateOnArray = (method, predicate, values) => { + if (!is.function_(predicate)) { throw new TypeError(`Invalid predicate: ${JSON.stringify(predicate)}`); } if (values.length === 0) { throw new TypeError('Invalid number of values'); } return method.call(values, predicate); -} -function typeErrorMessage(description, value) { - return `Expected value which is \`${description}\`, received value of type \`${is(value)}\`.`; -} -function unique(values) { - // eslint-disable-next-line unicorn/prefer-spread - return Array.from(new Set(values)); -} -const andFormatter = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' }); -const orFormatter = new Intl.ListFormat('en', { style: 'long', type: 'disjunction' }); -function typeErrorMessageMultipleValues(expectedType, values) { - const uniqueExpectedTypes = unique((isArray(expectedType) ? expectedType : [expectedType]).map(value => `\`${value}\``)); - const uniqueValueTypes = unique(values.map(value => `\`${is(value)}\``)); - return `Expected values which are ${orFormatter.format(uniqueExpectedTypes)}. Received values of type${uniqueValueTypes.length > 1 ? 's' : ''} ${andFormatter.format(uniqueValueTypes)}.`; -} -export const assert = { - all: assertAll, - any: assertAny, - array: assertArray, - arrayBuffer: assertArrayBuffer, - arrayLike: assertArrayLike, - asyncFunction: assertAsyncFunction, - asyncGenerator: assertAsyncGenerator, - asyncGeneratorFunction: assertAsyncGeneratorFunction, - asyncIterable: assertAsyncIterable, - bigint: assertBigint, - bigInt64Array: assertBigInt64Array, - bigUint64Array: assertBigUint64Array, - blob: assertBlob, - boolean: assertBoolean, - boundFunction: assertBoundFunction, - buffer: assertBuffer, - class: assertClass, - class_: assertClass, - dataView: assertDataView, - date: assertDate, - directInstanceOf: assertDirectInstanceOf, - domElement: assertHtmlElement, - emptyArray: assertEmptyArray, - emptyMap: assertEmptyMap, - emptyObject: assertEmptyObject, - emptySet: assertEmptySet, - emptyString: assertEmptyString, - emptyStringOrWhitespace: assertEmptyStringOrWhitespace, - enumCase: assertEnumCase, - error: assertError, - evenInteger: assertEvenInteger, - falsy: assertFalsy, - float32Array: assertFloat32Array, - float64Array: assertFloat64Array, - formData: assertFormData, - function: assertFunction, - function_: assertFunction, - generator: assertGenerator, - generatorFunction: assertGeneratorFunction, - htmlElement: assertHtmlElement, - infinite: assertInfinite, - inRange: assertInRange, - int16Array: assertInt16Array, - int32Array: assertInt32Array, - int8Array: assertInt8Array, - integer: assertInteger, - iterable: assertIterable, - map: assertMap, - nan: assertNan, - nativePromise: assertNativePromise, - negativeNumber: assertNegativeNumber, - nodeStream: assertNodeStream, - nonEmptyArray: assertNonEmptyArray, - nonEmptyMap: assertNonEmptyMap, - nonEmptyObject: assertNonEmptyObject, - nonEmptySet: assertNonEmptySet, - nonEmptyString: assertNonEmptyString, - nonEmptyStringAndNotWhitespace: assertNonEmptyStringAndNotWhitespace, - null: assertNull, - null_: assertNull, - nullOrUndefined: assertNullOrUndefined, - number: assertNumber, - numericString: assertNumericString, - object: assertObject, - observable: assertObservable, - oddInteger: assertOddInteger, - plainObject: assertPlainObject, - positiveNumber: assertPositiveNumber, - primitive: assertPrimitive, - promise: assertPromise, - propertyKey: assertPropertyKey, - regExp: assertRegExp, - safeInteger: assertSafeInteger, - set: assertSet, - sharedArrayBuffer: assertSharedArrayBuffer, - string: assertString, - symbol: assertSymbol, - truthy: assertTruthy, - tupleLike: assertTupleLike, - typedArray: assertTypedArray, - uint16Array: assertUint16Array, - uint32Array: assertUint32Array, - uint8Array: assertUint8Array, - uint8ClampedArray: assertUint8ClampedArray, - undefined: assertUndefined, - urlInstance: assertUrlInstance, - urlSearchParams: assertUrlSearchParams, - urlString: assertUrlString, - validLength: assertValidLength, - weakMap: assertWeakMap, - weakRef: assertWeakRef, - weakSet: assertWeakSet, - whitespaceString: assertWhitespaceString, }; -const methodTypeMap = { - isArray: 'Array', - isArrayBuffer: 'ArrayBuffer', - isArrayLike: 'array-like', - isAsyncFunction: 'AsyncFunction', - isAsyncGenerator: 'AsyncGenerator', - isAsyncGeneratorFunction: 'AsyncGeneratorFunction', - isAsyncIterable: 'AsyncIterable', - isBigint: 'bigint', - isBigInt64Array: 'BigInt64Array', - isBigUint64Array: 'BigUint64Array', - isBlob: 'Blob', - isBoolean: 'boolean', - isBoundFunction: 'Function', - isBuffer: 'Buffer', - isClass: 'Class', - isDataView: 'DataView', - isDate: 'Date', - isDirectInstanceOf: 'T', - /** @deprecated */ - isDomElement: 'HTMLElement', - isEmptyArray: 'empty array', - isEmptyMap: 'empty map', - isEmptyObject: 'empty object', - isEmptySet: 'empty set', - isEmptyString: 'empty string', - isEmptyStringOrWhitespace: 'empty string or whitespace', - isEnumCase: 'EnumCase', - isError: 'Error', - isEvenInteger: 'even integer', - isFalsy: 'falsy', - isFloat32Array: 'Float32Array', - isFloat64Array: 'Float64Array', - isFormData: 'FormData', - isFunction: 'Function', - isGenerator: 'Generator', - isGeneratorFunction: 'GeneratorFunction', - isHtmlElement: 'HTMLElement', - isInfinite: 'infinite number', - isInRange: 'in range', - isInt16Array: 'Int16Array', - isInt32Array: 'Int32Array', - isInt8Array: 'Int8Array', - isInteger: 'integer', - isIterable: 'Iterable', - isMap: 'Map', - isNan: 'NaN', - isNativePromise: 'native Promise', - isNegativeNumber: 'negative number', - isNodeStream: 'Node.js Stream', - isNonEmptyArray: 'non-empty array', - isNonEmptyMap: 'non-empty map', - isNonEmptyObject: 'non-empty object', - isNonEmptySet: 'non-empty set', - isNonEmptyString: 'non-empty string', - isNonEmptyStringAndNotWhitespace: 'non-empty string and not whitespace', - isNull: 'null', - isNullOrUndefined: 'null or undefined', - isNumber: 'number', - isNumericString: 'string with a number', - isObject: 'Object', - isObservable: 'Observable', - isOddInteger: 'odd integer', - isPlainObject: 'plain object', - isPositiveNumber: 'positive number', - isPrimitive: 'primitive', - isPromise: 'Promise', - isPropertyKey: 'PropertyKey', - isRegExp: 'RegExp', - isSafeInteger: 'integer', - isSet: 'Set', - isSharedArrayBuffer: 'SharedArrayBuffer', - isString: 'string', - isSymbol: 'symbol', - isTruthy: 'truthy', - isTupleLike: 'tuple-like', - isTypedArray: 'TypedArray', - isUint16Array: 'Uint16Array', - isUint32Array: 'Uint32Array', - isUint8Array: 'Uint8Array', - isUint8ClampedArray: 'Uint8ClampedArray', - isUndefined: 'undefined', - isUrlInstance: 'URL', - isUrlSearchParams: 'URLSearchParams', - isUrlString: 'string with a URL', - isValidLength: 'valid length', - isWeakMap: 'WeakMap', - isWeakRef: 'WeakRef', - isWeakSet: 'WeakSet', - isWhitespaceString: 'whitespace string', +is.any = (predicate, ...values) => { + const predicates = is.array(predicate) ? predicate : [predicate]; + return predicates.some(singlePredicate => predicateOnArray(Array.prototype.some, singlePredicate, values)); }; -function keysOf(value) { - return Object.keys(value); -} -const isMethodNames = keysOf(methodTypeMap); -function isIsMethodName(value) { - return isMethodNames.includes(value); -} -export function assertAll(predicate, ...values) { - if (!isAll(predicate, ...values)) { - const expectedType = isIsMethodName(predicate.name) ? methodTypeMap[predicate.name] : 'predicate returns truthy for all values'; - throw new TypeError(typeErrorMessageMultipleValues(expectedType, values)); - } -} -export function assertAny(predicate, ...values) { - if (!isAny(predicate, ...values)) { - const predicates = isArray(predicate) ? predicate : [predicate]; - const expectedTypes = predicates.map(predicate => isIsMethodName(predicate.name) ? methodTypeMap[predicate.name] : 'predicate returns truthy for any value'); - throw new TypeError(typeErrorMessageMultipleValues(expectedTypes, values)); - } -} -export function assertArray(value, assertion) { - if (!isArray(value)) { - throw new TypeError(typeErrorMessage('Array', value)); - } - if (assertion) { - // eslint-disable-next-line unicorn/no-array-for-each, unicorn/no-array-callback-reference - value.forEach(assertion); - } -} -export function assertArrayBuffer(value) { - if (!isArrayBuffer(value)) { - throw new TypeError(typeErrorMessage('ArrayBuffer', value)); - } -} -export function assertArrayLike(value) { - if (!isArrayLike(value)) { - throw new TypeError(typeErrorMessage('array-like', value)); - } -} -// eslint-disable-next-line @typescript-eslint/ban-types -export function assertAsyncFunction(value) { - if (!isAsyncFunction(value)) { - throw new TypeError(typeErrorMessage('AsyncFunction', value)); - } -} -export function assertAsyncGenerator(value) { - if (!isAsyncGenerator(value)) { - throw new TypeError(typeErrorMessage('AsyncGenerator', value)); - } -} -export function assertAsyncGeneratorFunction(value) { - if (!isAsyncGeneratorFunction(value)) { - throw new TypeError(typeErrorMessage('AsyncGeneratorFunction', value)); - } -} -export function assertAsyncIterable(value) { - if (!isAsyncIterable(value)) { - throw new TypeError(typeErrorMessage('AsyncIterable', value)); - } -} -export function assertBigint(value) { - if (!isBigint(value)) { - throw new TypeError(typeErrorMessage('bigint', value)); - } -} -export function assertBigInt64Array(value) { - if (!isBigInt64Array(value)) { - throw new TypeError(typeErrorMessage('BigInt64Array', value)); - } -} -export function assertBigUint64Array(value) { - if (!isBigUint64Array(value)) { - throw new TypeError(typeErrorMessage('BigUint64Array', value)); - } -} -export function assertBlob(value) { - if (!isBlob(value)) { - throw new TypeError(typeErrorMessage('Blob', value)); - } -} -export function assertBoolean(value) { - if (!isBoolean(value)) { - throw new TypeError(typeErrorMessage('boolean', value)); - } -} -// eslint-disable-next-line @typescript-eslint/ban-types -export function assertBoundFunction(value) { - if (!isBoundFunction(value)) { - throw new TypeError(typeErrorMessage('Function', value)); - } -} -export function assertBuffer(value) { - if (!isBuffer(value)) { - throw new TypeError(typeErrorMessage('Buffer', value)); - } -} -export function assertClass(value) { - if (!isClass(value)) { - throw new TypeError(typeErrorMessage('Class', value)); - } -} -export function assertDataView(value) { - if (!isDataView(value)) { - throw new TypeError(typeErrorMessage('DataView', value)); - } -} -export function assertDate(value) { - if (!isDate(value)) { - throw new TypeError(typeErrorMessage('Date', value)); - } -} -export function assertDirectInstanceOf(instance, class_) { - if (!isDirectInstanceOf(instance, class_)) { - throw new TypeError(typeErrorMessage('T', instance)); - } -} -export function assertEmptyArray(value) { - if (!isEmptyArray(value)) { - throw new TypeError(typeErrorMessage('empty array', value)); - } -} -export function assertEmptyMap(value) { - if (!isEmptyMap(value)) { - throw new TypeError(typeErrorMessage('empty map', value)); - } -} -export function assertEmptyObject(value) { - if (!isEmptyObject(value)) { - throw new TypeError(typeErrorMessage('empty object', value)); - } -} -export function assertEmptySet(value) { - if (!isEmptySet(value)) { - throw new TypeError(typeErrorMessage('empty set', value)); - } -} -export function assertEmptyString(value) { - if (!isEmptyString(value)) { - throw new TypeError(typeErrorMessage('empty string', value)); - } -} -export function assertEmptyStringOrWhitespace(value) { - if (!isEmptyStringOrWhitespace(value)) { - throw new TypeError(typeErrorMessage('empty string or whitespace', value)); - } -} -export function assertEnumCase(value, targetEnum) { - if (!isEnumCase(value, targetEnum)) { - throw new TypeError(typeErrorMessage('EnumCase', value)); - } -} -export function assertError(value) { - if (!isError(value)) { - throw new TypeError(typeErrorMessage('Error', value)); - } -} -export function assertEvenInteger(value) { - if (!isEvenInteger(value)) { - throw new TypeError(typeErrorMessage('even integer', value)); - } -} -export function assertFalsy(value) { - if (!isFalsy(value)) { - throw new TypeError(typeErrorMessage('falsy', value)); - } -} -export function assertFloat32Array(value) { - if (!isFloat32Array(value)) { - throw new TypeError(typeErrorMessage('Float32Array', value)); - } -} -export function assertFloat64Array(value) { - if (!isFloat64Array(value)) { - throw new TypeError(typeErrorMessage('Float64Array', value)); - } -} -export function assertFormData(value) { - if (!isFormData(value)) { - throw new TypeError(typeErrorMessage('FormData', value)); - } -} -// eslint-disable-next-line @typescript-eslint/ban-types -export function assertFunction(value) { - if (!isFunction(value)) { - throw new TypeError(typeErrorMessage('Function', value)); - } -} -export function assertGenerator(value) { - if (!isGenerator(value)) { - throw new TypeError(typeErrorMessage('Generator', value)); - } -} -export function assertGeneratorFunction(value) { - if (!isGeneratorFunction(value)) { - throw new TypeError(typeErrorMessage('GeneratorFunction', value)); - } -} -export function assertHtmlElement(value) { - if (!isHtmlElement(value)) { - throw new TypeError(typeErrorMessage('HTMLElement', value)); - } -} -export function assertInfinite(value) { - if (!isInfinite(value)) { - throw new TypeError(typeErrorMessage('infinite number', value)); - } -} -export function assertInRange(value, range) { - if (!isInRange(value, range)) { - throw new TypeError(typeErrorMessage('in range', value)); - } -} -export function assertInt16Array(value) { - if (!isInt16Array(value)) { - throw new TypeError(typeErrorMessage('Int16Array', value)); - } -} -export function assertInt32Array(value) { - if (!isInt32Array(value)) { - throw new TypeError(typeErrorMessage('Int32Array', value)); - } -} -export function assertInt8Array(value) { - if (!isInt8Array(value)) { - throw new TypeError(typeErrorMessage('Int8Array', value)); - } -} -export function assertInteger(value) { - if (!isInteger(value)) { - throw new TypeError(typeErrorMessage('integer', value)); - } -} -export function assertIterable(value) { - if (!isIterable(value)) { - throw new TypeError(typeErrorMessage('Iterable', value)); - } -} -export function assertMap(value) { - if (!isMap(value)) { - throw new TypeError(typeErrorMessage('Map', value)); - } -} -export function assertNan(value) { - if (!isNan(value)) { - throw new TypeError(typeErrorMessage('NaN', value)); - } -} -export function assertNativePromise(value) { - if (!isNativePromise(value)) { - throw new TypeError(typeErrorMessage('native Promise', value)); - } -} -export function assertNegativeNumber(value) { - if (!isNegativeNumber(value)) { - throw new TypeError(typeErrorMessage('negative number', value)); - } -} -export function assertNodeStream(value) { - if (!isNodeStream(value)) { - throw new TypeError(typeErrorMessage('Node.js Stream', value)); +is.all = (predicate, ...values) => predicateOnArray(Array.prototype.every, predicate, values); +const assertType = (condition, description, value, options = {}) => { + if (!condition) { + const { multipleValues } = options; + const valuesMessage = multipleValues ? + `received values of types ${[ + ...new Set(value.map(singleValue => `\`${is(singleValue)}\``)) + ].join(', ')}` : + `received value of type \`${is(value)}\``; + throw new TypeError(`Expected value which is \`${description}\`, ${valuesMessage}.`); } -} -export function assertNonEmptyArray(value) { - if (!isNonEmptyArray(value)) { - throw new TypeError(typeErrorMessage('non-empty array', value)); - } -} -export function assertNonEmptyMap(value) { - if (!isNonEmptyMap(value)) { - throw new TypeError(typeErrorMessage('non-empty map', value)); - } -} -export function assertNonEmptyObject(value) { - if (!isNonEmptyObject(value)) { - throw new TypeError(typeErrorMessage('non-empty object', value)); - } -} -export function assertNonEmptySet(value) { - if (!isNonEmptySet(value)) { - throw new TypeError(typeErrorMessage('non-empty set', value)); - } -} -export function assertNonEmptyString(value) { - if (!isNonEmptyString(value)) { - throw new TypeError(typeErrorMessage('non-empty string', value)); - } -} -export function assertNonEmptyStringAndNotWhitespace(value) { - if (!isNonEmptyStringAndNotWhitespace(value)) { - throw new TypeError(typeErrorMessage('non-empty string and not whitespace', value)); - } -} -// eslint-disable-next-line @typescript-eslint/ban-types -export function assertNull(value) { - if (!isNull(value)) { - throw new TypeError(typeErrorMessage('null', value)); - } -} -// eslint-disable-next-line @typescript-eslint/ban-types -export function assertNullOrUndefined(value) { - if (!isNullOrUndefined(value)) { - throw new TypeError(typeErrorMessage('null or undefined', value)); - } -} -export function assertNumber(value) { - if (!isNumber(value)) { - throw new TypeError(typeErrorMessage('number', value)); - } -} -export function assertNumericString(value) { - if (!isNumericString(value)) { - throw new TypeError(typeErrorMessage('string with a number', value)); - } -} -// eslint-disable-next-line @typescript-eslint/ban-types -export function assertObject(value) { - if (!isObject(value)) { - throw new TypeError(typeErrorMessage('Object', value)); - } -} -export function assertObservable(value) { - if (!isObservable(value)) { - throw new TypeError(typeErrorMessage('Observable', value)); - } -} -export function assertOddInteger(value) { - if (!isOddInteger(value)) { - throw new TypeError(typeErrorMessage('odd integer', value)); - } -} -export function assertPlainObject(value) { - if (!isPlainObject(value)) { - throw new TypeError(typeErrorMessage('plain object', value)); - } -} -export function assertPositiveNumber(value) { - if (!isPositiveNumber(value)) { - throw new TypeError(typeErrorMessage('positive number', value)); - } -} -export function assertPrimitive(value) { - if (!isPrimitive(value)) { - throw new TypeError(typeErrorMessage('primitive', value)); - } -} -export function assertPromise(value) { - if (!isPromise(value)) { - throw new TypeError(typeErrorMessage('Promise', value)); - } -} -export function assertPropertyKey(value) { - if (!isPropertyKey(value)) { - throw new TypeError(typeErrorMessage('PropertyKey', value)); - } -} -export function assertRegExp(value) { - if (!isRegExp(value)) { - throw new TypeError(typeErrorMessage('RegExp', value)); - } -} -export function assertSafeInteger(value) { - if (!isSafeInteger(value)) { - throw new TypeError(typeErrorMessage('integer', value)); - } -} -export function assertSet(value) { - if (!isSet(value)) { - throw new TypeError(typeErrorMessage('Set', value)); - } -} -export function assertSharedArrayBuffer(value) { - if (!isSharedArrayBuffer(value)) { - throw new TypeError(typeErrorMessage('SharedArrayBuffer', value)); - } -} -export function assertString(value) { - if (!isString(value)) { - throw new TypeError(typeErrorMessage('string', value)); - } -} -export function assertSymbol(value) { - if (!isSymbol(value)) { - throw new TypeError(typeErrorMessage('symbol', value)); - } -} -export function assertTruthy(value) { - if (!isTruthy(value)) { - throw new TypeError(typeErrorMessage('truthy', value)); - } -} -export function assertTupleLike(value, guards) { - if (!isTupleLike(value, guards)) { - throw new TypeError(typeErrorMessage('tuple-like', value)); - } -} -export function assertTypedArray(value) { - if (!isTypedArray(value)) { - throw new TypeError(typeErrorMessage('TypedArray', value)); - } -} -export function assertUint16Array(value) { - if (!isUint16Array(value)) { - throw new TypeError(typeErrorMessage('Uint16Array', value)); - } -} -export function assertUint32Array(value) { - if (!isUint32Array(value)) { - throw new TypeError(typeErrorMessage('Uint32Array', value)); - } -} -export function assertUint8Array(value) { - if (!isUint8Array(value)) { - throw new TypeError(typeErrorMessage('Uint8Array', value)); - } -} -export function assertUint8ClampedArray(value) { - if (!isUint8ClampedArray(value)) { - throw new TypeError(typeErrorMessage('Uint8ClampedArray', value)); - } -} -export function assertUndefined(value) { - if (!isUndefined(value)) { - throw new TypeError(typeErrorMessage('undefined', value)); - } -} -export function assertUrlInstance(value) { - if (!isUrlInstance(value)) { - throw new TypeError(typeErrorMessage('URL', value)); - } -} -// eslint-disable-next-line unicorn/prevent-abbreviations -export function assertUrlSearchParams(value) { - if (!isUrlSearchParams(value)) { - throw new TypeError(typeErrorMessage('URLSearchParams', value)); - } -} -export function assertUrlString(value) { - if (!isUrlString(value)) { - throw new TypeError(typeErrorMessage('string with a URL', value)); - } -} -export function assertValidLength(value) { - if (!isValidLength(value)) { - throw new TypeError(typeErrorMessage('valid length', value)); - } -} -// eslint-disable-next-line @typescript-eslint/ban-types -export function assertWeakMap(value) { - if (!isWeakMap(value)) { - throw new TypeError(typeErrorMessage('WeakMap', value)); - } -} -// eslint-disable-next-line @typescript-eslint/ban-types -export function assertWeakRef(value) { - if (!isWeakRef(value)) { - throw new TypeError(typeErrorMessage('WeakRef', value)); - } -} -// eslint-disable-next-line @typescript-eslint/ban-types -export function assertWeakSet(value) { - if (!isWeakSet(value)) { - throw new TypeError(typeErrorMessage('WeakSet', value)); +}; +exports.assert = { + // Unknowns. + undefined: (value) => assertType(is.undefined(value), 'undefined', value), + string: (value) => assertType(is.string(value), 'string', value), + number: (value) => assertType(is.number(value), 'number', value), + bigint: (value) => assertType(is.bigint(value), 'bigint', value), + // eslint-disable-next-line @typescript-eslint/ban-types + function_: (value) => assertType(is.function_(value), 'Function', value), + null_: (value) => assertType(is.null_(value), 'null', value), + class_: (value) => assertType(is.class_(value), "Class" /* class_ */, value), + boolean: (value) => assertType(is.boolean(value), 'boolean', value), + symbol: (value) => assertType(is.symbol(value), 'symbol', value), + numericString: (value) => assertType(is.numericString(value), "string with a number" /* numericString */, value), + array: (value, assertion) => { + const assert = assertType; + assert(is.array(value), 'Array', value); + if (assertion) { + value.forEach(assertion); + } + }, + buffer: (value) => assertType(is.buffer(value), 'Buffer', value), + blob: (value) => assertType(is.blob(value), 'Blob', value), + nullOrUndefined: (value) => assertType(is.nullOrUndefined(value), "null or undefined" /* nullOrUndefined */, value), + object: (value) => assertType(is.object(value), 'Object', value), + iterable: (value) => assertType(is.iterable(value), "Iterable" /* iterable */, value), + asyncIterable: (value) => assertType(is.asyncIterable(value), "AsyncIterable" /* asyncIterable */, value), + generator: (value) => assertType(is.generator(value), 'Generator', value), + asyncGenerator: (value) => assertType(is.asyncGenerator(value), 'AsyncGenerator', value), + nativePromise: (value) => assertType(is.nativePromise(value), "native Promise" /* nativePromise */, value), + promise: (value) => assertType(is.promise(value), 'Promise', value), + generatorFunction: (value) => assertType(is.generatorFunction(value), 'GeneratorFunction', value), + asyncGeneratorFunction: (value) => assertType(is.asyncGeneratorFunction(value), 'AsyncGeneratorFunction', value), + // eslint-disable-next-line @typescript-eslint/ban-types + asyncFunction: (value) => assertType(is.asyncFunction(value), 'AsyncFunction', value), + // eslint-disable-next-line @typescript-eslint/ban-types + boundFunction: (value) => assertType(is.boundFunction(value), 'Function', value), + regExp: (value) => assertType(is.regExp(value), 'RegExp', value), + date: (value) => assertType(is.date(value), 'Date', value), + error: (value) => assertType(is.error(value), 'Error', value), + map: (value) => assertType(is.map(value), 'Map', value), + set: (value) => assertType(is.set(value), 'Set', value), + weakMap: (value) => assertType(is.weakMap(value), 'WeakMap', value), + weakSet: (value) => assertType(is.weakSet(value), 'WeakSet', value), + int8Array: (value) => assertType(is.int8Array(value), 'Int8Array', value), + uint8Array: (value) => assertType(is.uint8Array(value), 'Uint8Array', value), + uint8ClampedArray: (value) => assertType(is.uint8ClampedArray(value), 'Uint8ClampedArray', value), + int16Array: (value) => assertType(is.int16Array(value), 'Int16Array', value), + uint16Array: (value) => assertType(is.uint16Array(value), 'Uint16Array', value), + int32Array: (value) => assertType(is.int32Array(value), 'Int32Array', value), + uint32Array: (value) => assertType(is.uint32Array(value), 'Uint32Array', value), + float32Array: (value) => assertType(is.float32Array(value), 'Float32Array', value), + float64Array: (value) => assertType(is.float64Array(value), 'Float64Array', value), + bigInt64Array: (value) => assertType(is.bigInt64Array(value), 'BigInt64Array', value), + bigUint64Array: (value) => assertType(is.bigUint64Array(value), 'BigUint64Array', value), + arrayBuffer: (value) => assertType(is.arrayBuffer(value), 'ArrayBuffer', value), + sharedArrayBuffer: (value) => assertType(is.sharedArrayBuffer(value), 'SharedArrayBuffer', value), + dataView: (value) => assertType(is.dataView(value), 'DataView', value), + enumCase: (value, targetEnum) => assertType(is.enumCase(value, targetEnum), 'EnumCase', value), + urlInstance: (value) => assertType(is.urlInstance(value), 'URL', value), + urlString: (value) => assertType(is.urlString(value), "string with a URL" /* urlString */, value), + truthy: (value) => assertType(is.truthy(value), "truthy" /* truthy */, value), + falsy: (value) => assertType(is.falsy(value), "falsy" /* falsy */, value), + nan: (value) => assertType(is.nan(value), "NaN" /* nan */, value), + primitive: (value) => assertType(is.primitive(value), "primitive" /* primitive */, value), + integer: (value) => assertType(is.integer(value), "integer" /* integer */, value), + safeInteger: (value) => assertType(is.safeInteger(value), "integer" /* safeInteger */, value), + plainObject: (value) => assertType(is.plainObject(value), "plain object" /* plainObject */, value), + typedArray: (value) => assertType(is.typedArray(value), "TypedArray" /* typedArray */, value), + arrayLike: (value) => assertType(is.arrayLike(value), "array-like" /* arrayLike */, value), + domElement: (value) => assertType(is.domElement(value), "HTMLElement" /* domElement */, value), + observable: (value) => assertType(is.observable(value), 'Observable', value), + nodeStream: (value) => assertType(is.nodeStream(value), "Node.js Stream" /* nodeStream */, value), + infinite: (value) => assertType(is.infinite(value), "infinite number" /* infinite */, value), + emptyArray: (value) => assertType(is.emptyArray(value), "empty array" /* emptyArray */, value), + nonEmptyArray: (value) => assertType(is.nonEmptyArray(value), "non-empty array" /* nonEmptyArray */, value), + emptyString: (value) => assertType(is.emptyString(value), "empty string" /* emptyString */, value), + emptyStringOrWhitespace: (value) => assertType(is.emptyStringOrWhitespace(value), "empty string or whitespace" /* emptyStringOrWhitespace */, value), + nonEmptyString: (value) => assertType(is.nonEmptyString(value), "non-empty string" /* nonEmptyString */, value), + nonEmptyStringAndNotWhitespace: (value) => assertType(is.nonEmptyStringAndNotWhitespace(value), "non-empty string and not whitespace" /* nonEmptyStringAndNotWhitespace */, value), + emptyObject: (value) => assertType(is.emptyObject(value), "empty object" /* emptyObject */, value), + nonEmptyObject: (value) => assertType(is.nonEmptyObject(value), "non-empty object" /* nonEmptyObject */, value), + emptySet: (value) => assertType(is.emptySet(value), "empty set" /* emptySet */, value), + nonEmptySet: (value) => assertType(is.nonEmptySet(value), "non-empty set" /* nonEmptySet */, value), + emptyMap: (value) => assertType(is.emptyMap(value), "empty map" /* emptyMap */, value), + nonEmptyMap: (value) => assertType(is.nonEmptyMap(value), "non-empty map" /* nonEmptyMap */, value), + propertyKey: (value) => assertType(is.propertyKey(value), 'PropertyKey', value), + formData: (value) => assertType(is.formData(value), 'FormData', value), + urlSearchParams: (value) => assertType(is.urlSearchParams(value), 'URLSearchParams', value), + // Numbers. + evenInteger: (value) => assertType(is.evenInteger(value), "even integer" /* evenInteger */, value), + oddInteger: (value) => assertType(is.oddInteger(value), "odd integer" /* oddInteger */, value), + // Two arguments. + directInstanceOf: (instance, class_) => assertType(is.directInstanceOf(instance, class_), "T" /* directInstanceOf */, instance), + inRange: (value, range) => assertType(is.inRange(value, range), "in range" /* inRange */, value), + // Variadic functions. + any: (predicate, ...values) => { + return assertType(is.any(predicate, ...values), "predicate returns truthy for any value" /* any */, values, { multipleValues: true }); + }, + all: (predicate, ...values) => assertType(is.all(predicate, ...values), "predicate returns truthy for all values" /* all */, values, { multipleValues: true }) +}; +// Some few keywords are reserved, but we'll populate them for Node.js users +// See https://github.com/Microsoft/TypeScript/issues/2536 +Object.defineProperties(is, { + class: { + value: is.class_ + }, + function: { + value: is.function_ + }, + null: { + value: is.null_ } -} -export function assertWhitespaceString(value) { - if (!isWhitespaceString(value)) { - throw new TypeError(typeErrorMessage('whitespace string', value)); +}); +Object.defineProperties(exports.assert, { + class: { + value: exports.assert.class_ + }, + function: { + value: exports.assert.function_ + }, + null: { + value: exports.assert.null_ } -} -export default is; +}); +exports.default = is; +// For CommonJS default export support +module.exports = is; +module.exports.default = is; +module.exports.assert = exports.assert; diff --git a/setup-pandoc/node_modules/@sindresorhus/is/dist/types.d.ts b/setup-pandoc/node_modules/@sindresorhus/is/dist/types.d.ts index 73d39a63f..b4fae5d62 100644 --- a/setup-pandoc/node_modules/@sindresorhus/is/dist/types.d.ts +++ b/setup-pandoc/node_modules/@sindresorhus/is/dist/types.d.ts @@ -1,20 +1,15 @@ -/// -/// /** Matches any [primitive value](https://developer.mozilla.org/en-US/docs/Glossary/Primitive). */ -export type Primitive = null | undefined | string | number | boolean | symbol | bigint; +export declare type Primitive = null | undefined | string | number | boolean | symbol | bigint; /** Matches a [`class` constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes). */ -/** -Matches a [`class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes). -*/ -export type Class = new (...arguments_: Arguments) => T; +export declare type Class = new (...arguments_: Arguments) => T; /** Matches any [typed array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), like `Uint8Array` or `Float64Array`. */ -export type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array; +export declare type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array; declare global { interface SymbolConstructor { readonly observable: symbol; @@ -23,25 +18,8 @@ declare global { /** Matches a value that is like an [Observable](https://github.com/tc39/proposal-observable). */ -export type ObservableLike = { +export interface ObservableLike { subscribe(observer: (value: unknown) => void): void; [Symbol.observable](): ObservableLike; -}; -export type Falsy = false | 0 | 0n | '' | null | undefined; -export type WeakRef = { - readonly [Symbol.toStringTag]: 'WeakRef'; - deref(): T | undefined; -}; -export type ArrayLike = { - readonly [index: number]: T; - readonly length: number; -}; -export type NodeStream = { - pipe(destination: T, options?: { - end?: boolean; - }): T; -} & NodeJS.EventEmitter; -export type Predicate = (value: unknown) => boolean; -export type NonEmptyString = string & { - 0: string; -}; +} +export declare type Falsy = false | 0 | 0n | '' | null | undefined; diff --git a/setup-pandoc/node_modules/@sindresorhus/is/dist/types.js b/setup-pandoc/node_modules/@sindresorhus/is/dist/types.js index 584792b08..093032386 100644 --- a/setup-pandoc/node_modules/@sindresorhus/is/dist/types.js +++ b/setup-pandoc/node_modules/@sindresorhus/is/dist/types.js @@ -1,2 +1,3 @@ +"use strict"; // Extracted from https://github.com/sindresorhus/type-fest/blob/78019f42ea888b0cdceb41a4a78163868de57555/index.d.ts -export {}; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/setup-pandoc/node_modules/@sindresorhus/is/package.json b/setup-pandoc/node_modules/@sindresorhus/is/package.json index de6c3e4fa..8052a8788 100644 --- a/setup-pandoc/node_modules/@sindresorhus/is/package.json +++ b/setup-pandoc/node_modules/@sindresorhus/is/package.json @@ -1,6 +1,6 @@ { "name": "@sindresorhus/is", - "version": "6.1.0", + "version": "4.6.0", "description": "Type check values", "license": "MIT", "repository": "sindresorhus/is", @@ -10,15 +10,13 @@ "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, - "type": "module", - "exports": "./dist/index.js", - "types": "./dist/index.d.ts", + "main": "dist/index.js", "engines": { - "node": ">=16" + "node": ">=10" }, "scripts": { "build": "del dist && tsc", - "test": "tsc --noEmit && xo && NODE_OPTIONS='--loader=ts-node/esm --no-warnings=ExperimentalWarning' ava", + "test": "xo && ava", "prepare": "npm run build" }, "files": [ @@ -49,25 +47,50 @@ "types" ], "devDependencies": { - "@sindresorhus/tsconfig": "^4.0.0", - "@types/jsdom": "^21.1.1", - "@types/node": "^20.5.0", - "@types/zen-observable": "^0.8.3", - "ava": "^5.3.1", - "del-cli": "^5.0.0", - "jsdom": "^22.1.0", - "rxjs": "^7.8.1", - "tempy": "^3.1.0", - "ts-node": "^10.9.1", - "typescript": "^5.1.6", - "xo": "^0.56.0", - "zen-observable": "^0.10.0", - "expect-type": "^0.16.0" + "@sindresorhus/tsconfig": "^0.7.0", + "@types/jsdom": "^16.1.0", + "@types/node": "^14.0.13", + "@types/zen-observable": "^0.8.0", + "@typescript-eslint/eslint-plugin": "^2.20.0", + "@typescript-eslint/parser": "^2.20.0", + "ava": "^3.3.0", + "del-cli": "^2.0.0", + "eslint-config-xo-typescript": "^0.26.0", + "jsdom": "^16.0.1", + "rxjs": "^6.4.0", + "tempy": "^0.4.0", + "ts-node": "^8.3.0", + "typescript": "~3.8.2", + "xo": "^0.26.1", + "zen-observable": "^0.8.8" }, + "types": "dist/index.d.ts", "sideEffects": false, "ava": { - "extensions": { - "ts": "module" + "extensions": [ + "ts" + ], + "require": [ + "ts-node/register" + ] + }, + "xo": { + "extends": "xo-typescript", + "extensions": [ + "ts" + ], + "parserOptions": { + "project": "./tsconfig.xo.json" + }, + "globals": [ + "BigInt", + "BigInt64Array", + "BigUint64Array" + ], + "rules": { + "@typescript-eslint/promise-function-async": "off", + "@typescript-eslint/no-empty-function": "off", + "@typescript-eslint/explicit-function-return-type": "off" } } } diff --git a/setup-pandoc/node_modules/@sindresorhus/is/readme.md b/setup-pandoc/node_modules/@sindresorhus/is/readme.md index 3f6cfbaa1..05a291a02 100644 --- a/setup-pandoc/node_modules/@sindresorhus/is/readme.md +++ b/setup-pandoc/node_modules/@sindresorhus/is/readme.md @@ -24,7 +24,7 @@ npm install @sindresorhus/is ## Usage ```js -import is from '@sindresorhus/is'; +const is = require('@sindresorhus/is'); is('🦄'); //=> 'string' @@ -39,7 +39,7 @@ is.number(6); [Assertions](#type-assertions) perform the same type checks, but throw an error if the type does not match. ```js -import {assert} from '@sindresorhus/is'; +const {assert} = require('@sindresorhus/is'); assert.string(2); //=> Error: Expected value which is `string`, received value of type `number`. @@ -54,18 +54,6 @@ assert.string(foo); // `foo` is now typed as a `string`. ``` -### Named exports - -Named exports allow tooling to perform tree-shaking, potentially reducing bundle size by including only code from the methods that are used. - -Every method listed below is available as a named export. Each method is prefixed by either `is` or `assert` depending on usage. - -For example: - -```js -import {assertNull, isUndefined} from '@sindresorhus/is'; -``` - ## API ### is(value) @@ -84,23 +72,19 @@ Example: - `'Function'` - `'Object'` -This method is also exported as `detect`. You can import it like this: - -```js -import {detect} from '@sindresorhus/is'; -``` - Note: It will throw an error if you try to feed it object-wrapped primitives, as that's a bad practice. For example `new String('foo')`. ### is.{method} -All the below methods accept a value and return a boolean for whether the value is of the desired type. +All the below methods accept a value and returns a boolean for whether the value is of the desired type. #### Primitives ##### .undefined(value) ##### .null(value) +**Note:** TypeScript users must use `.null_()` because of a TypeScript naming limitation. + ##### .string(value) ##### .number(value) @@ -123,6 +107,8 @@ is.array(value, is.number); // Validate `value` is an array and all of its items ##### .function(value) +**Note:** TypeScript users must use `.function_()` because of a TypeScript naming limitation. + ##### .buffer(value) ##### .blob(value) ##### .object(value) @@ -212,7 +198,6 @@ is.boundFunction(function () {}); ##### .set(value) ##### .weakMap(value) ##### .weakSet(value) -##### .weakRef(value) #### Typed arrays @@ -387,15 +372,7 @@ Returns `true` if `value` is one of: `false`, `0`, `''`, `null`, `undefined`, `N ##### .nullOrUndefined(value) ##### .primitive(value) -JavaScript primitives are as follows: - -- `null` -- `undefined` -- `string` -- `number` -- `boolean` -- `symbol` -- `bigint` +JavaScript primitives are as follows: `null`, `undefined`, `string`, `number`, `boolean`, `symbol`. ##### .integer(value) @@ -411,7 +388,9 @@ An object is plain if it's created by either `{}`, `new Object()`, or `Object.cr ##### .asyncIterable(value) ##### .class(value) -Returns `true` if the value is a class constructor. +Returns `true` for instances created by a class. + +**Note:** TypeScript users must use `.class_()` because of a TypeScript naming limitation. ##### .typedArray(value) @@ -430,34 +409,6 @@ function foo() { foo(); ``` -##### .tupleLike(value, guards) - -A `value` is tuple-like if it matches the provided `guards` array both in `.length` and in types. - -```js -is.tupleLike([1], [is.number]); -//=> true -``` - -```js -function foo() { - const tuple = [1, '2', true]; - if (is.tupleLike(tuple, [is.number, is.string, is.boolean])) { - tuple // [number, string, boolean] - } -} - -foo(); -``` - -#### .positiveNumber(value) - -Check if `value` is a number and is more than 0. - -#### .negativeNumber(value) - -Check if `value` is a number and is less than 0. - ##### .inRange(value, range) Check if `value` (number) is in the given `range`. The range is an array of two values, lower bound and upper bound, in no specific order. @@ -476,16 +427,16 @@ Check if `value` (number) is in the range of `0` to `upperBound`. is.inRange(3, 10); ``` -##### .htmlElement(value) +##### .domElement(value) -Returns `true` if `value` is an [HTMLElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement). +Returns `true` if `value` is a DOM Element. ##### .nodeStream(value) Returns `true` if `value` is a Node.js [stream](https://nodejs.org/api/stream.html). ```js -import fs from 'node:fs'; +const fs = require('fs'); is.nodeStream(fs.createReadStream('unicorn.png')); //=> true @@ -496,7 +447,7 @@ is.nodeStream(fs.createReadStream('unicorn.png')); Returns `true` if `value` is an `Observable`. ```js -import {Observable} from 'rxjs'; +const {Observable} = require('rxjs'); is.observable(new Observable()); //=> true @@ -574,16 +525,6 @@ is.all(is.string, '🦄', [], 'unicorns'); //=> false ``` -##### .validLength(value) - -Returns `true` if the value is a safe integer that is greater than or equal to zero. - -This can be useful to confirm that a value is a valid count of something, ie. 0 or more. - -##### .whitespaceString(value) - -Returns `true` if the value is a string with only whitespace characters. - ## Type guards When using `is` together with TypeScript, [type guards](http://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types) are being used extensively to infer the correct type inside if-else statements. diff --git a/setup-pandoc/node_modules/@szmarczak/http-timer/README.md b/setup-pandoc/node_modules/@szmarczak/http-timer/README.md index f637767d3..f58e10bf9 100644 --- a/setup-pandoc/node_modules/@szmarczak/http-timer/README.md +++ b/setup-pandoc/node_modules/@szmarczak/http-timer/README.md @@ -23,8 +23,8 @@ Yarn: > - Sending a chunk greater than [`highWaterMark`](https://nodejs.org/api/stream.html#stream_new_stream_writable_options) will result in invalid `upload` and `response` timings. You can avoid this by splitting the payload into smaller chunks. ```js -import https from 'https'; -import timer from '@szmarczak/http-timer'; +const https = require('https'); +const timer = require('@szmarczak/http-timer'); const request = https.get('https://httpbin.org/anything'); timer(request); diff --git a/setup-pandoc/node_modules/@szmarczak/http-timer/dist/source/index.d.ts b/setup-pandoc/node_modules/@szmarczak/http-timer/dist/source/index.d.ts index cae5c24e5..2620b4a9f 100644 --- a/setup-pandoc/node_modules/@szmarczak/http-timer/dist/source/index.d.ts +++ b/setup-pandoc/node_modules/@szmarczak/http-timer/dist/source/index.d.ts @@ -1,5 +1,5 @@ /// -import type { ClientRequest, IncomingMessage } from 'http'; +import { ClientRequest, IncomingMessage } from 'http'; export interface Timings { start: number; socket?: number; diff --git a/setup-pandoc/node_modules/@szmarczak/http-timer/dist/source/index.js b/setup-pandoc/node_modules/@szmarczak/http-timer/dist/source/index.js index 407014fff..6f07245de 100644 --- a/setup-pandoc/node_modules/@szmarczak/http-timer/dist/source/index.js +++ b/setup-pandoc/node_modules/@szmarczak/http-timer/dist/source/index.js @@ -1,6 +1,8 @@ -import { errorMonitor } from 'events'; -import { types } from 'util'; -import deferToConnect from 'defer-to-connect'; +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const defer_to_connect_1 = require("defer-to-connect"); +const util_1 = require("util"); +const nodejsMajorVersion = Number(process.versions.node.split('.')[0]); const timer = (request) => { if (request.timings) { return request.timings; @@ -24,26 +26,37 @@ const timer = (request) => { request: undefined, firstByte: undefined, download: undefined, - total: undefined, - }, + total: undefined + } }; request.timings = timings; const handleError = (origin) => { - origin.once(errorMonitor, () => { - timings.error = Date.now(); - timings.phases.total = timings.error - timings.start; - }); + const emit = origin.emit.bind(origin); + origin.emit = (event, ...args) => { + // Catches the `error` event + if (event === 'error') { + timings.error = Date.now(); + timings.phases.total = timings.error - timings.start; + origin.emit = emit; + } + // Saves the original behavior + return emit(event, ...args); + }; }; handleError(request); const onAbort = () => { timings.abort = Date.now(); - timings.phases.total = timings.abort - timings.start; + // Let the `end` response event be responsible for setting the total phase, + // unless the Node.js major version is >= 13. + if (!timings.response || nodejsMajorVersion >= 13) { + timings.phases.total = Date.now() - timings.start; + } }; request.prependOnceListener('abort', onAbort); const onSocket = (socket) => { timings.socket = Date.now(); timings.phases.wait = timings.socket - timings.start; - if (types.isProxy(socket)) { + if (util_1.types.isProxy(socket)) { return; } const lookupListener = () => { @@ -51,7 +64,7 @@ const timer = (request) => { timings.phases.dns = timings.lookup - timings.socket; }; socket.prependOnceListener('lookup', lookupListener); - deferToConnect(socket, { + defer_to_connect_1.default(socket, { connect: () => { timings.connect = Date.now(); if (timings.lookup === undefined) { @@ -60,11 +73,13 @@ const timer = (request) => { timings.phases.dns = timings.lookup - timings.socket; } timings.phases.tcp = timings.connect - timings.lookup; + // This callback is called before flushing any data, + // so we don't need to set `timings.phases.request` here. }, secureConnect: () => { timings.secureConnect = Date.now(); timings.phases.tls = timings.secureConnect - timings.connect; - }, + } }); }; if (request.socket) { @@ -74,10 +89,18 @@ const timer = (request) => { request.prependOnceListener('socket', onSocket); } const onUpload = () => { + var _a; timings.upload = Date.now(); - timings.phases.request = timings.upload - (timings.secureConnect ?? timings.connect); + timings.phases.request = timings.upload - ((_a = timings.secureConnect) !== null && _a !== void 0 ? _a : timings.connect); }; - if (request.writableFinished) { + const writableFinished = () => { + if (typeof request.writableFinished === 'boolean') { + return request.writableFinished; + } + // Node.js doesn't have `request.writableFinished` property + return request.finished && request.outputSize === 0 && (!request.socket || request.socket.writableLength === 0); + }; + if (writableFinished()) { onUpload(); } else { @@ -89,12 +112,6 @@ const timer = (request) => { response.timings = timings; handleError(response); response.prependOnceListener('end', () => { - request.off('abort', onAbort); - response.off('aborted', onAbort); - if (timings.phases.total) { - // Aborted or errored - return; - } timings.end = Date.now(); timings.phases.download = timings.end - timings.response; timings.phases.total = timings.end - timings.start; @@ -103,4 +120,7 @@ const timer = (request) => { }); return timings; }; -export default timer; +exports.default = timer; +// For CommonJS default export support +module.exports = timer; +module.exports.default = timer; diff --git a/setup-pandoc/node_modules/@szmarczak/http-timer/package.json b/setup-pandoc/node_modules/@szmarczak/http-timer/package.json index d9567b5ed..43a355906 100644 --- a/setup-pandoc/node_modules/@szmarczak/http-timer/package.json +++ b/setup-pandoc/node_modules/@szmarczak/http-timer/package.json @@ -1,17 +1,16 @@ { "name": "@szmarczak/http-timer", - "version": "5.0.1", + "version": "4.0.6", "description": "Timings for HTTP requests", - "type": "module", - "exports": "./dist/source/index.js", + "main": "dist/source", "engines": { - "node": ">=14.16" + "node": ">=10" }, "scripts": { - "test": "xo && ava", + "test": "xo && tsc --noEmit && nyc ava", "build": "del-cli dist && tsc", "prepare": "npm run build", - "coveralls": "exit 0 && nyc report --reporter=text-lcov | coveralls" + "coveralls": "nyc report --reporter=text-lcov | coveralls" }, "files": [ "dist/source" @@ -19,11 +18,8 @@ "keywords": [ "http", "https", - "http2", "timer", - "timings", - "performance", - "measure" + "timings" ], "repository": { "type": "git", @@ -36,21 +32,20 @@ }, "homepage": "https://github.com/szmarczak/http-timer#readme", "dependencies": { - "defer-to-connect": "^2.0.1" + "defer-to-connect": "^2.0.0" }, "devDependencies": { "@ava/typescript": "^2.0.0", "@sindresorhus/tsconfig": "^1.0.2", - "@types/node": "^16.7.0", + "@types/node": "^16.3.1", "ava": "^3.15.0", "coveralls": "^3.1.1", - "del-cli": "^4.0.1", - "http2-wrapper": "^2.1.4", + "del-cli": "^3.0.1", + "http2-wrapper": "^2.0.7", "nyc": "^15.1.0", "p-event": "^4.2.0", - "ts-node": "^10.2.1", "typescript": "^4.3.5", - "xo": "^0.44.0" + "xo": "^0.39.1" }, "types": "dist/source", "nyc": { @@ -63,27 +58,15 @@ }, "xo": { "rules": { - "@typescript-eslint/no-non-null-assertion": "off", - "@typescript-eslint/no-unsafe-assignment": "off", - "@typescript-eslint/no-unsafe-member-access": "off", - "@typescript-eslint/no-unsafe-call": "off", - "unicorn/prefer-node-protocol": "off" + "@typescript-eslint/no-non-null-assertion": "off" } }, "ava": { - "files": [ - "tests/*" - ], - "timeout": "1m", - "nonSemVerExperiments": { - "nextGenConfig": true, - "configurableModuleFormat": true - }, - "extensions": { - "ts": "module" - }, - "nodeArguments": [ - "--loader=ts-node/esm" - ] + "typescript": { + "compile": false, + "rewritePaths": { + "tests/": "dist/tests/" + } + } } } diff --git a/setup-pandoc/node_modules/@types/cacheable-request/LICENSE b/setup-pandoc/node_modules/@types/cacheable-request/LICENSE new file mode 100755 index 000000000..9e841e7a2 --- /dev/null +++ b/setup-pandoc/node_modules/@types/cacheable-request/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/setup-pandoc/node_modules/@types/cacheable-request/README.md b/setup-pandoc/node_modules/@types/cacheable-request/README.md new file mode 100755 index 000000000..e87128eeb --- /dev/null +++ b/setup-pandoc/node_modules/@types/cacheable-request/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/cacheable-request` + +# Summary +This package contains type definitions for cacheable-request (https://github.com/lukechilds/cacheable-request#readme). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/cacheable-request. + +### Additional Details + * Last updated: Wed, 09 Nov 2022 16:32:53 GMT + * Dependencies: [@types/http-cache-semantics](https://npmjs.com/package/@types/http-cache-semantics), [@types/keyv](https://npmjs.com/package/@types/keyv), [@types/node](https://npmjs.com/package/@types/node), [@types/responselike](https://npmjs.com/package/@types/responselike) + * Global values: none + +# Credits +These definitions were written by [BendingBender](https://github.com/BendingBender), and [Paul Melnikow](https://github.com/paulmelnikow). diff --git a/setup-pandoc/node_modules/@types/cacheable-request/index.d.ts b/setup-pandoc/node_modules/@types/cacheable-request/index.d.ts new file mode 100755 index 000000000..832f9b9e8 --- /dev/null +++ b/setup-pandoc/node_modules/@types/cacheable-request/index.d.ts @@ -0,0 +1,137 @@ +// Type definitions for cacheable-request 6.0 +// Project: https://github.com/lukechilds/cacheable-request#readme +// Definitions by: BendingBender +// Paul Melnikow +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +import { request, RequestOptions, ClientRequest, ServerResponse } from 'http'; +import { URL } from 'url'; +import { EventEmitter } from 'events'; +import { Store } from 'keyv'; +import { Options as CacheSemanticsOptions } from 'http-cache-semantics'; +import ResponseLike = require('responselike'); + +export = CacheableRequest; + +declare const CacheableRequest: CacheableRequest; + +type RequestFn = typeof request; + +interface CacheableRequest { + new (requestFn: RequestFn, storageAdapter?: string | CacheableRequest.StorageAdapter): ( + opts: string | URL | (RequestOptions & CacheSemanticsOptions), + cb?: (response: ServerResponse | ResponseLike) => void + ) => CacheableRequest.Emitter; + + RequestError: typeof RequestErrorCls; + CacheError: typeof CacheErrorCls; +} + +declare namespace CacheableRequest { + type StorageAdapter = Store; + + interface Options { + /** + * If the cache should be used. Setting this to `false` will completely bypass the cache for the current request. + * @default true + */ + cache?: boolean | undefined; + + /** + * If set to `true` once a cached resource has expired it is deleted and will have to be re-requested. + * + * If set to `false`, after a cached resource's TTL expires it is kept in the cache and will be revalidated + * on the next request with `If-None-Match`/`If-Modified-Since` headers. + * @default false + */ + strictTtl?: boolean | undefined; + + /** + * Limits TTL. The `number` represents milliseconds. + * @default undefined + */ + maxTtl?: number | undefined; + + /** + * When set to `true`, if the DB connection fails we will automatically fallback to a network request. + * DB errors will still be emitted to notify you of the problem even though the request callback may succeed. + * @default false + */ + automaticFailover?: boolean | undefined; + + /** + * Forces refreshing the cache. If the response could be retrieved from the cache, it will perform a + * new request and override the cache instead. + * @default false + */ + forceRefresh?: boolean | undefined; + } + + interface Emitter extends EventEmitter { + addListener(event: 'request', listener: (request: ClientRequest) => void): this; + addListener( + event: 'response', + listener: (response: ServerResponse | ResponseLike) => void + ): this; + addListener(event: 'error', listener: (error: RequestError | CacheError) => void): this; + on(event: 'request', listener: (request: ClientRequest) => void): this; + on(event: 'response', listener: (response: ServerResponse | ResponseLike) => void): this; + on(event: 'error', listener: (error: RequestError | CacheError) => void): this; + once(event: 'request', listener: (request: ClientRequest) => void): this; + once(event: 'response', listener: (response: ServerResponse | ResponseLike) => void): this; + once(event: 'error', listener: (error: RequestError | CacheError) => void): this; + prependListener(event: 'request', listener: (request: ClientRequest) => void): this; + prependListener( + event: 'response', + listener: (response: ServerResponse | ResponseLike) => void + ): this; + prependListener(event: 'error', listener: (error: RequestError | CacheError) => void): this; + prependOnceListener(event: 'request', listener: (request: ClientRequest) => void): this; + prependOnceListener( + event: 'response', + listener: (response: ServerResponse | ResponseLike) => void + ): this; + prependOnceListener( + event: 'error', + listener: (error: RequestError | CacheError) => void + ): this; + removeListener(event: 'request', listener: (request: ClientRequest) => void): this; + removeListener( + event: 'response', + listener: (response: ServerResponse | ResponseLike) => void + ): this; + removeListener(event: 'error', listener: (error: RequestError | CacheError) => void): this; + off(event: 'request', listener: (request: ClientRequest) => void): this; + off(event: 'response', listener: (response: ServerResponse | ResponseLike) => void): this; + off(event: 'error', listener: (error: RequestError | CacheError) => void): this; + removeAllListeners(event?: 'request' | 'response' | 'error'): this; + listeners(event: 'request'): Array<(request: ClientRequest) => void>; + listeners(event: 'response'): Array<(response: ServerResponse | ResponseLike) => void>; + listeners(event: 'error'): Array<(error: RequestError | CacheError) => void>; + rawListeners(event: 'request'): Array<(request: ClientRequest) => void>; + rawListeners(event: 'response'): Array<(response: ServerResponse | ResponseLike) => void>; + rawListeners(event: 'error'): Array<(error: RequestError | CacheError) => void>; + emit(event: 'request', request: ClientRequest): boolean; + emit(event: 'response', response: ServerResponse | ResponseLike): boolean; + emit(event: 'error', error: RequestError | CacheError): boolean; + eventNames(): Array<'request' | 'response' | 'error'>; + listenerCount(type: 'request' | 'response' | 'error'): number; + } + + type RequestError = RequestErrorCls; + type CacheError = CacheErrorCls; +} + +declare class RequestErrorCls extends Error { + readonly name: 'RequestError'; + + constructor(error: Error); +} +declare class CacheErrorCls extends Error { + readonly name: 'CacheError'; + + constructor(error: Error); +} diff --git a/setup-pandoc/node_modules/@types/cacheable-request/package.json b/setup-pandoc/node_modules/@types/cacheable-request/package.json new file mode 100755 index 000000000..31742dd32 --- /dev/null +++ b/setup-pandoc/node_modules/@types/cacheable-request/package.json @@ -0,0 +1,35 @@ +{ + "name": "@types/cacheable-request", + "version": "6.0.3", + "description": "TypeScript definitions for cacheable-request", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/cacheable-request", + "license": "MIT", + "contributors": [ + { + "name": "BendingBender", + "url": "https://github.com/BendingBender", + "githubUsername": "BendingBender" + }, + { + "name": "Paul Melnikow", + "url": "https://github.com/paulmelnikow", + "githubUsername": "paulmelnikow" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/cacheable-request" + }, + "scripts": {}, + "dependencies": { + "@types/http-cache-semantics": "*", + "@types/keyv": "^3.1.4", + "@types/node": "*", + "@types/responselike": "^1.0.0" + }, + "typesPublisherContentHash": "9345f1216c9d26f9046880c34f6329b2874405d68cf13d1f1f771fbb4d96549f", + "typeScriptVersion": "4.1" +} \ No newline at end of file diff --git a/setup-pandoc/node_modules/@types/keyv/LICENSE b/setup-pandoc/node_modules/@types/keyv/LICENSE new file mode 100755 index 000000000..9e841e7a2 --- /dev/null +++ b/setup-pandoc/node_modules/@types/keyv/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/setup-pandoc/node_modules/@types/keyv/README.md b/setup-pandoc/node_modules/@types/keyv/README.md new file mode 100755 index 000000000..8167fcc38 --- /dev/null +++ b/setup-pandoc/node_modules/@types/keyv/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/keyv` + +# Summary +This package contains type definitions for keyv (https://github.com/lukechilds/keyv). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/keyv. + +### Additional Details + * Last updated: Thu, 17 Mar 2022 05:31:42 GMT + * Dependencies: [@types/node](https://npmjs.com/package/@types/node) + * Global values: none + +# Credits +These definitions were written by [AryloYeung](https://github.com/Arylo), and [BendingBender](https://github.com/BendingBender). diff --git a/setup-pandoc/node_modules/@types/keyv/index.d.ts b/setup-pandoc/node_modules/@types/keyv/index.d.ts new file mode 100755 index 000000000..adca74d90 --- /dev/null +++ b/setup-pandoc/node_modules/@types/keyv/index.d.ts @@ -0,0 +1,90 @@ +// Type definitions for keyv 3.1 +// Project: https://github.com/lukechilds/keyv +// Definitions by: AryloYeung +// BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/// +import { EventEmitter } from 'events'; + +type WithRequiredProperties = T & Required>; + +declare class Keyv extends EventEmitter { + /** + * `this.opts` is an object containing at least the properties listed + * below. However, `Keyv.Options` allows arbitrary properties as well. + * These properties can be specified as the second type parameter to `Keyv`. + */ + opts: WithRequiredProperties< + Keyv.Options, + 'deserialize' | 'namespace' | 'serialize' | 'store' | 'uri' + > & + TOpts; + + /** + * @param opts The options object is also passed through to the storage adapter. Check your storage adapter docs for any extra options. + */ + constructor(opts?: Keyv.Options & TOpts); + /** + * @param uri The connection string URI. + * + * Merged into the options object as options.uri. + * @param opts The options object is also passed through to the storage adapter. Check your storage adapter docs for any extra options. + */ + constructor(uri?: string, opts?: Keyv.Options & TOpts); + + /** Returns the value. */ + get(key: string, options?: { raw?: TRaw }): + Promise<(TRaw extends false + ? TValue + : Keyv.DeserializedData) | undefined>; + /** + * Set a value. + * + * By default keys are persistent. You can set an expiry TTL in milliseconds. + */ + set(key: string, value: TValue, ttl?: number): Promise; + /** + * Deletes an entry. + * + * Returns `true` if the key existed, `false` if not. + */ + delete(key: string): Promise; + /** Delete all entries in the current namespace. */ + clear(): Promise; +} + +declare namespace Keyv { + interface Options { + /** Namespace for the current instance. */ + namespace?: string | undefined; + /** A custom serialization function. */ + serialize?: ((data: DeserializedData) => string) | undefined; + /** A custom deserialization function. */ + deserialize?: ((data: string) => DeserializedData | undefined) | undefined; + /** The connection string URI. */ + uri?: string | undefined; + /** The storage adapter instance to be used by Keyv. */ + store?: Store | undefined; + /** Default TTL. Can be overridden by specififying a TTL on `.set()`. */ + ttl?: number | undefined; + /** Specify an adapter to use. e.g `'redis'` or `'mongodb'`. */ + adapter?: 'redis' | 'mongodb' | 'mongo' | 'sqlite' | 'postgresql' | 'postgres' | 'mysql' | undefined; + + [key: string]: any; + } + + interface DeserializedData { + value: TValue; expires: number | null; + } + + interface Store { + get(key: string): TValue | Promise | undefined; + set(key: string, value: TValue, ttl?: number): any; + delete(key: string): boolean | Promise; + clear(): void | Promise; + } +} + +export = Keyv; diff --git a/setup-pandoc/node_modules/@types/keyv/package.json b/setup-pandoc/node_modules/@types/keyv/package.json new file mode 100755 index 000000000..15d402095 --- /dev/null +++ b/setup-pandoc/node_modules/@types/keyv/package.json @@ -0,0 +1,32 @@ +{ + "name": "@types/keyv", + "version": "3.1.4", + "description": "TypeScript definitions for keyv", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/keyv", + "license": "MIT", + "contributors": [ + { + "name": "AryloYeung", + "url": "https://github.com/Arylo", + "githubUsername": "Arylo" + }, + { + "name": "BendingBender", + "url": "https://github.com/BendingBender", + "githubUsername": "BendingBender" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/keyv" + }, + "scripts": {}, + "dependencies": { + "@types/node": "*" + }, + "typesPublisherContentHash": "e83393e0860475d12e960cede22532e18e129cf659f31f2a0298a88cb5d02d36", + "typeScriptVersion": "3.9" +} \ No newline at end of file diff --git a/setup-pandoc/node_modules/@types/responselike/LICENSE b/setup-pandoc/node_modules/@types/responselike/LICENSE new file mode 100644 index 000000000..9e841e7a2 --- /dev/null +++ b/setup-pandoc/node_modules/@types/responselike/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/setup-pandoc/node_modules/@types/responselike/README.md b/setup-pandoc/node_modules/@types/responselike/README.md new file mode 100644 index 000000000..77d7f21d2 --- /dev/null +++ b/setup-pandoc/node_modules/@types/responselike/README.md @@ -0,0 +1,48 @@ +# Installation +> `npm install --save @types/responselike` + +# Summary +This package contains type definitions for responselike (https://github.com/lukechilds/responselike#readme). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/responselike. +## [index.d.ts](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/responselike/index.d.ts) +````ts +/// + +import { IncomingMessage } from "http"; +import { Stream } from "stream"; + +export = ResponseLike; + +/** + * Returns a streamable response object similar to a [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage). + */ +declare class ResponseLike extends Stream.Readable { + statusCode: number; + headers: { [header: string]: string | string[] | undefined }; + body: Buffer; + url: string; + + /** + * @param statusCode HTTP response status code. + * @param headers HTTP headers object. Keys will be automatically lowercased. + * @param body A Buffer containing the response body. The Buffer contents will be streamable but is also exposed directly as `response.body`. + * @param url Request URL string. + */ + constructor( + statusCode: number, + headers: { [header: string]: string | string[] | undefined }, + body: Buffer, + url: string, + ); +} + +```` + +### Additional Details + * Last updated: Tue, 07 Nov 2023 15:11:36 GMT + * Dependencies: [@types/node](https://npmjs.com/package/@types/node) + +# Credits +These definitions were written by [BendingBender](https://github.com/BendingBender). diff --git a/setup-pandoc/node_modules/@types/responselike/index.d.ts b/setup-pandoc/node_modules/@types/responselike/index.d.ts new file mode 100644 index 000000000..d7ce72b3c --- /dev/null +++ b/setup-pandoc/node_modules/@types/responselike/index.d.ts @@ -0,0 +1,29 @@ +/// + +import { IncomingMessage } from "http"; +import { Stream } from "stream"; + +export = ResponseLike; + +/** + * Returns a streamable response object similar to a [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage). + */ +declare class ResponseLike extends Stream.Readable { + statusCode: number; + headers: { [header: string]: string | string[] | undefined }; + body: Buffer; + url: string; + + /** + * @param statusCode HTTP response status code. + * @param headers HTTP headers object. Keys will be automatically lowercased. + * @param body A Buffer containing the response body. The Buffer contents will be streamable but is also exposed directly as `response.body`. + * @param url Request URL string. + */ + constructor( + statusCode: number, + headers: { [header: string]: string | string[] | undefined }, + body: Buffer, + url: string, + ); +} diff --git a/setup-pandoc/node_modules/@types/responselike/package.json b/setup-pandoc/node_modules/@types/responselike/package.json new file mode 100644 index 000000000..8112f8945 --- /dev/null +++ b/setup-pandoc/node_modules/@types/responselike/package.json @@ -0,0 +1,27 @@ +{ + "name": "@types/responselike", + "version": "1.0.3", + "description": "TypeScript definitions for responselike", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/responselike", + "license": "MIT", + "contributors": [ + { + "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/responselike" + }, + "scripts": {}, + "dependencies": { + "@types/node": "*" + }, + "typesPublisherContentHash": "ea1d581578b0ef6027b7cd6aa25990bb9ee8723d002d0617acf0aa4d3324aa49", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/setup-pandoc/node_modules/cacheable-lookup/LICENSE b/setup-pandoc/node_modules/cacheable-lookup/LICENSE old mode 100644 new mode 100755 diff --git a/setup-pandoc/node_modules/cacheable-lookup/README.md b/setup-pandoc/node_modules/cacheable-lookup/README.md old mode 100644 new mode 100755 index d04be69df..250715592 --- a/setup-pandoc/node_modules/cacheable-lookup/README.md +++ b/setup-pandoc/node_modules/cacheable-lookup/README.md @@ -3,7 +3,7 @@ > A cacheable [`dns.lookup(…)`](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback) that respects TTL :tada: [![Node CI](https://github.com/szmarczak/cacheable-lookup/workflows/Node%20CI/badge.svg)](https://github.com/szmarczak/cacheable-lookup/actions) -[![codecov](https://codecov.io/gh/szmarczak/cacheable-lookup/branch/master/graph/badge.svg)](https://codecov.io/gh/szmarczak/cacheable-lookup) +[![Coverage Status](https://coveralls.io/repos/github/szmarczak/cacheable-lookup/badge.svg?branch=master)](https://coveralls.io/github/szmarczak/cacheable-lookup?branch=master) [![npm](https://img.shields.io/npm/dm/cacheable-lookup.svg)](https://www.npmjs.com/package/cacheable-lookup) [![install size](https://packagephobia.now.sh/badge?p=cacheable-lookup)](https://packagephobia.now.sh/result?p=cacheable-lookup) @@ -14,8 +14,8 @@ Making lots of HTTP requests? You can save some time by caching DNS lookups :zap ### Using the `lookup` option ```js -import http from 'node:http'; -import CacheableLookup from 'cacheable-lookup'; +const http = require('http'); +const CacheableLookup = require('cacheable-lookup'); const cacheable = new CacheableLookup(); @@ -27,14 +27,11 @@ http.get('http://example.com', {lookup: cacheable.lookup}, response => { ### Attaching CacheableLookup to an Agent ```js -import http from 'node:http'; -import https from 'node:https'; -import CacheableLookup from 'cacheable-lookup'; +const http = require('http'); +const CacheableLookup = require('cacheable-lookup'); const cacheable = new CacheableLookup(); - cacheable.install(http.globalAgent); -cacheable.install(https.globalAgent); http.get('http://example.com', response => { // Handle the response here @@ -49,14 +46,14 @@ Returns a new instance of `CacheableLookup`. #### options -Type: `object`\ +Type: `object`
Default: `{}` Options used to cache the DNS lookups. ##### cache -Type: `Map` | [`Keyv`](https://github.com/lukechilds/keyv/)\ +Type: `Map` | [`Keyv`](https://github.com/lukechilds/keyv/)
Default: `new Map()` Custom cache instance. If `undefined`, it will create a new one. @@ -66,9 +63,9 @@ Custom cache instance. If `undefined`, it will create a new one. **Tip**: [`QuickLRU`](https://github.com/sindresorhus/quick-lru) is fully compatible with the Map API, you can use it to limit the amount of cached entries. Example: ```js -import http from 'node:http'; -import CacheableLookup from 'cacheable-lookup'; -import QuickLRU from 'quick-lru'; +const http = require('http'); +const CacheableLookup = require('cacheable-lookup'); +const QuickLRU = require('quick-lru'); const cacheable = new CacheableLookup({ cache: new QuickLRU({maxSize: 1000}) @@ -81,7 +78,7 @@ http.get('http://example.com', {lookup: cacheable.lookup}, response => { ##### options.maxTtl -Type: `number`\ +Type: `number`
Default: `Infinity` The maximum lifetime of the entries received from the specifed DNS server (TTL in seconds). @@ -92,16 +89,16 @@ If set to `0`, it will make a new DNS query each time. ##### options.fallbackDuration -Type: `number`\ +Type: `number`
Default: `3600` (1 hour) When the DNS server responds with `ENOTFOUND` or `ENODATA` and the OS reports that the entry is available, it will use `dns.lookup(...)` directly for the requested hostnames for the specified amount of time (in seconds). -**Note**: You should avoid setting this to `0` unless the provided DNS servers' database is limited to few domains. +If you don't query internal hostnames (such as `localhost`, `database.local` etc.), it is strongly recommended to set this value to `0`. ##### options.errorTtl -Type: `number`\ +Type: `number`
Default: `0.15` The time how long it needs to remember queries that threw `ENOTFOUND` or `ENODATA` (TTL in seconds). @@ -112,19 +109,19 @@ The time how long it needs to remember queries that threw `ENOTFOUND` or `ENODAT ##### options.resolver -Type: `dns.Resolver | dns.promises.Resolver`\ +Type: `dns.Resolver | dns.promises.Resolver`
Default: [`new dns.promises.Resolver()`](https://nodejs.org/api/dns.html#dns_class_dns_resolver) An instance of [DNS Resolver](https://nodejs.org/api/dns.html#dns_class_dns_resolver) used to make DNS queries. ##### options.lookup -Type: `Function`\ +Type: `Function`
Default: [`dns.lookup`](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback) The fallback function to use when the DNS server responds with `ENOTFOUND` or `ENODATA`. -If you don't query internal hostnames (such as `localhost`, `database.local` etc.), it is strongly recommended to set this to `false`. +**Note**: This has no effect if the `fallbackDuration` option is less than `1`. ### Entry object @@ -156,15 +153,9 @@ The timestamp (`Date.now() + ttl * 1000`) when the entry expires. The time in seconds for its lifetime. -#### source - -**Note**: This is not present when falling back to `dns.lookup(...)`! - -Whether this entry was loaded from the cache or came from a query (`cache` or `query`) - ### Entry object (callback-style) -When `options.all` is `false`, then `callback(error, address, family, expires, ttl)` is called.\ +When `options.all` is `false`, then `callback(error, address, family, expires, ttl)` is called.
When `options.all` is `true`, then `callback(error, entries)` is called. ### CacheableLookup instance @@ -181,7 +172,7 @@ The DNS servers used to make queries. Can be overridden - doing so will clear th The asynchronous version of `dns.lookup(…)`. -Returns an [entry object](#entry-object).\ +Returns an [entry object](#entry-object).
If `options.all` is true, returns an array of entry objects. ##### hostname @@ -196,7 +187,7 @@ The same as the [`dns.lookup(…)`](https://nodejs.org/api/dns.html#dns_dns_look #### query(hostname) -An asynchronous function which returns cached DNS lookup entries.\ +An asynchronous function which returns cached DNS lookup entries.
This is the base for `lookupAsync(hostname, options)` and `lookup(hostname, options, callback)`. **Note**: This function has no options. @@ -205,7 +196,7 @@ Returns an array of objects with `address`, `family`, `ttl` and `expires` proper #### queryAndCache(hostname) -An asynchronous function which makes two DNS queries: A and AAAA. The result is cached.\ +An asynchronous function which makes two DNS queries: A and AAAA. The result is cached.
This is used by `query(hostname)` if no entry in the database is present. Returns an array of objects with `address`, `family`, `ttl` and `expires` properties. @@ -242,4 +233,8 @@ Fastest is CacheableLookup#lookupAsync.all ## Related -- [cacheable-request](https://github.com/lukechilds/cacheable-request) - Wrap native HTTP requests with RFC compliant cache support + - [cacheable-request](https://github.com/lukechilds/cacheable-request) - Wrap native HTTP requests with RFC compliant cache support + +## License + +MIT diff --git a/setup-pandoc/node_modules/cacheable-lookup/index.d.ts b/setup-pandoc/node_modules/cacheable-lookup/index.d.ts old mode 100644 new mode 100755 index e805b70f0..528b1e271 --- a/setup-pandoc/node_modules/cacheable-lookup/index.d.ts +++ b/setup-pandoc/node_modules/cacheable-lookup/index.d.ts @@ -4,7 +4,6 @@ import {Agent} from 'http'; type AsyncResolver = dnsPromises.Resolver; export type IPFamily = 4 | 6; -export type EntrySource = 'query' | 'cache'; type TPromise = T | Promise; @@ -53,7 +52,7 @@ export interface Options { * **Note**: This has no effect if the `fallbackDuration` option is less than `1`. * @default dns.lookup */ - lookup?: typeof lookup | false; + lookup?: typeof lookup; } export interface EntryObject { @@ -73,10 +72,6 @@ export interface EntryObject { * The expiration timestamp. */ readonly expires?: number; - /** - * Whether this entry comes from the cache or a query - */ - readonly source?: EntrySource; } export interface LookupOptions { @@ -104,10 +99,10 @@ export default class CacheableLookup { /** * @see https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback */ - lookup(hostname: string, family: IPFamily, callback: (error: NodeJS.ErrnoException | null, address: string, family: IPFamily) => void): void; - lookup(hostname: string, callback: (error: NodeJS.ErrnoException | null, address: string, family: IPFamily) => void): void; - lookup(hostname: string, options: LookupOptions & {all: true}, callback: (error: NodeJS.ErrnoException | null, result: ReadonlyArray) => void): void; - lookup(hostname: string, options: LookupOptions, callback: (error: NodeJS.ErrnoException | null, address: string, family: IPFamily) => void): void; + lookup(hostname: string, family: IPFamily, callback: (error: NodeJS.ErrnoException, address: string, family: IPFamily) => void): void; + lookup(hostname: string, callback: (error: NodeJS.ErrnoException, address: string, family: IPFamily) => void): void; + lookup(hostname: string, options: LookupOptions & {all: true}, callback: (error: NodeJS.ErrnoException, result: ReadonlyArray) => void): void; + lookup(hostname: string, options: LookupOptions, callback: (error: NodeJS.ErrnoException, address: string, family: IPFamily) => void): void; /** * The asynchronous version of `dns.lookup(…)`. */ diff --git a/setup-pandoc/node_modules/cacheable-lookup/package.json b/setup-pandoc/node_modules/cacheable-lookup/package.json old mode 100644 new mode 100755 index d3d696aae..f20991eb7 --- a/setup-pandoc/node_modules/cacheable-lookup/package.json +++ b/setup-pandoc/node_modules/cacheable-lookup/package.json @@ -1,22 +1,18 @@ { "name": "cacheable-lookup", - "version": "7.0.0", - "description": "A cacheable dns.lookup(…) that respects TTL", + "version": "5.0.4", + "description": "A cacheable dns.lookup(…) that respects the TTL", "engines": { - "node": ">=14.16" + "node": ">=10.6.0" }, "files": [ "source", "index.d.ts" ], - "type": "module", - "exports": { - "types": "./index.d.ts", - "default": "./source/index.js" - }, + "main": "source/index.js", + "types": "index.d.ts", "scripts": { - "//test": "xo && nyc --reporter=lcovonly --reporter=text ava && tsd", - "test": "tsd" + "test": "xo && nyc --reporter=lcovonly --reporter=text ava && tsd" }, "repository": { "type": "git", @@ -36,26 +32,14 @@ "homepage": "https://github.com/szmarczak/cacheable-lookup#readme", "devDependencies": { "@types/keyv": "^3.1.1", - "ava": "^4.3.3", + "ava": "^3.8.2", "benchmark": "^2.1.4", "coveralls": "^3.0.9", "keyv": "^4.0.0", "nyc": "^15.0.0", - "quibble": "^0.6.14", - "quick-lru": "^5.1.0", + "proxyquire": "^2.1.3", "tsd": "^0.11.0", + "quick-lru": "^5.1.0", "xo": "^0.25.3" - }, - "ava": { - "nodeArguments": [ - "--loader=quibble" - ] - }, - "xo": { - "rules": { - "unicorn/import-index": "off", - "import/extensions": "off", - "import/no-useless-path-segments": "off" - } } } diff --git a/setup-pandoc/node_modules/cacheable-lookup/source/index.js b/setup-pandoc/node_modules/cacheable-lookup/source/index.js old mode 100644 new mode 100755 index 2accc60b5..21f731e9a --- a/setup-pandoc/node_modules/cacheable-lookup/source/index.js +++ b/setup-pandoc/node_modules/cacheable-lookup/source/index.js @@ -1,14 +1,15 @@ -import { +'use strict'; +const { V4MAPPED, ADDRCONFIG, ALL, - promises as dnsPromises, - lookup as dnsLookup -} from 'node:dns'; -import {promisify} from 'node:util'; -import os from 'node:os'; - -const {Resolver: AsyncResolver} = dnsPromises; + promises: { + Resolver: AsyncResolver + }, + lookup: dnsLookup +} = require('dns'); +const {promisify} = require('util'); +const os = require('os'); const kCacheableLookupCreateConnection = Symbol('cacheableLookupCreateConnection'); const kCacheableLookupInstance = Symbol('cacheableLookupInstance'); @@ -62,26 +63,10 @@ const isIterable = map => { return Symbol.iterator in map; }; -const ignoreNoResultErrors = dnsPromise => { - return dnsPromise.catch(error => { - if ( - error.code === 'ENODATA' || - error.code === 'ENOTFOUND' || - error.code === 'ENOENT' // Windows: name exists, but not this record type - ) { - return []; - } - - throw error; - }); -}; - const ttl = {ttl: true}; const all = {all: true}; -const all4 = {all: true, family: 4}; -const all6 = {all: true, family: 6}; -export default class CacheableLookup { +class CacheableLookup { constructor({ cache = new Map(), maxTtl = Infinity, @@ -95,11 +80,7 @@ export default class CacheableLookup { this._cache = cache; this._resolver = resolver; - this._dnsLookup = lookup && promisify(lookup); - this.stats = { - cache: 0, - query: 0 - }; + this._dnsLookup = promisify(lookup); if (this._resolver instanceof AsyncResolver) { this._resolve4 = this._resolver.resolve4.bind(this._resolver); @@ -115,9 +96,11 @@ export default class CacheableLookup { this._nextRemovalTime = false; this._hostnamesToFallback = new Set(); - this.fallbackDuration = fallbackDuration; + if (fallbackDuration < 1) { + this._fallback = false; + } else { + this._fallback = true; - if (fallbackDuration > 0) { const interval = setInterval(() => { this._hostnamesToFallback.clear(); }, fallbackDuration * 1000); @@ -126,8 +109,6 @@ export default class CacheableLookup { if (interval.unref) { interval.unref(); } - - this._fallbackInterval = interval; } this.lookup = this.lookup.bind(this); @@ -163,7 +144,7 @@ export default class CacheableLookup { if (options.all) { callback(null, result); } else { - callback(null, result.address, result.family, result.expires, result.ttl, result.source); + callback(null, result.address, result.family, result.expires, result.ttl); } }, callback); } @@ -214,23 +195,17 @@ export default class CacheableLookup { } async query(hostname) { - let source = 'cache'; let cached = await this._cache.get(hostname); - if (cached) { - this.stats.cache++; - } - if (!cached) { const pending = this._pending[hostname]; + if (pending) { - this.stats.cache++; cached = await pending; } else { - source = 'query'; const newPromise = this.queryAndCache(hostname); this._pending[hostname] = newPromise; - this.stats.query++; + try { cached = await newPromise; } finally { @@ -240,18 +215,30 @@ export default class CacheableLookup { } cached = cached.map(entry => { - return {...entry, source}; + return {...entry}; }); return cached; } async _resolve(hostname) { + const wrap = async promise => { + try { + return await promise; + } catch (error) { + if (error.code === 'ENODATA' || error.code === 'ENOTFOUND') { + return []; + } + + throw error; + } + }; + // ANY is unsafe as it doesn't trigger new queries in the underlying server. const [A, AAAA] = await Promise.all([ - ignoreNoResultErrors(this._resolve4(hostname, ttl)), - ignoreNoResultErrors(this._resolve6(hostname, ttl)) - ]); + this._resolve4(hostname, ttl), + this._resolve6(hostname, ttl) + ].map(promise => wrap(promise))); let aTtl = 0; let aaaaTtl = 0; @@ -294,21 +281,15 @@ export default class CacheableLookup { async _lookup(hostname) { try { - const [A, AAAA] = await Promise.all([ - // Passing {all: true} doesn't return all IPv4 and IPv6 entries. - // See https://github.com/szmarczak/cacheable-lookup/issues/42 - ignoreNoResultErrors(this._dnsLookup(hostname, all4)), - ignoreNoResultErrors(this._dnsLookup(hostname, all6)) - ]); + const entries = await this._dnsLookup(hostname, { + all: true + }); return { - entries: [ - ...A, - ...AAAA - ], + entries, cacheTtl: 0 }; - } catch { + } catch (_) { return { entries: [], cacheTtl: 0 @@ -345,10 +326,10 @@ export default class CacheableLookup { let query = await this._resolve(hostname); - if (query.entries.length === 0 && this._dnsLookup) { + if (query.entries.length === 0 && this._fallback) { query = await this._lookup(hostname); - if (query.entries.length !== 0 && this.fallbackDuration > 0) { + if (query.entries.length !== 0) { // Use `dns.lookup(...)` for that particular hostname this._hostnamesToFallback.add(hostname); } @@ -450,3 +431,6 @@ export default class CacheableLookup { this._cache.clear(); } } + +module.exports = CacheableLookup; +module.exports.default = CacheableLookup; diff --git a/setup-pandoc/node_modules/form-data-encoder/license b/setup-pandoc/node_modules/cacheable-request/LICENSE similarity index 94% rename from setup-pandoc/node_modules/form-data-encoder/license rename to setup-pandoc/node_modules/cacheable-request/LICENSE index 0c8fa88d3..f27ee9b41 100644 --- a/setup-pandoc/node_modules/form-data-encoder/license +++ b/setup-pandoc/node_modules/cacheable-request/LICENSE @@ -1,6 +1,6 @@ -The MIT License (MIT) +MIT License -Copyright (c) 2021-present Nick K. +Copyright (c) 2017 Luke Childs Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/setup-pandoc/node_modules/cacheable-request/README.md b/setup-pandoc/node_modules/cacheable-request/README.md index ade22aced..725e7e0df 100644 --- a/setup-pandoc/node_modules/cacheable-request/README.md +++ b/setup-pandoc/node_modules/cacheable-request/README.md @@ -1,11 +1,9 @@ -


cacheable logo

- # cacheable-request > Wrap native HTTP requests with RFC compliant cache support -[![tests](https://github.com/jaredwray/cacheable/actions/workflows/tests.yaml/badge.svg)](https://github.com/jaredwray/cacheable/actions/workflows/tests.yaml) -[![codecov](https://codecov.io/gh/jaredwray/cacheable/branch/master/graph/badge.svg?token=LDLaqe4PsI)](https://codecov.io/gh/jaredwray/cacheable) +[![Build Status](https://travis-ci.org/lukechilds/cacheable-request.svg?branch=master)](https://travis-ci.org/lukechilds/cacheable-request) +[![Coverage Status](https://coveralls.io/repos/github/lukechilds/cacheable-request/badge.svg?branch=master)](https://coveralls.io/github/lukechilds/cacheable-request?branch=master) [![npm](https://img.shields.io/npm/dm/cacheable-request.svg)](https://www.npmjs.com/package/cacheable-request) [![npm](https://img.shields.io/npm/v/cacheable-request.svg)](https://www.npmjs.com/package/cacheable-request) @@ -13,69 +11,6 @@ **Note:** This is a low level wrapper around the core HTTP modules, it's not a high level request library. -# Table of Contents -* [Latest Changes](#latest-changes) -* [Features](#features) -* [Install and Usage](#install-and-usage) -* [Storage Adapters](#storage-adapters) -* [API](#api) -* [Using Hooks](#using-hooks) -* [Contributing](#contributing) -* [Ask a Question](#ask-a-question) -* [License](#license) (MIT) - -# Latest Changes - -## Breaking Changes with v10.0.0 -This release contains breaking changes. This is the new way to use this package. - -### Usage Before v10 -```js -import http from 'http'; -import CacheableRequest from 'cacheable-request'; - -// Then instead of -const req = http.request('http://example.com', cb); -req.end(); - -// You can do -const cacheableRequest = new CacheableRequest(http.request); -const cacheReq = cacheableRequest('http://example.com', cb); -cacheReq.on('request', req => req.end()); -// Future requests to 'example.com' will be returned from cache if still valid - -// You pass in any other http.request API compatible method to be wrapped with cache support: -const cacheableRequest = new CacheableRequest(https.request); -const cacheableRequest = new CacheableRequest(electron.net); -``` - -### Usage After v10.1.0 -```js - -import CacheableRequest from 'cacheable-request'; - -// Now You can do -const cacheableRequest = new CacheableRequest(http.request).request(); -const cacheReq = cacheableRequest('http://example.com', cb); -cacheReq.on('request', req => req.end()); -// Future requests to 'example.com' will be returned from cache if still valid - -// You pass in any other http.request API compatible method to be wrapped with cache support: -const cacheableRequest = new CacheableRequest(https.request).request(); -const cacheableRequest = new CacheableRequest(electron.net).request(); -``` - -The biggest change is that when you do a `new` CacheableRequest you now want to call `request` method will give you the instance to use. - -```diff -- const cacheableRequest = new CacheableRequest(http.request); -+ const cacheableRequest = new CacheableRequest(http.request).request(); -``` - -### ESM Support in version 9 and higher. - -We are now using pure esm support in our package. If you need to use commonjs you can use v8 or lower. To learn more about using ESM please read this from `sindresorhus`: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c - ## Features - Only stores cacheable responses as defined by RFC 7234 @@ -85,40 +20,42 @@ We are now using pure esm support in our package. If you need to use commonjs yo - Updates `Age` header on cached responses - Can completely bypass cache on a per request basis - In memory cache by default -- Official support for Redis, Memcache, Etcd, MongoDB, SQLite, PostgreSQL and MySQL storage adapters +- Official support for Redis, MongoDB, SQLite, PostgreSQL and MySQL storage adapters - Easily plug in your own or third-party storage adapters - If DB connection fails, cache is automatically bypassed ([disabled by default](#optsautomaticfailover)) - Adds cache support to any existing HTTP code with minimal changes - Uses [http-cache-semantics](https://github.com/pornel/http-cache-semantics) internally for HTTP RFC 7234 compliance -## Install and Usage +## Install ```shell npm install cacheable-request ``` +## Usage + ```js -import http from 'http'; -import CacheableRequest from 'cacheable-request'; +const http = require('http'); +const CacheableRequest = require('cacheable-request'); // Then instead of const req = http.request('http://example.com', cb); req.end(); // You can do -const cacheableRequest = new CacheableRequest(http.request).createCacheableRequest(); +const cacheableRequest = new CacheableRequest(http.request); const cacheReq = cacheableRequest('http://example.com', cb); cacheReq.on('request', req => req.end()); // Future requests to 'example.com' will be returned from cache if still valid // You pass in any other http.request API compatible method to be wrapped with cache support: -const cacheableRequest = new CacheableRequest(https.request).createCacheableRequest(); -const cacheableRequest = new CacheableRequest(electron.net).createCacheableRequest(); +const cacheableRequest = new CacheableRequest(https.request); +const cacheableRequest = new CacheableRequest(electron.net); ``` ## Storage Adapters -`cacheable-request` uses [Keyv](https://github.com/jaredwray/keyv) to support a wide range of storage adapters. +`cacheable-request` uses [Keyv](https://github.com/lukechilds/keyv) to support a wide range of storage adapters. For example, to use Redis as a cache backend, you just need to install the official Redis Keyv storage adapter: @@ -129,10 +66,10 @@ npm install @keyv/redis And then you can pass `CacheableRequest` your connection string: ```js -const cacheableRequest = new CacheableRequest(http.request, 'redis://user:pass@localhost:6379').createCacheableRequest(); +const cacheableRequest = new CacheableRequest(http.request, 'redis://user:pass@localhost:6379'); ``` -[View all official Keyv storage adapters.](https://github.com/jaredwray/keyv#official-storage-adapters) +[View all official Keyv storage adapters.](https://github.com/lukechilds/keyv#official-storage-adapters) Keyv also supports anything that follows the Map API so it's easy to write your own storage adapter or use a third-party solution. @@ -146,10 +83,10 @@ const storageAdapter = require('./my-storage-adapter'); const QuickLRU = require('quick-lru'); const storageAdapter = new QuickLRU({ maxSize: 1000 }); -const cacheableRequest = new CacheableRequest(http.request, storageAdapter).createCacheableRequest(); +const cacheableRequest = new CacheableRequest(http.request, storageAdapter); ``` -View the [Keyv docs](https://github.com/jaredwray/keyv) for more information on how to use storage adapters. +View the [Keyv docs](https://github.com/lukechilds/keyv) for more information on how to use storage adapters. ## API @@ -168,7 +105,7 @@ Request function to wrap with cache support. Should be [`http.request`](https:// Type: `Keyv storage adapter`
Default: `new Map()` -A [Keyv](https://github.com/jaredwray/keyv) storage adapter instance, or connection string if using with an official Keyv storage adapter. +A [Keyv](https://github.com/lukechilds/keyv) storage adapter instance, or connection string if using with an official Keyv storage adapter. ### Instance @@ -261,75 +198,9 @@ cacheableRequest('example.com', cb) req.end(); }); ``` -**Note:** Database connection errors are emitted here, however `cacheable-request` will attempt to re-request the resource and bypass the cache on a connection error. Therefore a database connection error doesn't necessarily mean the request won't be fulfilled. - - -## Using Hooks -Hooks have been implemented since version `v9` and are very useful to modify response before saving it in cache. You can use hooks to modify response before saving it in cache. - -### Add Hooks - -The hook will pre compute response right before saving it in cache. You can include many hooks and it will run in order you add hook on response object. - -```js -import http from 'http'; -import CacheableRequest from 'cacheable-request'; - -const cacheableRequest = new CacheableRequest(request, cache).request(); - -// adding a hook to decompress response -cacheableRequest.addHook('onResponse', async (value: CacheValue, response: any) => { - const buffer = await pm(gunzip)(value.body); - value.body = buffer.toString(); - return value; -}); -``` - -here is also an example of how to add in the remote address - -```js -import CacheableRequest, {CacheValue} from 'cacheable-request'; - -const cacheableRequest = new CacheableRequest(request, cache).request(); -cacheableRequest.addHook('onResponse', (value: CacheValue, response: any) => { - if (response.connection) { - value.remoteAddress = response.connection.remoteAddress; - } - return value; -}); -``` - -### Remove Hooks - -You can also remove hook by using below - -```js -CacheableRequest.removeHook('onResponse'); -``` - -## How to Contribute - -Cacheable-Request is an open source package and community driven that is maintained regularly. In addtion we have a couple of other guidelines for review: - -* [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) - Our code of conduct -* [CONTRIBUTING.md](CONTRIBUTING.md) - How to contribute to this project -* [SECURITY.md](SECURITY.md) - Security guidelines and supported versions - -## Post an Issue - -To post an issue, navigate to the "Issues" tab in the main repository, and then select "New Issue." Enter a clear title describing the issue, as well as a description containing additional relevant information. Also select the label that best describes your issue type. For a bug report, for example, create an issue with the label "bug." In the description field, Be sure to include replication steps, as well as any relevant error messages. - -If you're reporting a security violation, be sure to check out the project's [security policy](SECURITY.md). - -Please also refer to our [Code of Conduct](CODE_OF_CONDUCT.md) for more information on how to report issues. - -## Ask a Question - -To ask a question, create an issue with the label "question." In the issue description, include the related code and any context that can help us answer your question. +**Note:** Database connection errors are emitted here, however `cacheable-request` will attempt to re-request the resource and bypass the cache on a connection error. Therefore a database connection error doesn't necessarily mean the request won't be fulfilled. ## License -This project is under the [MIT](LICENSE) license. - -MIT © Luke Childs 2017-2021 and Jared Wray 2022+ +MIT © Luke Childs diff --git a/setup-pandoc/node_modules/cacheable-request/dist/index.d.ts b/setup-pandoc/node_modules/cacheable-request/dist/index.d.ts deleted file mode 100644 index 123a8e3ab..000000000 --- a/setup-pandoc/node_modules/cacheable-request/dist/index.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { RequestFn, StorageAdapter, CacheResponse, CacheValue, CacheableOptions, Emitter } from './types.js'; -type Func = (...args: any[]) => any; -declare class CacheableRequest { - cache: StorageAdapter; - cacheRequest: RequestFn; - hooks: Map; - constructor(cacheRequest: RequestFn, cacheAdapter?: StorageAdapter | string); - request: () => (options: CacheableOptions, cb?: (response: CacheResponse) => void) => Emitter; - addHook: (name: string, fn: Func) => void; - removeHook: (name: string) => boolean; - getHook: (name: string) => Func; - runHook: (name: string, ...args: any[]) => Promise; -} -export default CacheableRequest; -export * from './types.js'; -export declare const onResponse = "onResponse"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/setup-pandoc/node_modules/cacheable-request/dist/index.d.ts.map b/setup-pandoc/node_modules/cacheable-request/dist/index.d.ts.map deleted file mode 100644 index 318c87ed6..000000000 --- a/setup-pandoc/node_modules/cacheable-request/dist/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAWA,OAAO,EAAC,SAAS,EAAE,cAAc,EAAE,aAAa,EAAE,UAAU,EAAE,gBAAgB,EAAuC,OAAO,EAA2B,MAAM,YAAY,CAAC;AAE1K,KAAK,IAAI,GAAG,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,CAAC;AAEpC,cAAM,gBAAgB;IACrB,KAAK,EAAE,cAAc,CAAC;IACtB,YAAY,EAAE,SAAS,CAAC;IACxB,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,CAA2B;gBACvC,YAAY,EAAE,SAAS,EAAE,YAAY,CAAC,EAAE,cAAc,GAAG,MAAM;IAmB3E,OAAO,kBAAmB,gBAAgB,kBACzB,aAAa,KAAK,IAAI,KAAG,OAAO,CAuM/C;IAEF,OAAO,SAAU,MAAM,MAAM,IAAI,UAI/B;IAEF,UAAU,SAAU,MAAM,aAA6B;IAEvD,OAAO,SAAU,MAAM,UAA0B;IAEjD,OAAO,SAAgB,MAAM,WAAW,GAAG,EAAE,KAAG,QAAQ,UAAU,CAAC,CAAoC;CACvG;AA6CD,eAAe,gBAAgB,CAAC;AAChC,cAAc,YAAY,CAAC;AAC3B,eAAO,MAAM,UAAU,eAAe,CAAC"} \ No newline at end of file diff --git a/setup-pandoc/node_modules/cacheable-request/dist/index.js b/setup-pandoc/node_modules/cacheable-request/dist/index.js deleted file mode 100644 index ef53ad1b8..000000000 --- a/setup-pandoc/node_modules/cacheable-request/dist/index.js +++ /dev/null @@ -1,275 +0,0 @@ -import EventEmitter from 'node:events'; -import urlLib from 'node:url'; -import crypto from 'node:crypto'; -import stream, { PassThrough as PassThroughStream } from 'node:stream'; -import normalizeUrl from 'normalize-url'; -import getStream from 'get-stream'; -import CachePolicy from 'http-cache-semantics'; -import Response from 'responselike'; -import Keyv from 'keyv'; -import mimicResponse from 'mimic-response'; -import { CacheError, RequestError } from './types.js'; -class CacheableRequest { - constructor(cacheRequest, cacheAdapter) { - this.hooks = new Map(); - this.request = () => (options, cb) => { - let url; - if (typeof options === 'string') { - url = normalizeUrlObject(urlLib.parse(options)); - options = {}; - } - else if (options instanceof urlLib.URL) { - url = normalizeUrlObject(urlLib.parse(options.toString())); - options = {}; - } - else { - const [pathname, ...searchParts] = (options.path ?? '').split('?'); - const search = searchParts.length > 0 - ? `?${searchParts.join('?')}` - : ''; - url = normalizeUrlObject({ ...options, pathname, search }); - } - options = { - headers: {}, - method: 'GET', - cache: true, - strictTtl: false, - automaticFailover: false, - ...options, - ...urlObjectToRequestOptions(url), - }; - options.headers = Object.fromEntries(entries(options.headers).map(([key, value]) => [key.toLowerCase(), value])); - const ee = new EventEmitter(); - const normalizedUrlString = normalizeUrl(urlLib.format(url), { - stripWWW: false, - removeTrailingSlash: false, - stripAuthentication: false, - }); - let key = `${options.method}:${normalizedUrlString}`; - // POST, PATCH, and PUT requests may be cached, depending on the response - // cache-control headers. As a result, the body of the request should be - // added to the cache key in order to avoid collisions. - if (options.body && options.method !== undefined && ['POST', 'PATCH', 'PUT'].includes(options.method)) { - if (options.body instanceof stream.Readable) { - // Streamed bodies should completely skip the cache because they may - // or may not be hashable and in either case the stream would need to - // close before the cache key could be generated. - options.cache = false; - } - else { - key += `:${crypto.createHash('md5').update(options.body).digest('hex')}`; - } - } - let revalidate = false; - let madeRequest = false; - const makeRequest = (options_) => { - madeRequest = true; - let requestErrored = false; - let requestErrorCallback = () => { }; - const requestErrorPromise = new Promise(resolve => { - requestErrorCallback = () => { - if (!requestErrored) { - requestErrored = true; - resolve(); - } - }; - }); - const handler = async (response) => { - if (revalidate) { - response.status = response.statusCode; - const revalidatedPolicy = CachePolicy.fromObject(revalidate.cachePolicy).revalidatedPolicy(options_, response); - if (!revalidatedPolicy.modified) { - response.resume(); - await new Promise(resolve => { - // Skipping 'error' handler cause 'error' event should't be emitted for 304 response - response - .once('end', resolve); - }); - const headers = convertHeaders(revalidatedPolicy.policy.responseHeaders()); - response = new Response({ statusCode: revalidate.statusCode, headers, body: revalidate.body, url: revalidate.url }); - response.cachePolicy = revalidatedPolicy.policy; - response.fromCache = true; - } - } - if (!response.fromCache) { - response.cachePolicy = new CachePolicy(options_, response, options_); - response.fromCache = false; - } - let clonedResponse; - if (options_.cache && response.cachePolicy.storable()) { - clonedResponse = cloneResponse(response); - (async () => { - try { - const bodyPromise = getStream.buffer(response); - await Promise.race([ - requestErrorPromise, - new Promise(resolve => response.once('end', resolve)), - new Promise(resolve => response.once('close', resolve)), // eslint-disable-line no-promise-executor-return - ]); - const body = await bodyPromise; - let value = { - url: response.url, - statusCode: response.fromCache ? revalidate.statusCode : response.statusCode, - body, - cachePolicy: response.cachePolicy.toObject(), - }; - let ttl = options_.strictTtl ? response.cachePolicy.timeToLive() : undefined; - if (options_.maxTtl) { - ttl = ttl ? Math.min(ttl, options_.maxTtl) : options_.maxTtl; - } - if (this.hooks.size > 0) { - /* eslint-disable no-await-in-loop */ - for (const key_ of this.hooks.keys()) { - value = await this.runHook(key_, value, response); - } - /* eslint-enable no-await-in-loop */ - } - await this.cache.set(key, value, ttl); - } - catch (error) { - ee.emit('error', new CacheError(error)); - } - })(); - } - else if (options_.cache && revalidate) { - (async () => { - try { - await this.cache.delete(key); - } - catch (error) { - ee.emit('error', new CacheError(error)); - } - })(); - } - ee.emit('response', clonedResponse ?? response); - if (typeof cb === 'function') { - cb(clonedResponse ?? response); - } - }; - try { - const request_ = this.cacheRequest(options_, handler); - request_.once('error', requestErrorCallback); - request_.once('abort', requestErrorCallback); - request_.once('destroy', requestErrorCallback); - ee.emit('request', request_); - } - catch (error) { - ee.emit('error', new RequestError(error)); - } - }; - (async () => { - const get = async (options_) => { - await Promise.resolve(); - const cacheEntry = options_.cache ? await this.cache.get(key) : undefined; - if (cacheEntry === undefined && !options_.forceRefresh) { - makeRequest(options_); - return; - } - const policy = CachePolicy.fromObject(cacheEntry.cachePolicy); - if (policy.satisfiesWithoutRevalidation(options_) && !options_.forceRefresh) { - const headers = convertHeaders(policy.responseHeaders()); - const response = new Response({ statusCode: cacheEntry.statusCode, headers, body: cacheEntry.body, url: cacheEntry.url }); - response.cachePolicy = policy; - response.fromCache = true; - ee.emit('response', response); - if (typeof cb === 'function') { - cb(response); - } - } - else if (policy.satisfiesWithoutRevalidation(options_) && Date.now() >= policy.timeToLive() && options_.forceRefresh) { - await this.cache.delete(key); - options_.headers = policy.revalidationHeaders(options_); - makeRequest(options_); - } - else { - revalidate = cacheEntry; - options_.headers = policy.revalidationHeaders(options_); - makeRequest(options_); - } - }; - const errorHandler = (error) => ee.emit('error', new CacheError(error)); - if (this.cache instanceof Keyv) { - const cachek = this.cache; - cachek.once('error', errorHandler); - ee.on('error', () => cachek.removeListener('error', errorHandler)); - ee.on('response', () => cachek.removeListener('error', errorHandler)); - } - try { - await get(options); - } - catch (error) { - if (options.automaticFailover && !madeRequest) { - makeRequest(options); - } - ee.emit('error', new CacheError(error)); - } - })(); - return ee; - }; - this.addHook = (name, fn) => { - if (!this.hooks.has(name)) { - this.hooks.set(name, fn); - } - }; - this.removeHook = (name) => this.hooks.delete(name); - this.getHook = (name) => this.hooks.get(name); - this.runHook = async (name, ...args) => this.hooks.get(name)?.(...args); - if (cacheAdapter instanceof Keyv) { - this.cache = cacheAdapter; - } - else if (typeof cacheAdapter === 'string') { - this.cache = new Keyv({ - uri: cacheAdapter, - namespace: 'cacheable-request', - }); - } - else { - this.cache = new Keyv({ - store: cacheAdapter, - namespace: 'cacheable-request', - }); - } - this.request = this.request.bind(this); - this.cacheRequest = cacheRequest; - } -} -const entries = Object.entries; -const cloneResponse = (response) => { - const clone = new PassThroughStream({ autoDestroy: false }); - mimicResponse(response, clone); - return response.pipe(clone); -}; -const urlObjectToRequestOptions = (url) => { - const options = { ...url }; - options.path = `${url.pathname || '/'}${url.search || ''}`; - delete options.pathname; - delete options.search; - return options; -}; -const normalizeUrlObject = (url) => -// If url was parsed by url.parse or new URL: -// - hostname will be set -// - host will be hostname[:port] -// - port will be set if it was explicit in the parsed string -// Otherwise, url was from request options: -// - hostname or host may be set -// - host shall not have port encoded -({ - protocol: url.protocol, - auth: url.auth, - hostname: url.hostname || url.host || 'localhost', - port: url.port, - pathname: url.pathname, - search: url.search, -}); -const convertHeaders = (headers) => { - const result = []; - for (const name of Object.keys(headers)) { - result[name.toLowerCase()] = headers[name]; - } - return result; -}; -export default CacheableRequest; -export * from './types.js'; -export const onResponse = 'onResponse'; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/setup-pandoc/node_modules/cacheable-request/dist/index.js.map b/setup-pandoc/node_modules/cacheable-request/dist/index.js.map deleted file mode 100644 index bad71ec81..000000000 --- a/setup-pandoc/node_modules/cacheable-request/dist/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,YAAY,MAAM,aAAa,CAAC;AACvC,OAAO,MAAM,MAAM,UAAU,CAAC;AAC9B,OAAO,MAAM,MAAM,aAAa,CAAC;AACjC,OAAO,MAAM,EAAE,EAAC,WAAW,IAAI,iBAAiB,EAAC,MAAM,aAAa,CAAC;AAErE,OAAO,YAAY,MAAM,eAAe,CAAC;AACzC,OAAO,SAAS,MAAM,YAAY,CAAC;AACnC,OAAO,WAAW,MAAM,sBAAsB,CAAC;AAC/C,OAAO,QAAQ,MAAM,cAAc,CAAC;AACpC,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,aAAa,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAoF,UAAU,EAAE,YAAY,EAAoC,MAAM,YAAY,CAAC;AAI1K,MAAM,gBAAgB;IAIrB,YAAY,YAAuB,EAAE,YAAsC;QAD3E,UAAK,GAAsB,IAAI,GAAG,EAAgB,CAAC;QAoBnD,YAAO,GAAG,GAAG,EAAE,CAAC,CAAC,OAAyB,EACzC,EAAsC,EAAW,EAAE;YACnD,IAAI,GAAG,CAAC;YACR,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;gBAChC,GAAG,GAAG,kBAAkB,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;gBAChD,OAAO,GAAG,EAAE,CAAC;aACb;iBAAM,IAAI,OAAO,YAAY,MAAM,CAAC,GAAG,EAAE;gBACzC,GAAG,GAAG,kBAAkB,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC;gBAC3D,OAAO,GAAG,EAAE,CAAC;aACb;iBAAM;gBACN,MAAM,CAAC,QAAQ,EAAE,GAAG,WAAW,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;gBACnE,MAAM,MAAM,GAAG,WAAW,CAAC,MAAM,GAAG,CAAC;oBACpC,CAAC,CAAC,IAAI,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE;oBAC7B,CAAC,CAAC,EAAE,CAAC;gBACN,GAAG,GAAG,kBAAkB,CAAC,EAAC,GAAG,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAC,CAAC,CAAC;aACzD;YAED,OAAO,GAAG;gBACT,OAAO,EAAE,EAAE;gBACX,MAAM,EAAE,KAAK;gBACb,KAAK,EAAE,IAAI;gBACX,SAAS,EAAE,KAAK;gBAChB,iBAAiB,EAAE,KAAK;gBACxB,GAAG,OAAO;gBACV,GAAG,yBAAyB,CAAC,GAAG,CAAC;aACjC,CAAC;YACF,OAAO,CAAC,OAAO,GAAG,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,CAAE,GAAc,CAAC,WAAW,EAAE,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC;YAC7H,MAAM,EAAE,GAAY,IAAI,YAAY,EAAa,CAAC;YAClD,MAAM,mBAAmB,GAAG,YAAY,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE;gBAC5D,QAAQ,EAAE,KAAK;gBACf,mBAAmB,EAAE,KAAK;gBAC1B,mBAAmB,EAAE,KAAK;aAC1B,CAAC,CAAC;YACH,IAAI,GAAG,GAAG,GAAG,OAAO,CAAC,MAAM,IAAI,mBAAmB,EAAE,CAAC;YACrD,yEAAyE;YACzE,wEAAwE;YACxE,uDAAuD;YACvD,IAAI,OAAO,CAAC,IAAI,IAAI,OAAO,CAAC,MAAM,KAAK,SAAS,IAAI,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE;gBACtG,IAAI,OAAO,CAAC,IAAI,YAAY,MAAM,CAAC,QAAQ,EAAE;oBAC5C,oEAAoE;oBACpE,qEAAqE;oBACrE,iDAAiD;oBACjD,OAAO,CAAC,KAAK,GAAG,KAAK,CAAC;iBACtB;qBAAM;oBACN,GAAG,IAAI,IAAI,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;iBACzE;aACD;YAED,IAAI,UAAU,GAAQ,KAAK,CAAC;YAC5B,IAAI,WAAW,GAAG,KAAK,CAAC;YACxB,MAAM,WAAW,GAAG,CAAC,QAAa,EAAE,EAAE;gBACrC,WAAW,GAAG,IAAI,CAAC;gBACnB,IAAI,cAAc,GAAG,KAAK,CAAC;gBAC3B,IAAI,oBAAoB,GAA6B,GAAG,EAAE,GAAkB,CAAC,CAAC;gBAE9E,MAAM,mBAAmB,GAAG,IAAI,OAAO,CAAO,OAAO,CAAC,EAAE;oBACvD,oBAAoB,GAAG,GAAG,EAAE;wBAC3B,IAAI,CAAC,cAAc,EAAE;4BACpB,cAAc,GAAG,IAAI,CAAC;4BACtB,OAAO,EAAE,CAAC;yBACV;oBACF,CAAC,CAAC;gBACH,CAAC,CAAC,CAAC;gBACH,MAAM,OAAO,GAAG,KAAK,EAAE,QAAa,EAAE,EAAE;oBACvC,IAAI,UAAU,EAAE;wBACf,QAAQ,CAAC,MAAM,GAAG,QAAQ,CAAC,UAAU,CAAC;wBACtC,MAAM,iBAAiB,GAAG,WAAW,CAAC,UAAU,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC,iBAAiB,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;wBAC/G,IAAI,CAAC,iBAAiB,CAAC,QAAQ,EAAE;4BAChC,QAAQ,CAAC,MAAM,EAAE,CAAC;4BAClB,MAAM,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE;gCAC3B,oFAAoF;gCACpF,QAAQ;qCACN,IAAI,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;4BACxB,CAAC,CAAC,CAAC;4BACH,MAAM,OAAO,GAAG,cAAc,CAAC,iBAAiB,CAAC,MAAM,CAAC,eAAe,EAAE,CAAC,CAAC;4BAC3E,QAAQ,GAAG,IAAI,QAAQ,CAAC,EAAC,UAAU,EAAE,UAAU,CAAC,UAAU,EAAE,OAAO,EAAE,IAAI,EAAE,UAAU,CAAC,IAAI,EAAE,GAAG,EAAE,UAAU,CAAC,GAAG,EAAC,CAAC,CAAC;4BAClH,QAAQ,CAAC,WAAW,GAAG,iBAAiB,CAAC,MAAM,CAAC;4BAChD,QAAQ,CAAC,SAAS,GAAG,IAAI,CAAC;yBAC1B;qBACD;oBAED,IAAI,CAAC,QAAQ,CAAC,SAAS,EAAE;wBACxB,QAAQ,CAAC,WAAW,GAAG,IAAI,WAAW,CAAC,QAAQ,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAAC;wBACrE,QAAQ,CAAC,SAAS,GAAG,KAAK,CAAC;qBAC3B;oBAED,IAAI,cAAc,CAAC;oBACnB,IAAI,QAAQ,CAAC,KAAK,IAAI,QAAQ,CAAC,WAAW,CAAC,QAAQ,EAAE,EAAE;wBACtD,cAAc,GAAG,aAAa,CAAC,QAAQ,CAAC,CAAC;wBACzC,CAAC,KAAK,IAAI,EAAE;4BACX,IAAI;gCACH,MAAM,WAAW,GAAG,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;gCAC/C,MAAM,OAAO,CAAC,IAAI,CAAC;oCAClB,mBAAmB;oCACnB,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;oCACrD,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,EAAE,iDAAiD;iCAC1G,CAAC,CAAC;gCACH,MAAM,IAAI,GAAG,MAAM,WAAW,CAAC;gCAC/B,IAAI,KAAK,GAAe;oCACvB,GAAG,EAAE,QAAQ,CAAC,GAAG;oCACjB,UAAU,EAAE,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC,CAAC,QAAQ,CAAC,UAAU;oCAC5E,IAAI;oCACJ,WAAW,EAAE,QAAQ,CAAC,WAAW,CAAC,QAAQ,EAAE;iCAC5C,CAAC;gCACF,IAAI,GAAG,GAAG,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,QAAQ,CAAC,WAAW,CAAC,UAAU,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;gCAC7E,IAAI,QAAQ,CAAC,MAAM,EAAE;oCACpB,GAAG,GAAG,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC;iCAC7D;gCAED,IAAI,IAAI,CAAC,KAAK,CAAC,IAAI,GAAG,CAAC,EAAE;oCACxB,qCAAqC;oCACrC,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,EAAE;wCACrC,KAAK,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAC;qCAClD;oCACD,oCAAoC;iCACpC;gCAED,MAAM,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,EAAE,GAAG,CAAC,CAAC;6BACtC;4BAAC,OAAO,KAAU,EAAE;gCACpB,EAAE,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC;6BACxC;wBACF,CAAC,CAAC,EAAE,CAAC;qBACL;yBAAM,IAAI,QAAQ,CAAC,KAAK,IAAI,UAAU,EAAE;wBACxC,CAAC,KAAK,IAAI,EAAE;4BACX,IAAI;gCACH,MAAM,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;6BAC7B;4BAAC,OAAO,KAAU,EAAE;gCACpB,EAAE,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC;6BACxC;wBACF,CAAC,CAAC,EAAE,CAAC;qBACL;oBAED,EAAE,CAAC,IAAI,CAAC,UAAU,EAAE,cAAc,IAAI,QAAQ,CAAC,CAAC;oBAChD,IAAI,OAAO,EAAE,KAAK,UAAU,EAAE;wBAC7B,EAAE,CAAC,cAAc,IAAI,QAAQ,CAAC,CAAC;qBAC/B;gBACF,CAAC,CAAC;gBAEF,IAAI;oBACH,MAAM,QAAQ,GAAG,IAAI,CAAC,YAAY,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;oBACtD,QAAQ,CAAC,IAAI,CAAC,OAAO,EAAE,oBAAoB,CAAC,CAAC;oBAC7C,QAAQ,CAAC,IAAI,CAAC,OAAO,EAAE,oBAAoB,CAAC,CAAC;oBAC7C,QAAQ,CAAC,IAAI,CAAC,SAAS,EAAE,oBAAoB,CAAC,CAAC;oBAC/C,EAAE,CAAC,IAAI,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;iBAC7B;gBAAC,OAAO,KAAU,EAAE;oBACpB,EAAE,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC;iBAC1C;YACF,CAAC,CAAC;YAEF,CAAC,KAAK,IAAI,EAAE;gBACX,MAAM,GAAG,GAAG,KAAK,EAAE,QAAa,EAAE,EAAE;oBACnC,MAAM,OAAO,CAAC,OAAO,EAAE,CAAC;oBACxB,MAAM,UAAU,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;oBAE1E,IAAI,UAAU,KAAK,SAAS,IAAI,CAAC,QAAQ,CAAC,YAAY,EAAE;wBACvD,WAAW,CAAC,QAAQ,CAAC,CAAC;wBACtB,OAAO;qBACP;oBAED,MAAM,MAAM,GAAG,WAAW,CAAC,UAAU,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC;oBAC9D,IAAI,MAAM,CAAC,4BAA4B,CAAC,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC,YAAY,EAAE;wBAC5E,MAAM,OAAO,GAAG,cAAc,CAAC,MAAM,CAAC,eAAe,EAAE,CAAC,CAAC;wBACzD,MAAM,QAAQ,GAAQ,IAAI,QAAQ,CAAC,EAAC,UAAU,EAAE,UAAU,CAAC,UAAU,EAAE,OAAO,EAAE,IAAI,EAAE,UAAU,CAAC,IAAI,EAAE,GAAG,EAAE,UAAU,CAAC,GAAG,EAAC,CAAC,CAAC;wBAC7H,QAAQ,CAAC,WAAW,GAAG,MAAM,CAAC;wBAC9B,QAAQ,CAAC,SAAS,GAAG,IAAI,CAAC;wBAC1B,EAAE,CAAC,IAAI,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;wBAC9B,IAAI,OAAO,EAAE,KAAK,UAAU,EAAE;4BAC7B,EAAE,CAAC,QAAQ,CAAC,CAAC;yBACb;qBACD;yBAAM,IAAI,MAAM,CAAC,4BAA4B,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,GAAG,EAAE,IAAI,MAAM,CAAC,UAAU,EAAE,IAAI,QAAQ,CAAC,YAAY,EAAE;wBACvH,MAAM,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;wBAC7B,QAAQ,CAAC,OAAO,GAAG,MAAM,CAAC,mBAAmB,CAAC,QAAQ,CAAC,CAAC;wBACxD,WAAW,CAAC,QAAQ,CAAC,CAAC;qBACtB;yBAAM;wBACN,UAAU,GAAG,UAAU,CAAC;wBACxB,QAAQ,CAAC,OAAO,GAAG,MAAM,CAAC,mBAAmB,CAAC,QAAQ,CAAC,CAAC;wBACxD,WAAW,CAAC,QAAQ,CAAC,CAAC;qBACtB;gBACF,CAAC,CAAC;gBAEF,MAAM,YAAY,GAAG,CAAC,KAAY,EAAE,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC;gBAC/E,IAAI,IAAI,CAAC,KAAK,YAAY,IAAI,EAAE;oBAC/B,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC;oBAC1B,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC;oBACnC,EAAE,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC;oBACnE,EAAE,CAAC,EAAE,CAAC,UAAU,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC;iBACtE;gBAED,IAAI;oBACH,MAAM,GAAG,CAAC,OAAO,CAAC,CAAC;iBACnB;gBAAC,OAAO,KAAU,EAAE;oBACpB,IAAI,OAAO,CAAC,iBAAiB,IAAI,CAAC,WAAW,EAAE;wBAC9C,WAAW,CAAC,OAAO,CAAC,CAAC;qBACrB;oBAED,EAAE,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC;iBACxC;YACF,CAAC,CAAC,EAAE,CAAC;YAEL,OAAO,EAAE,CAAC;QACX,CAAC,CAAC;QAEF,YAAO,GAAG,CAAC,IAAY,EAAE,EAAQ,EAAE,EAAE;YACpC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE;gBAC1B,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;aACzB;QACF,CAAC,CAAC;QAEF,eAAU,GAAG,CAAC,IAAY,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QAEvD,YAAO,GAAG,CAAC,IAAY,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAEjD,YAAO,GAAG,KAAK,EAAE,IAAY,EAAE,GAAG,IAAW,EAAuB,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC;QAtOtG,IAAI,YAAY,YAAY,IAAI,EAAE;YACjC,IAAI,CAAC,KAAK,GAAG,YAAY,CAAC;SAC1B;aAAM,IAAI,OAAO,YAAY,KAAK,QAAQ,EAAE;YAC5C,IAAI,CAAC,KAAK,GAAG,IAAI,IAAI,CAAC;gBACrB,GAAG,EAAE,YAAY;gBACjB,SAAS,EAAE,mBAAmB;aAC9B,CAAC,CAAC;SACH;aAAM;YACN,IAAI,CAAC,KAAK,GAAG,IAAI,IAAI,CAAC;gBACrB,KAAK,EAAE,YAAY;gBACnB,SAAS,EAAE,mBAAmB;aAC9B,CAAC,CAAC;SACH;QAED,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACvC,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;IAClC,CAAC;CAuND;AAED,MAAM,OAAO,GAAG,MAAM,CAAC,OAAyD,CAAC;AAEjF,MAAM,aAAa,GAAG,CAAC,QAAyB,EAAE,EAAE;IACnD,MAAM,KAAK,GAAG,IAAI,iBAAiB,CAAC,EAAC,WAAW,EAAE,KAAK,EAAC,CAAC,CAAC;IAC1D,aAAa,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;IAE/B,OAAO,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC7B,CAAC,CAAC;AAEF,MAAM,yBAAyB,GAAG,CAAC,GAAQ,EAAE,EAAE;IAC9C,MAAM,OAAO,GAAc,EAAC,GAAG,GAAG,EAAC,CAAC;IACpC,OAAO,CAAC,IAAI,GAAG,GAAG,GAAG,CAAC,QAAQ,IAAI,GAAG,GAAG,GAAG,CAAC,MAAM,IAAI,EAAE,EAAE,CAAC;IAC3D,OAAO,OAAO,CAAC,QAAQ,CAAC;IACxB,OAAO,OAAO,CAAC,MAAM,CAAC;IACtB,OAAO,OAAO,CAAC;AAChB,CAAC,CAAC;AAEF,MAAM,kBAAkB,GAAG,CAAC,GAAQ,EAAE,EAAE;AACvC,6CAA6C;AAC7C,yBAAyB;AACzB,iCAAiC;AACjC,6DAA6D;AAC7D,2CAA2C;AAC3C,gCAAgC;AAChC,qCAAqC;AACrC,CAAC;IACA,QAAQ,EAAE,GAAG,CAAC,QAAQ;IACtB,IAAI,EAAE,GAAG,CAAC,IAAI;IACd,QAAQ,EAAE,GAAG,CAAC,QAAQ,IAAI,GAAG,CAAC,IAAI,IAAI,WAAW;IACjD,IAAI,EAAE,GAAG,CAAC,IAAI;IACd,QAAQ,EAAE,GAAG,CAAC,QAAQ;IACtB,MAAM,EAAE,GAAG,CAAC,MAAM;CAClB,CAAC,CAAC;AAEJ,MAAM,cAAc,GAAG,CAAC,OAA4B,EAAE,EAAE;IACvD,MAAM,MAAM,GAAQ,EAAE,CAAC;IACvB,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE;QACxC,MAAM,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;KAC3C;IAED,OAAO,MAAM,CAAC;AACf,CAAC,CAAC;AAEF,eAAe,gBAAgB,CAAC;AAChC,cAAc,YAAY,CAAC;AAC3B,MAAM,CAAC,MAAM,UAAU,GAAG,YAAY,CAAC","sourcesContent":["import EventEmitter from 'node:events';\nimport urlLib from 'node:url';\nimport crypto from 'node:crypto';\nimport stream, {PassThrough as PassThroughStream} from 'node:stream';\nimport {IncomingMessage} from 'node:http';\nimport normalizeUrl from 'normalize-url';\nimport getStream from 'get-stream';\nimport CachePolicy from 'http-cache-semantics';\nimport Response from 'responselike';\nimport Keyv from 'keyv';\nimport mimicResponse from 'mimic-response';\nimport {RequestFn, StorageAdapter, CacheResponse, CacheValue, CacheableOptions, UrlOption, CacheError, RequestError, Emitter, CacheableRequestFunction} from './types.js';\n\ntype Func = (...args: any[]) => any;\n\nclass CacheableRequest {\n\tcache: StorageAdapter;\n\tcacheRequest: RequestFn;\n\thooks: Map = new Map();\n\tconstructor(cacheRequest: RequestFn, cacheAdapter?: StorageAdapter | string) {\n\t\tif (cacheAdapter instanceof Keyv) {\n\t\t\tthis.cache = cacheAdapter;\n\t\t} else if (typeof cacheAdapter === 'string') {\n\t\t\tthis.cache = new Keyv({\n\t\t\t\turi: cacheAdapter,\n\t\t\t\tnamespace: 'cacheable-request',\n\t\t\t});\n\t\t} else {\n\t\t\tthis.cache = new Keyv({\n\t\t\t\tstore: cacheAdapter,\n\t\t\t\tnamespace: 'cacheable-request',\n\t\t\t});\n\t\t}\n\n\t\tthis.request = this.request.bind(this);\n\t\tthis.cacheRequest = cacheRequest;\n\t}\n\n\trequest = () => (options: CacheableOptions,\n\t\tcb?: (response: CacheResponse) => void): Emitter => {\n\t\tlet url;\n\t\tif (typeof options === 'string') {\n\t\t\turl = normalizeUrlObject(urlLib.parse(options));\n\t\t\toptions = {};\n\t\t} else if (options instanceof urlLib.URL) {\n\t\t\turl = normalizeUrlObject(urlLib.parse(options.toString()));\n\t\t\toptions = {};\n\t\t} else {\n\t\t\tconst [pathname, ...searchParts] = (options.path ?? '').split('?');\n\t\t\tconst search = searchParts.length > 0\n\t\t\t\t? `?${searchParts.join('?')}`\n\t\t\t\t: '';\n\t\t\turl = normalizeUrlObject({...options, pathname, search});\n\t\t}\n\n\t\toptions = {\n\t\t\theaders: {},\n\t\t\tmethod: 'GET',\n\t\t\tcache: true,\n\t\t\tstrictTtl: false,\n\t\t\tautomaticFailover: false,\n\t\t\t...options,\n\t\t\t...urlObjectToRequestOptions(url),\n\t\t};\n\t\toptions.headers = Object.fromEntries(entries(options.headers).map(([key, value]) => [(key as string).toLowerCase(), value]));\n\t\tconst ee: Emitter = new EventEmitter() as Emitter;\n\t\tconst normalizedUrlString = normalizeUrl(urlLib.format(url), {\n\t\t\tstripWWW: false, // eslint-disable-line @typescript-eslint/naming-convention\n\t\t\tremoveTrailingSlash: false,\n\t\t\tstripAuthentication: false,\n\t\t});\n\t\tlet key = `${options.method}:${normalizedUrlString}`;\n\t\t// POST, PATCH, and PUT requests may be cached, depending on the response\n\t\t// cache-control headers. As a result, the body of the request should be\n\t\t// added to the cache key in order to avoid collisions.\n\t\tif (options.body && options.method !== undefined && ['POST', 'PATCH', 'PUT'].includes(options.method)) {\n\t\t\tif (options.body instanceof stream.Readable) {\n\t\t\t\t// Streamed bodies should completely skip the cache because they may\n\t\t\t\t// or may not be hashable and in either case the stream would need to\n\t\t\t\t// close before the cache key could be generated.\n\t\t\t\toptions.cache = false;\n\t\t\t} else {\n\t\t\t\tkey += `:${crypto.createHash('md5').update(options.body).digest('hex')}`;\n\t\t\t}\n\t\t}\n\n\t\tlet revalidate: any = false;\n\t\tlet madeRequest = false;\n\t\tconst makeRequest = (options_: any) => {\n\t\t\tmadeRequest = true;\n\t\t\tlet requestErrored = false;\n\t\t\tlet requestErrorCallback: (...args: any[]) => void = () => {/* do nothing */};\n\n\t\t\tconst requestErrorPromise = new Promise(resolve => {\n\t\t\t\trequestErrorCallback = () => {\n\t\t\t\t\tif (!requestErrored) {\n\t\t\t\t\t\trequestErrored = true;\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t});\n\t\t\tconst handler = async (response: any) => {\n\t\t\t\tif (revalidate) {\n\t\t\t\t\tresponse.status = response.statusCode;\n\t\t\t\t\tconst revalidatedPolicy = CachePolicy.fromObject(revalidate.cachePolicy).revalidatedPolicy(options_, response);\n\t\t\t\t\tif (!revalidatedPolicy.modified) {\n\t\t\t\t\t\tresponse.resume();\n\t\t\t\t\t\tawait new Promise(resolve => {\n\t\t\t\t\t\t\t// Skipping 'error' handler cause 'error' event should't be emitted for 304 response\n\t\t\t\t\t\t\tresponse\n\t\t\t\t\t\t\t\t.once('end', resolve);\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst headers = convertHeaders(revalidatedPolicy.policy.responseHeaders());\n\t\t\t\t\t\tresponse = new Response({statusCode: revalidate.statusCode, headers, body: revalidate.body, url: revalidate.url});\n\t\t\t\t\t\tresponse.cachePolicy = revalidatedPolicy.policy;\n\t\t\t\t\t\tresponse.fromCache = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!response.fromCache) {\n\t\t\t\t\tresponse.cachePolicy = new CachePolicy(options_, response, options_);\n\t\t\t\t\tresponse.fromCache = false;\n\t\t\t\t}\n\n\t\t\t\tlet clonedResponse;\n\t\t\t\tif (options_.cache && response.cachePolicy.storable()) {\n\t\t\t\t\tclonedResponse = cloneResponse(response);\n\t\t\t\t\t(async () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst bodyPromise = getStream.buffer(response);\n\t\t\t\t\t\t\tawait Promise.race([\n\t\t\t\t\t\t\t\trequestErrorPromise,\n\t\t\t\t\t\t\t\tnew Promise(resolve => response.once('end', resolve)), // eslint-disable-line no-promise-executor-return\n\t\t\t\t\t\t\t\tnew Promise(resolve => response.once('close', resolve)), // eslint-disable-line no-promise-executor-return\n\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t\tconst body = await bodyPromise;\n\t\t\t\t\t\t\tlet value: CacheValue = {\n\t\t\t\t\t\t\t\turl: response.url,\n\t\t\t\t\t\t\t\tstatusCode: response.fromCache ? revalidate.statusCode : response.statusCode,\n\t\t\t\t\t\t\t\tbody,\n\t\t\t\t\t\t\t\tcachePolicy: response.cachePolicy.toObject(),\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tlet ttl = options_.strictTtl ? response.cachePolicy.timeToLive() : undefined;\n\t\t\t\t\t\t\tif (options_.maxTtl) {\n\t\t\t\t\t\t\t\tttl = ttl ? Math.min(ttl, options_.maxTtl) : options_.maxTtl;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (this.hooks.size > 0) {\n\t\t\t\t\t\t\t\t/* eslint-disable no-await-in-loop */\n\t\t\t\t\t\t\t\tfor (const key_ of this.hooks.keys()) {\n\t\t\t\t\t\t\t\t\tvalue = await this.runHook(key_, value, response);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t/* eslint-enable no-await-in-loop */\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tawait this.cache.set(key, value, ttl);\n\t\t\t\t\t\t} catch (error: any) {\n\t\t\t\t\t\t\tee.emit('error', new CacheError(error));\n\t\t\t\t\t\t}\n\t\t\t\t\t})();\n\t\t\t\t} else if (options_.cache && revalidate) {\n\t\t\t\t\t(async () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait this.cache.delete(key);\n\t\t\t\t\t\t} catch (error: any) {\n\t\t\t\t\t\t\tee.emit('error', new CacheError(error));\n\t\t\t\t\t\t}\n\t\t\t\t\t})();\n\t\t\t\t}\n\n\t\t\t\tee.emit('response', clonedResponse ?? response);\n\t\t\t\tif (typeof cb === 'function') {\n\t\t\t\t\tcb(clonedResponse ?? response);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\tconst request_ = this.cacheRequest(options_, handler);\n\t\t\t\trequest_.once('error', requestErrorCallback);\n\t\t\t\trequest_.once('abort', requestErrorCallback);\n\t\t\t\trequest_.once('destroy', requestErrorCallback);\n\t\t\t\tee.emit('request', request_);\n\t\t\t} catch (error: any) {\n\t\t\t\tee.emit('error', new RequestError(error));\n\t\t\t}\n\t\t};\n\n\t\t(async () => {\n\t\t\tconst get = async (options_: any) => {\n\t\t\t\tawait Promise.resolve();\n\t\t\t\tconst cacheEntry = options_.cache ? await this.cache.get(key) : undefined;\n\n\t\t\t\tif (cacheEntry === undefined && !options_.forceRefresh) {\n\t\t\t\t\tmakeRequest(options_);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst policy = CachePolicy.fromObject(cacheEntry.cachePolicy);\n\t\t\t\tif (policy.satisfiesWithoutRevalidation(options_) && !options_.forceRefresh) {\n\t\t\t\t\tconst headers = convertHeaders(policy.responseHeaders());\n\t\t\t\t\tconst response: any = new Response({statusCode: cacheEntry.statusCode, headers, body: cacheEntry.body, url: cacheEntry.url});\n\t\t\t\t\tresponse.cachePolicy = policy;\n\t\t\t\t\tresponse.fromCache = true;\n\t\t\t\t\tee.emit('response', response);\n\t\t\t\t\tif (typeof cb === 'function') {\n\t\t\t\t\t\tcb(response);\n\t\t\t\t\t}\n\t\t\t\t} else if (policy.satisfiesWithoutRevalidation(options_) && Date.now() >= policy.timeToLive() && options_.forceRefresh) {\n\t\t\t\t\tawait this.cache.delete(key);\n\t\t\t\t\toptions_.headers = policy.revalidationHeaders(options_);\n\t\t\t\t\tmakeRequest(options_);\n\t\t\t\t} else {\n\t\t\t\t\trevalidate = cacheEntry;\n\t\t\t\t\toptions_.headers = policy.revalidationHeaders(options_);\n\t\t\t\t\tmakeRequest(options_);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst errorHandler = (error: Error) => ee.emit('error', new CacheError(error));\n\t\t\tif (this.cache instanceof Keyv) {\n\t\t\t\tconst cachek = this.cache;\n\t\t\t\tcachek.once('error', errorHandler);\n\t\t\t\tee.on('error', () => cachek.removeListener('error', errorHandler));\n\t\t\t\tee.on('response', () => cachek.removeListener('error', errorHandler));\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tawait get(options);\n\t\t\t} catch (error: any) {\n\t\t\t\tif (options.automaticFailover && !madeRequest) {\n\t\t\t\t\tmakeRequest(options);\n\t\t\t\t}\n\n\t\t\t\tee.emit('error', new CacheError(error));\n\t\t\t}\n\t\t})();\n\n\t\treturn ee;\n\t};\n\n\taddHook = (name: string, fn: Func) => {\n\t\tif (!this.hooks.has(name)) {\n\t\t\tthis.hooks.set(name, fn);\n\t\t}\n\t};\n\n\tremoveHook = (name: string) => this.hooks.delete(name);\n\n\tgetHook = (name: string) => this.hooks.get(name);\n\n\trunHook = async (name: string, ...args: any[]): Promise => this.hooks.get(name)?.(...args);\n}\n\nconst entries = Object.entries as (object: T) => Array<[keyof T, T[keyof T]]>;\n\nconst cloneResponse = (response: IncomingMessage) => {\n\tconst clone = new PassThroughStream({autoDestroy: false});\n\tmimicResponse(response, clone);\n\n\treturn response.pipe(clone);\n};\n\nconst urlObjectToRequestOptions = (url: any) => {\n\tconst options: UrlOption = {...url};\n\toptions.path = `${url.pathname || '/'}${url.search || ''}`;\n\tdelete options.pathname;\n\tdelete options.search;\n\treturn options;\n};\n\nconst normalizeUrlObject = (url: any) =>\n\t// If url was parsed by url.parse or new URL:\n\t// - hostname will be set\n\t// - host will be hostname[:port]\n\t// - port will be set if it was explicit in the parsed string\n\t// Otherwise, url was from request options:\n\t// - hostname or host may be set\n\t// - host shall not have port encoded\n\t({\n\t\tprotocol: url.protocol,\n\t\tauth: url.auth,\n\t\thostname: url.hostname || url.host || 'localhost',\n\t\tport: url.port,\n\t\tpathname: url.pathname,\n\t\tsearch: url.search,\n\t});\n\nconst convertHeaders = (headers: CachePolicy.Headers) => {\n\tconst result: any = [];\n\tfor (const name of Object.keys(headers)) {\n\t\tresult[name.toLowerCase()] = headers[name];\n\t}\n\n\treturn result;\n};\n\nexport default CacheableRequest;\nexport * from './types.js';\nexport const onResponse = 'onResponse';\n"]} \ No newline at end of file diff --git a/setup-pandoc/node_modules/cacheable-request/dist/types.d.ts b/setup-pandoc/node_modules/cacheable-request/dist/types.d.ts deleted file mode 100644 index 151b57636..000000000 --- a/setup-pandoc/node_modules/cacheable-request/dist/types.d.ts +++ /dev/null @@ -1,106 +0,0 @@ -/// -/// -/// -/// -import { request, RequestOptions, ClientRequest, ServerResponse } from 'node:http'; -import { URL } from 'node:url'; -import { EventEmitter } from 'node:events'; -import { Buffer } from 'node:buffer'; -import { Store } from 'keyv'; -import ResponseLike from 'responselike'; -import { CachePolicyObject } from 'http-cache-semantics'; -export type RequestFn = typeof request; -export type RequestFunction = typeof request; -export type CacheResponse = ServerResponse | typeof ResponseLike; -export type CacheableRequestFunction = (options: CacheableOptions, cb?: (response: CacheResponse) => void) => Emitter; -export type CacheableOptions = Options & RequestOptions | string | URL; -export type StorageAdapter = Store; -export interface Options { - /** - * If the cache should be used. Setting this to `false` will completely bypass the cache for the current request. - * @default true - */ - cache?: boolean | undefined; - /** - * If set to `true` once a cached resource has expired it is deleted and will have to be re-requested. - * - * If set to `false`, after a cached resource's TTL expires it is kept in the cache and will be revalidated - * on the next request with `If-None-Match`/`If-Modified-Since` headers. - * @default false - */ - strictTtl?: boolean | undefined; - /** - * Limits TTL. The `number` represents milliseconds. - * @default undefined - */ - maxTtl?: number | undefined; - /** - * When set to `true`, if the DB connection fails we will automatically fallback to a network request. - * DB errors will still be emitted to notify you of the problem even though the request callback may succeed. - * @default false - */ - automaticFailover?: boolean | undefined; - /** - * Forces refreshing the cache. If the response could be retrieved from the cache, it will perform a - * new request and override the cache instead. - * @default false - */ - forceRefresh?: boolean | undefined; - remoteAddress?: boolean | undefined; - url?: string | undefined; - headers?: Record; - body?: Buffer; -} -export interface CacheValue extends Record { - url: string; - statusCode: number; - body: Buffer | string; - cachePolicy: CachePolicyObject; -} -export interface Emitter extends EventEmitter { - addListener(event: 'request', listener: (request: ClientRequest) => void): this; - addListener(event: 'response', listener: (response: CacheResponse) => void): this; - addListener(event: 'error', listener: (error: RequestError | CacheError) => void): this; - on(event: 'request', listener: (request: ClientRequest) => void): this; - on(event: 'response', listener: (response: CacheResponse) => void): this; - on(event: 'error', listener: (error: RequestError | CacheError) => void): this; - once(event: 'request', listener: (request: ClientRequest) => void): this; - once(event: 'response', listener: (response: CacheResponse) => void): this; - once(event: 'error', listener: (error: RequestError | CacheError) => void): this; - prependListener(event: 'request', listener: (request: ClientRequest) => void): this; - prependListener(event: 'response', listener: (response: CacheResponse) => void): this; - prependListener(event: 'error', listener: (error: RequestError | CacheError) => void): this; - prependOnceListener(event: 'request', listener: (request: ClientRequest) => void): this; - prependOnceListener(event: 'response', listener: (response: CacheResponse) => void): this; - prependOnceListener(event: 'error', listener: (error: RequestError | CacheError) => void): this; - removeListener(event: 'request', listener: (request: ClientRequest) => void): this; - removeListener(event: 'response', listener: (response: CacheResponse) => void): this; - removeListener(event: 'error', listener: (error: RequestError | CacheError) => void): this; - off(event: 'request', listener: (request: ClientRequest) => void): this; - off(event: 'response', listener: (response: CacheResponse) => void): this; - off(event: 'error', listener: (error: RequestError | CacheError) => void): this; - removeAllListeners(event?: 'request' | 'response' | 'error'): this; - listeners(event: 'request'): Array<(request: ClientRequest) => void>; - listeners(event: 'response'): Array<(response: CacheResponse) => void>; - listeners(event: 'error'): Array<(error: RequestError | CacheError) => void>; - rawListeners(event: 'request'): Array<(request: ClientRequest) => void>; - rawListeners(event: 'response'): Array<(response: CacheResponse) => void>; - rawListeners(event: 'error'): Array<(error: RequestError | CacheError) => void>; - emit(event: 'request', request: ClientRequest): boolean; - emit(event: 'response', response: CacheResponse): boolean; - emit(event: 'error', error: RequestError | CacheError): boolean; - eventNames(): Array<'request' | 'response' | 'error'>; - listenerCount(type: 'request' | 'response' | 'error'): number; -} -export declare class RequestError extends Error { - constructor(error: Error); -} -export declare class CacheError extends Error { - constructor(error: Error); -} -export interface UrlOption { - path: string; - pathname?: string; - search?: string; -} -//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/setup-pandoc/node_modules/cacheable-request/dist/types.d.ts.map b/setup-pandoc/node_modules/cacheable-request/dist/types.d.ts.map deleted file mode 100644 index 4d46e2147..000000000 --- a/setup-pandoc/node_modules/cacheable-request/dist/types.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";;;;AASA,OAAO,EAAC,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,cAAc,EAAC,MAAM,WAAW,CAAC;AACjF,OAAO,EAAC,GAAG,EAAC,MAAM,UAAU,CAAC;AAC7B,OAAO,EAAC,YAAY,EAAC,MAAM,aAAa,CAAC;AACzC,OAAO,EAAC,MAAM,EAAC,MAAM,aAAa,CAAC;AACnC,OAAO,EAAC,KAAK,EAAC,MAAM,MAAM,CAAC;AAC3B,OAAO,YAAY,MAAM,cAAc,CAAC;AACxC,OAAO,EAAC,iBAAiB,EAAC,MAAM,sBAAsB,CAAC;AAEvD,MAAM,MAAM,SAAS,GAAG,OAAO,OAAO,CAAC;AACvC,MAAM,MAAM,eAAe,GAAG,OAAO,OAAO,CAAC;AAC7C,MAAM,MAAM,aAAa,GAAG,cAAc,GAAG,OAAO,YAAY,CAAC;AAEjE,MAAM,MAAM,wBAAwB,GAAG,CACtC,OAAO,EAAE,gBAAgB,EACzB,EAAE,CAAC,EAAE,CAAC,QAAQ,EAAE,aAAa,KAAK,IAAI,KAClC,OAAO,CAAC;AAEb,MAAM,MAAM,gBAAgB,GAAG,OAAO,GAAG,cAAc,GAAG,MAAM,GAAG,GAAG,CAAC;AAEvE,MAAM,MAAM,cAAc,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC;AAExC,MAAM,WAAW,OAAO;IACvB;;;eAGK;IACL,KAAK,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IAE5B;;;;;;eAMK;IACL,SAAS,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IAEhC;;;eAGK;IACL,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAE5B;;;;eAIK;IACL,iBAAiB,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IAExC;;;;GAIE;IACF,YAAY,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IACnC,aAAa,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IAEpC,GAAG,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAEzB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC,CAAC;IAExD,IAAI,CAAC,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,UAAW,SAAQ,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC;IACtD,GAAG,EAAE,MAAM,CAAC;IACZ,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC;IACtB,WAAW,EAAE,iBAAiB,CAAC;CAC/B;AAED,MAAM,WAAW,OAAQ,SAAQ,YAAY;IAC5C,WAAW,CAAC,KAAK,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,OAAO,EAAE,aAAa,KAAK,IAAI,GAAG,IAAI,CAAC;IAChF,WAAW,CACV,KAAK,EAAE,UAAU,EACjB,QAAQ,EAAE,CAAC,QAAQ,EAAE,aAAa,KAAK,IAAI,GACzC,IAAI,CAAC;IACR,WAAW,CAAC,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE,YAAY,GAAG,UAAU,KAAK,IAAI,GAAG,IAAI,CAAC;IACxF,EAAE,CAAC,KAAK,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,OAAO,EAAE,aAAa,KAAK,IAAI,GAAG,IAAI,CAAC;IACvE,EAAE,CAAC,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC,QAAQ,EAAE,aAAa,KAAK,IAAI,GAAG,IAAI,CAAC;IACzE,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE,YAAY,GAAG,UAAU,KAAK,IAAI,GAAG,IAAI,CAAC;IAC/E,IAAI,CAAC,KAAK,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,OAAO,EAAE,aAAa,KAAK,IAAI,GAAG,IAAI,CAAC;IACzE,IAAI,CAAC,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC,QAAQ,EAAE,aAAa,KAAK,IAAI,GAAG,IAAI,CAAC;IAC3E,IAAI,CAAC,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE,YAAY,GAAG,UAAU,KAAK,IAAI,GAAG,IAAI,CAAC;IACjF,eAAe,CAAC,KAAK,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,OAAO,EAAE,aAAa,KAAK,IAAI,GAAG,IAAI,CAAC;IACpF,eAAe,CACd,KAAK,EAAE,UAAU,EACjB,QAAQ,EAAE,CAAC,QAAQ,EAAE,aAAa,KAAK,IAAI,GACzC,IAAI,CAAC;IACR,eAAe,CAAC,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE,YAAY,GAAG,UAAU,KAAK,IAAI,GAAG,IAAI,CAAC;IAC5F,mBAAmB,CAAC,KAAK,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,OAAO,EAAE,aAAa,KAAK,IAAI,GAAG,IAAI,CAAC;IACxF,mBAAmB,CAClB,KAAK,EAAE,UAAU,EACjB,QAAQ,EAAE,CAAC,QAAQ,EAAE,aAAa,KAAK,IAAI,GACzC,IAAI,CAAC;IACR,mBAAmB,CAClB,KAAK,EAAE,OAAO,EACd,QAAQ,EAAE,CAAC,KAAK,EAAE,YAAY,GAAG,UAAU,KAAK,IAAI,GAClD,IAAI,CAAC;IACR,cAAc,CAAC,KAAK,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,OAAO,EAAE,aAAa,KAAK,IAAI,GAAG,IAAI,CAAC;IACnF,cAAc,CACb,KAAK,EAAE,UAAU,EACjB,QAAQ,EAAE,CAAC,QAAQ,EAAE,aAAa,KAAK,IAAI,GACzC,IAAI,CAAC;IACR,cAAc,CAAC,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE,YAAY,GAAG,UAAU,KAAK,IAAI,GAAG,IAAI,CAAC;IAC3F,GAAG,CAAC,KAAK,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,OAAO,EAAE,aAAa,KAAK,IAAI,GAAG,IAAI,CAAC;IACxE,GAAG,CAAC,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC,QAAQ,EAAE,aAAa,KAAK,IAAI,GAAG,IAAI,CAAC;IAC1E,GAAG,CAAC,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE,YAAY,GAAG,UAAU,KAAK,IAAI,GAAG,IAAI,CAAC;IAChF,kBAAkB,CAAC,KAAK,CAAC,EAAE,SAAS,GAAG,UAAU,GAAG,OAAO,GAAG,IAAI,CAAC;IACnE,SAAS,CAAC,KAAK,EAAE,SAAS,GAAG,KAAK,CAAC,CAAC,OAAO,EAAE,aAAa,KAAK,IAAI,CAAC,CAAC;IACrE,SAAS,CAAC,KAAK,EAAE,UAAU,GAAG,KAAK,CAAC,CAAC,QAAQ,EAAE,aAAa,KAAK,IAAI,CAAC,CAAC;IACvE,SAAS,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,CAAC,CAAC,KAAK,EAAE,YAAY,GAAG,UAAU,KAAK,IAAI,CAAC,CAAC;IAC7E,YAAY,CAAC,KAAK,EAAE,SAAS,GAAG,KAAK,CAAC,CAAC,OAAO,EAAE,aAAa,KAAK,IAAI,CAAC,CAAC;IACxE,YAAY,CAAC,KAAK,EAAE,UAAU,GAAG,KAAK,CAAC,CAAC,QAAQ,EAAE,aAAa,KAAK,IAAI,CAAC,CAAC;IAC1E,YAAY,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,CAAC,CAAC,KAAK,EAAE,YAAY,GAAG,UAAU,KAAK,IAAI,CAAC,CAAC;IAChF,IAAI,CAAC,KAAK,EAAE,SAAS,EAAE,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC;IACxD,IAAI,CAAC,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,aAAa,GAAG,OAAO,CAAC;IAC1D,IAAI,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,YAAY,GAAG,UAAU,GAAG,OAAO,CAAC;IAChE,UAAU,IAAI,KAAK,CAAC,SAAS,GAAG,UAAU,GAAG,OAAO,CAAC,CAAC;IACtD,aAAa,CAAC,IAAI,EAAE,SAAS,GAAG,UAAU,GAAG,OAAO,GAAG,MAAM,CAAC;CAC9D;AAED,qBAAa,YAAa,SAAQ,KAAK;gBAC1B,KAAK,EAAE,KAAK;CAIxB;AACD,qBAAa,UAAW,SAAQ,KAAK;gBACxB,KAAK,EAAE,KAAK;CAIxB;AAED,MAAM,WAAW,SAAS;IACzB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,CAAC;CAChB"} \ No newline at end of file diff --git a/setup-pandoc/node_modules/cacheable-request/dist/types.js b/setup-pandoc/node_modules/cacheable-request/dist/types.js deleted file mode 100644 index 311ef10de..000000000 --- a/setup-pandoc/node_modules/cacheable-request/dist/types.js +++ /dev/null @@ -1,19 +0,0 @@ -// Type definitions for cacheable-request 6.0 -// Project: https://github.com/lukechilds/cacheable-request#readme -// Definitions by: BendingBender -// Paul Melnikow -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 -export class RequestError extends Error { - constructor(error) { - super(error.message); - Object.assign(this, error); - } -} -export class CacheError extends Error { - constructor(error) { - super(error.message); - Object.assign(this, error); - } -} -//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/setup-pandoc/node_modules/cacheable-request/dist/types.js.map b/setup-pandoc/node_modules/cacheable-request/dist/types.js.map deleted file mode 100644 index ae4ff5b99..000000000 --- a/setup-pandoc/node_modules/cacheable-request/dist/types.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,6CAA6C;AAC7C,kEAAkE;AAClE,mEAAmE;AACnE,kEAAkE;AAClE,kEAAkE;AAClE,0BAA0B;AA+H1B,MAAM,OAAO,YAAa,SAAQ,KAAK;IACtC,YAAY,KAAY;QACvB,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QACrB,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IAC5B,CAAC;CACD;AACD,MAAM,OAAO,UAAW,SAAQ,KAAK;IACpC,YAAY,KAAY;QACvB,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QACrB,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IAC5B,CAAC;CACD","sourcesContent":["// Type definitions for cacheable-request 6.0\n// Project: https://github.com/lukechilds/cacheable-request#readme\n// Definitions by: BendingBender \n// Paul Melnikow \n// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n// TypeScript Version: 2.3\n\n/// \n\nimport {request, RequestOptions, ClientRequest, ServerResponse} from 'node:http';\nimport {URL} from 'node:url';\nimport {EventEmitter} from 'node:events';\nimport {Buffer} from 'node:buffer';\nimport {Store} from 'keyv';\nimport ResponseLike from 'responselike';\nimport {CachePolicyObject} from 'http-cache-semantics';\n\nexport type RequestFn = typeof request;\nexport type RequestFunction = typeof request;\nexport type CacheResponse = ServerResponse | typeof ResponseLike;\n\nexport type CacheableRequestFunction = (\n\toptions: CacheableOptions,\n\tcb?: (response: CacheResponse) => void\n) => Emitter;\n\nexport type CacheableOptions = Options & RequestOptions | string | URL;\n\nexport type StorageAdapter = Store;\n\nexport interface Options {\n\t/**\n\t\t\t * If the cache should be used. Setting this to `false` will completely bypass the cache for the current request.\n\t\t\t * @default true\n\t\t\t */\n\tcache?: boolean | undefined;\n\n\t/**\n\t\t\t * If set to `true` once a cached resource has expired it is deleted and will have to be re-requested.\n\t\t\t *\n\t\t\t * If set to `false`, after a cached resource's TTL expires it is kept in the cache and will be revalidated\n\t\t\t * on the next request with `If-None-Match`/`If-Modified-Since` headers.\n\t\t\t * @default false\n\t\t\t */\n\tstrictTtl?: boolean | undefined;\n\n\t/**\n\t\t\t * Limits TTL. The `number` represents milliseconds.\n\t\t\t * @default undefined\n\t\t\t */\n\tmaxTtl?: number | undefined;\n\n\t/**\n\t\t\t * When set to `true`, if the DB connection fails we will automatically fallback to a network request.\n\t\t\t * DB errors will still be emitted to notify you of the problem even though the request callback may succeed.\n\t\t\t * @default false\n\t\t\t */\n\tautomaticFailover?: boolean | undefined;\n\n\t/**\n * Forces refreshing the cache. If the response could be retrieved from the cache, it will perform a\n * new request and override the cache instead.\n * @default false\n */\n\tforceRefresh?: boolean | undefined;\n\tremoteAddress?: boolean | undefined;\n\n\turl?: string | undefined;\n\n\theaders?: Record;\n\n\tbody?: Buffer;\n}\n\nexport interface CacheValue extends Record {\n\turl: string;\n\tstatusCode: number;\n\tbody: Buffer | string;\n\tcachePolicy: CachePolicyObject;\n}\n\nexport interface Emitter extends EventEmitter {\n\taddListener(event: 'request', listener: (request: ClientRequest) => void): this;\n\taddListener(\n\t\tevent: 'response',\n\t\tlistener: (response: CacheResponse) => void\n\t): this;\n\taddListener(event: 'error', listener: (error: RequestError | CacheError) => void): this;\n\ton(event: 'request', listener: (request: ClientRequest) => void): this;\n\ton(event: 'response', listener: (response: CacheResponse) => void): this;\n\ton(event: 'error', listener: (error: RequestError | CacheError) => void): this;\n\tonce(event: 'request', listener: (request: ClientRequest) => void): this;\n\tonce(event: 'response', listener: (response: CacheResponse) => void): this;\n\tonce(event: 'error', listener: (error: RequestError | CacheError) => void): this;\n\tprependListener(event: 'request', listener: (request: ClientRequest) => void): this;\n\tprependListener(\n\t\tevent: 'response',\n\t\tlistener: (response: CacheResponse) => void\n\t): this;\n\tprependListener(event: 'error', listener: (error: RequestError | CacheError) => void): this;\n\tprependOnceListener(event: 'request', listener: (request: ClientRequest) => void): this;\n\tprependOnceListener(\n\t\tevent: 'response',\n\t\tlistener: (response: CacheResponse) => void\n\t): this;\n\tprependOnceListener(\n\t\tevent: 'error',\n\t\tlistener: (error: RequestError | CacheError) => void\n\t): this;\n\tremoveListener(event: 'request', listener: (request: ClientRequest) => void): this;\n\tremoveListener(\n\t\tevent: 'response',\n\t\tlistener: (response: CacheResponse) => void\n\t): this;\n\tremoveListener(event: 'error', listener: (error: RequestError | CacheError) => void): this;\n\toff(event: 'request', listener: (request: ClientRequest) => void): this;\n\toff(event: 'response', listener: (response: CacheResponse) => void): this;\n\toff(event: 'error', listener: (error: RequestError | CacheError) => void): this;\n\tremoveAllListeners(event?: 'request' | 'response' | 'error'): this;\n\tlisteners(event: 'request'): Array<(request: ClientRequest) => void>;\n\tlisteners(event: 'response'): Array<(response: CacheResponse) => void>;\n\tlisteners(event: 'error'): Array<(error: RequestError | CacheError) => void>;\n\trawListeners(event: 'request'): Array<(request: ClientRequest) => void>;\n\trawListeners(event: 'response'): Array<(response: CacheResponse) => void>;\n\trawListeners(event: 'error'): Array<(error: RequestError | CacheError) => void>;\n\temit(event: 'request', request: ClientRequest): boolean;\n\temit(event: 'response', response: CacheResponse): boolean;\n\temit(event: 'error', error: RequestError | CacheError): boolean;\n\teventNames(): Array<'request' | 'response' | 'error'>;\n\tlistenerCount(type: 'request' | 'response' | 'error'): number;\n}\n\nexport class RequestError extends Error {\n\tconstructor(error: Error) {\n\t\tsuper(error.message);\n\t\tObject.assign(this, error);\n\t}\n}\nexport class CacheError extends Error {\n\tconstructor(error: Error) {\n\t\tsuper(error.message);\n\t\tObject.assign(this, error);\n\t}\n}\n\nexport interface UrlOption {\n\tpath: string;\n\tpathname?: string;\n\tsearch?: string;\n}\n"]} \ No newline at end of file diff --git a/setup-pandoc/node_modules/cacheable-request/node_modules/get-stream/index.d.ts b/setup-pandoc/node_modules/cacheable-request/node_modules/get-stream/index.d.ts index 9485b2b6d..7b98134d9 100644 --- a/setup-pandoc/node_modules/cacheable-request/node_modules/get-stream/index.d.ts +++ b/setup-pandoc/node_modules/cacheable-request/node_modules/get-stream/index.d.ts @@ -74,7 +74,7 @@ declare const getStream: { */ buffer( stream: Stream, - options?: getStream.Options + options?: getStream.OptionsWithEncoding ): Promise; /** @@ -100,6 +100,9 @@ declare const getStream: { ): Promise; MaxBufferError: typeof MaxBufferErrorClass; + + // TODO: Remove this for the next major release + default: typeof getStream; }; export = getStream; diff --git a/setup-pandoc/node_modules/cacheable-request/node_modules/get-stream/index.js b/setup-pandoc/node_modules/cacheable-request/node_modules/get-stream/index.js index 1c5d02860..71f399193 100644 --- a/setup-pandoc/node_modules/cacheable-request/node_modules/get-stream/index.js +++ b/setup-pandoc/node_modules/cacheable-request/node_modules/get-stream/index.js @@ -1,11 +1,8 @@ 'use strict'; const {constants: BufferConstants} = require('buffer'); -const stream = require('stream'); -const {promisify} = require('util'); +const pump = require('pump'); const bufferStream = require('./buffer-stream'); -const streamPipelinePromisified = promisify(stream.pipeline); - class MaxBufferError extends Error { constructor() { super('maxBuffer exceeded'); @@ -15,7 +12,7 @@ class MaxBufferError extends Error { async function getStream(inputStream, options) { if (!inputStream) { - throw new Error('Expected a stream'); + return Promise.reject(new Error('Expected a stream')); } options = { @@ -24,8 +21,8 @@ async function getStream(inputStream, options) { }; const {maxBuffer} = options; - const stream = bufferStream(options); + let stream; await new Promise((resolve, reject) => { const rejectPromise = error => { // Don't retrieve an oversized buffer. @@ -36,14 +33,14 @@ async function getStream(inputStream, options) { reject(error); }; - (async () => { - try { - await streamPipelinePromisified(inputStream, stream); - resolve(); - } catch (error) { + stream = pump(inputStream, bufferStream(options), error => { + if (error) { rejectPromise(error); + return; } - })(); + + resolve(); + }); stream.on('data', () => { if (stream.getBufferedLength() > maxBuffer) { @@ -56,6 +53,8 @@ async function getStream(inputStream, options) { } module.exports = getStream; +// TODO: Remove this for the next major release +module.exports.default = getStream; module.exports.buffer = (stream, options) => getStream(stream, {...options, encoding: 'buffer'}); module.exports.array = (stream, options) => getStream(stream, {...options, array: true}); module.exports.MaxBufferError = MaxBufferError; diff --git a/setup-pandoc/node_modules/cacheable-request/node_modules/get-stream/package.json b/setup-pandoc/node_modules/cacheable-request/node_modules/get-stream/package.json index bd47a75f9..e2f1687cc 100644 --- a/setup-pandoc/node_modules/cacheable-request/node_modules/get-stream/package.json +++ b/setup-pandoc/node_modules/cacheable-request/node_modules/get-stream/package.json @@ -1,6 +1,6 @@ { "name": "get-stream", - "version": "6.0.1", + "version": "5.2.0", "description": "Get a stream as a string, buffer, or array", "license": "MIT", "repository": "sindresorhus/get-stream", @@ -11,7 +11,7 @@ "url": "https://sindresorhus.com" }, "engines": { - "node": ">=10" + "node": ">=8" }, "scripts": { "test": "xo && ava && tsd" @@ -37,11 +37,14 @@ "array", "object" ], + "dependencies": { + "pump": "^3.0.0" + }, "devDependencies": { - "@types/node": "^14.0.27", - "ava": "^2.4.0", + "@types/node": "^12.0.7", + "ava": "^2.0.0", "into-stream": "^5.0.0", - "tsd": "^0.13.1", + "tsd": "^0.7.2", "xo": "^0.24.0" } } diff --git a/setup-pandoc/node_modules/cacheable-request/node_modules/get-stream/readme.md b/setup-pandoc/node_modules/cacheable-request/node_modules/get-stream/readme.md index 70b01fd16..7d7565dc6 100644 --- a/setup-pandoc/node_modules/cacheable-request/node_modules/get-stream/readme.md +++ b/setup-pandoc/node_modules/cacheable-request/node_modules/get-stream/readme.md @@ -1,4 +1,4 @@ -# get-stream +# get-stream [![Build Status](https://travis-ci.com/sindresorhus/get-stream.svg?branch=master)](https://travis-ci.com/github/sindresorhus/get-stream) > Get a stream as a string, buffer, or array diff --git a/setup-pandoc/node_modules/cacheable-request/package.json b/setup-pandoc/node_modules/cacheable-request/package.json index 154c57dc3..ef1c2ae2f 100644 --- a/setup-pandoc/node_modules/cacheable-request/package.json +++ b/setup-pandoc/node_modules/cacheable-request/package.json @@ -1,24 +1,20 @@ { "name": "cacheable-request", - "version": "10.2.14", + "version": "7.0.4", "description": "Wrap native HTTP requests with RFC compliant cache support", "license": "MIT", - "repository": "jaredwray/cacheable", - "author": "Jared Wray (http://jaredwray.com)", - "type": "module", - "exports": "./dist/index.js", - "types": "./dist/index.d.ts", + "repository": "lukechilds/cacheable-request", + "author": "Luke Childs (http://lukechilds.co.uk)", + "main": "src/index.js", "engines": { - "node": ">=14.16" + "node": ">=8" }, "scripts": { - "test": "xo && NODE_OPTIONS=--experimental-vm-modules jest --coverage ", - "prepare": "npm run build", - "build": "tsc --project tsconfig.build.json", - "clean": "rm -rf node_modules && rm -rf ./coverage && rm -rf ./test/testdb.sqlite && rm -rf ./dist" + "test": "xo && nyc ava", + "coverage": "nyc report --reporter=text-lcov | coveralls" }, "files": [ - "dist" + "src" ], "keywords": [ "HTTP", @@ -32,90 +28,29 @@ "7234", "compliant" ], - "dependenciesComments": { - "@types/http-cache-semantics": "It needs to be in the dependencies list and not devDependencies because otherwise projects that use this one will be getting `Could not find a declaration file for module 'http-cache-semantics'` error when running `tsc`, see https://github.com/jaredwray/cacheable-request/issues/194 for details" - }, "dependencies": { - "@types/http-cache-semantics": "^4.0.2", - "get-stream": "^6.0.1", - "http-cache-semantics": "^4.1.1", - "keyv": "^4.5.3", - "mimic-response": "^4.0.0", - "normalize-url": "^8.0.0", - "responselike": "^3.0.0" + "clone-response": "^1.0.2", + "get-stream": "^5.1.0", + "http-cache-semantics": "^4.0.0", + "keyv": "^4.0.0", + "lowercase-keys": "^2.0.0", + "normalize-url": "^6.0.1", + "responselike": "^2.0.0" }, "devDependencies": { - "@keyv/sqlite": "^3.6.6", - "@types/jest": "^29.5.5", - "@types/node": "^20.8.2", - "@types/responselike": "^1.0.1", - "@types/sqlite3": "^3.1.9", - "body-parser": "^1.20.2", - "delay": "^6.0.0", - "eslint": "^8.50.0", - "eslint-plugin-jest": "^27.4.2", - "express": "^4.18.2", - "jest": "^29.7.0", - "pify": "^6.1.0", - "sqlite3": "^5.1.6", - "ts-jest": "^29.1.1", - "ts-jest-resolver": "^2.0.1", - "ts-node": "^10.9.1", - "typescript": "^5.2.2", - "xo": "^0.56.0" - }, - "jest": { - "collectCoverageFrom": [ - "src/**/*.{ts,js}" - ], - "extensionsToTreatAsEsm": [ - ".ts" - ], - "resolver": "ts-jest-resolver", - "moduleFileExtensions": [ - "ts", - "js" - ], - "transform": { - "^.+\\.(ts|tsx)$": [ - "ts-jest", - { - "tsconfig": "./tsconfig.build.json", - "useESM": true - } - ] - }, - "testMatch": [ - "**/test/*.test.(ts|js)" - ], - "testEnvironment": "node" + "@keyv/sqlite": "^2.0.0", + "ava": "^1.1.0", + "coveralls": "^3.0.0", + "create-test-server": "3.0.0", + "delay": "^4.0.0", + "eslint-config-xo-lukechilds": "^1.0.0", + "nyc": "^14.1.1", + "pify": "^4.0.0", + "sqlite3": "^4.0.2", + "this": "^1.0.2", + "xo": "^0.23.0" }, "xo": { - "plugins": [ - "jest" - ], - "extends": [ - "plugin:jest/recommended" - ], - "rules": { - "@typescript-eslint/triple-slash-reference": 0, - "@typescript-eslint/no-namespace": 0, - "@typescript-eslint/no-unsafe-assignment": 0, - "@typescript-eslint/no-unsafe-call": 0, - "@typescript-eslint/ban-types": 0, - "@typescript-eslint/restrict-template-expressions": 0, - "@typescript-eslint/no-unsafe-return": 0, - "@typescript-eslint/no-unsafe-argument": 0, - "new-cap": 0, - "unicorn/no-abusive-eslint-disable": 0, - "@typescript-eslint/restrict-plus-operands": 0, - "@typescript-eslint/no-implicit-any-catch": 0, - "@typescript-eslint/consistent-type-imports": 0, - "@typescript-eslint/consistent-type-definitions": 0, - "@typescript-eslint/prefer-nullish-coalescing": 0, - "n/prefer-global/url": 0, - "n/no-deprecated-api": 0, - "unicorn/prefer-event-target": 0 - } + "extends": "xo-lukechilds" } } diff --git a/setup-pandoc/node_modules/cacheable-request/src/index.js b/setup-pandoc/node_modules/cacheable-request/src/index.js new file mode 100644 index 000000000..3fcea3f90 --- /dev/null +++ b/setup-pandoc/node_modules/cacheable-request/src/index.js @@ -0,0 +1,251 @@ +'use strict'; + +const EventEmitter = require('events'); +const urlLib = require('url'); +const normalizeUrl = require('normalize-url'); +const getStream = require('get-stream'); +const CachePolicy = require('http-cache-semantics'); +const Response = require('responselike'); +const lowercaseKeys = require('lowercase-keys'); +const cloneResponse = require('clone-response'); +const Keyv = require('keyv'); + +class CacheableRequest { + constructor(request, cacheAdapter) { + if (typeof request !== 'function') { + throw new TypeError('Parameter `request` must be a function'); + } + + this.cache = new Keyv({ + uri: typeof cacheAdapter === 'string' && cacheAdapter, + store: typeof cacheAdapter !== 'string' && cacheAdapter, + namespace: 'cacheable-request' + }); + + return this.createCacheableRequest(request); + } + + createCacheableRequest(request) { + return (opts, cb) => { + let url; + if (typeof opts === 'string') { + url = normalizeUrlObject(urlLib.parse(opts)); + opts = {}; + } else if (opts instanceof urlLib.URL) { + url = normalizeUrlObject(urlLib.parse(opts.toString())); + opts = {}; + } else { + const [pathname, ...searchParts] = (opts.path || '').split('?'); + const search = searchParts.length > 0 ? + `?${searchParts.join('?')}` : + ''; + url = normalizeUrlObject({ ...opts, pathname, search }); + } + + opts = { + headers: {}, + method: 'GET', + cache: true, + strictTtl: false, + automaticFailover: false, + ...opts, + ...urlObjectToRequestOptions(url) + }; + opts.headers = lowercaseKeys(opts.headers); + + const ee = new EventEmitter(); + const normalizedUrlString = normalizeUrl( + urlLib.format(url), + { + stripWWW: false, + removeTrailingSlash: false, + stripAuthentication: false + } + ); + const key = `${opts.method}:${normalizedUrlString}`; + let revalidate = false; + let madeRequest = false; + + const makeRequest = opts => { + madeRequest = true; + let requestErrored = false; + let requestErrorCallback; + + const requestErrorPromise = new Promise(resolve => { + requestErrorCallback = () => { + if (!requestErrored) { + requestErrored = true; + resolve(); + } + }; + }); + + const handler = response => { + if (revalidate && !opts.forceRefresh) { + response.status = response.statusCode; + const revalidatedPolicy = CachePolicy.fromObject(revalidate.cachePolicy).revalidatedPolicy(opts, response); + if (!revalidatedPolicy.modified) { + const headers = revalidatedPolicy.policy.responseHeaders(); + response = new Response(revalidate.statusCode, headers, revalidate.body, revalidate.url); + response.cachePolicy = revalidatedPolicy.policy; + response.fromCache = true; + } + } + + if (!response.fromCache) { + response.cachePolicy = new CachePolicy(opts, response, opts); + response.fromCache = false; + } + + let clonedResponse; + if (opts.cache && response.cachePolicy.storable()) { + clonedResponse = cloneResponse(response); + + (async () => { + try { + const bodyPromise = getStream.buffer(response); + + await Promise.race([ + requestErrorPromise, + new Promise(resolve => response.once('end', resolve)) + ]); + + if (requestErrored) { + return; + } + + const body = await bodyPromise; + + const value = { + cachePolicy: response.cachePolicy.toObject(), + url: response.url, + statusCode: response.fromCache ? revalidate.statusCode : response.statusCode, + body + }; + + let ttl = opts.strictTtl ? response.cachePolicy.timeToLive() : undefined; + if (opts.maxTtl) { + ttl = ttl ? Math.min(ttl, opts.maxTtl) : opts.maxTtl; + } + + await this.cache.set(key, value, ttl); + } catch (error) { + ee.emit('error', new CacheableRequest.CacheError(error)); + } + })(); + } else if (opts.cache && revalidate) { + (async () => { + try { + await this.cache.delete(key); + } catch (error) { + ee.emit('error', new CacheableRequest.CacheError(error)); + } + })(); + } + + ee.emit('response', clonedResponse || response); + if (typeof cb === 'function') { + cb(clonedResponse || response); + } + }; + + try { + const req = request(opts, handler); + req.once('error', requestErrorCallback); + req.once('abort', requestErrorCallback); + ee.emit('request', req); + } catch (error) { + ee.emit('error', new CacheableRequest.RequestError(error)); + } + }; + + (async () => { + const get = async opts => { + await Promise.resolve(); + + const cacheEntry = opts.cache ? await this.cache.get(key) : undefined; + if (typeof cacheEntry === 'undefined') { + return makeRequest(opts); + } + + const policy = CachePolicy.fromObject(cacheEntry.cachePolicy); + if (policy.satisfiesWithoutRevalidation(opts) && !opts.forceRefresh) { + const headers = policy.responseHeaders(); + const response = new Response(cacheEntry.statusCode, headers, cacheEntry.body, cacheEntry.url); + response.cachePolicy = policy; + response.fromCache = true; + + ee.emit('response', response); + if (typeof cb === 'function') { + cb(response); + } + } else { + revalidate = cacheEntry; + opts.headers = policy.revalidationHeaders(opts); + makeRequest(opts); + } + }; + + const errorHandler = error => ee.emit('error', new CacheableRequest.CacheError(error)); + this.cache.once('error', errorHandler); + ee.on('response', () => this.cache.removeListener('error', errorHandler)); + + try { + await get(opts); + } catch (error) { + if (opts.automaticFailover && !madeRequest) { + makeRequest(opts); + } + + ee.emit('error', new CacheableRequest.CacheError(error)); + } + })(); + + return ee; + }; + } +} + +function urlObjectToRequestOptions(url) { + const options = { ...url }; + options.path = `${url.pathname || '/'}${url.search || ''}`; + delete options.pathname; + delete options.search; + return options; +} + +function normalizeUrlObject(url) { + // If url was parsed by url.parse or new URL: + // - hostname will be set + // - host will be hostname[:port] + // - port will be set if it was explicit in the parsed string + // Otherwise, url was from request options: + // - hostname or host may be set + // - host shall not have port encoded + return { + protocol: url.protocol, + auth: url.auth, + hostname: url.hostname || url.host || 'localhost', + port: url.port, + pathname: url.pathname, + search: url.search + }; +} + +CacheableRequest.RequestError = class extends Error { + constructor(error) { + super(error.message); + this.name = 'RequestError'; + Object.assign(this, error); + } +}; + +CacheableRequest.CacheError = class extends Error { + constructor(error) { + super(error.message); + this.name = 'CacheError'; + Object.assign(this, error); + } +}; + +module.exports = CacheableRequest; diff --git a/setup-pandoc/node_modules/clone-response/LICENSE b/setup-pandoc/node_modules/clone-response/LICENSE new file mode 100644 index 000000000..f27ee9b41 --- /dev/null +++ b/setup-pandoc/node_modules/clone-response/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Luke Childs + +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/setup-pandoc/node_modules/clone-response/README.md b/setup-pandoc/node_modules/clone-response/README.md new file mode 100644 index 000000000..d037cfec1 --- /dev/null +++ b/setup-pandoc/node_modules/clone-response/README.md @@ -0,0 +1,62 @@ +# clone-response + +> Clone a Node.js HTTP response stream + +[![Build Status](https://travis-ci.org/lukechilds/clone-response.svg?branch=master)](https://travis-ci.org/lukechilds/clone-response) +[![Coverage Status](https://coveralls.io/repos/github/lukechilds/clone-response/badge.svg?branch=master)](https://coveralls.io/github/lukechilds/clone-response?branch=master) +[![npm](https://img.shields.io/npm/dm/clone-response.svg)](https://www.npmjs.com/package/clone-response) +[![npm](https://img.shields.io/npm/v/clone-response.svg)](https://www.npmjs.com/package/clone-response) + +Returns a new stream and copies over all properties and methods from the original response giving you a complete duplicate. + +This is useful in situations where you need to consume the response stream but also want to pass an unconsumed stream somewhere else to be consumed later. + +## Install + +```shell +npm install --save clone-response +``` + +## Usage + +```js +const http = require('http'); +const cloneResponse = require('clone-response'); + +http.get('http://example.com', response => { + const clonedResponse = cloneResponse(response); + response.pipe(process.stdout); + + setImmediate(() => { + // The response stream has already been consumed by the time this executes, + // however the cloned response stream is still available. + doSomethingWithResponse(clonedResponse); + }); +}); +``` + +Please bear in mind that the process of cloning a stream consumes it. However, you can consume a stream multiple times in the same tick, therefore allowing you to create multiple clones. e.g: + +```js +const clone1 = cloneResponse(response); +const clone2 = cloneResponse(response); +// response can still be consumed in this tick but cannot be consumed if passed +// into any async callbacks. clone1 and clone2 can be passed around and be +// consumed in the future. +``` + +## API + +### cloneResponse(response) + +Returns a clone of the passed in response. + +#### response + +Type: `stream` + +A [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage) to clone. + +## License + +MIT © Luke Childs diff --git a/setup-pandoc/node_modules/clone-response/package.json b/setup-pandoc/node_modules/clone-response/package.json new file mode 100644 index 000000000..a4a081043 --- /dev/null +++ b/setup-pandoc/node_modules/clone-response/package.json @@ -0,0 +1,41 @@ +{ + "name": "clone-response", + "version": "1.0.3", + "description": "Clone a Node.js HTTP response stream", + "main": "src/index.js", + "scripts": { + "test": "xo && nyc ava", + "coverage": "nyc report --reporter=text-lcov | coveralls" + }, + "funding": "https://github.com/sponsors/sindresorhus", + "xo": { + "extends": "xo-lukechilds" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/clone-response.git" + }, + "keywords": [ + "clone", + "duplicate", + "copy", + "response", + "HTTP", + "stream" + ], + "author": "Luke Childs (http://lukechilds.co.uk)", + "license": "MIT", + "dependencies": { + "mimic-response": "^1.0.0" + }, + "devDependencies": { + "ava": "^0.22.0", + "coveralls": "^2.13.1", + "create-test-server": "^2.0.1", + "eslint-config-xo-lukechilds": "^1.0.0", + "get-stream": "^3.0.0", + "nyc": "^11.0.2", + "pify": "^3.0.0", + "xo": "^0.19.0" + } +} diff --git a/setup-pandoc/node_modules/clone-response/src/index.js b/setup-pandoc/node_modules/clone-response/src/index.js new file mode 100644 index 000000000..0285dfffe --- /dev/null +++ b/setup-pandoc/node_modules/clone-response/src/index.js @@ -0,0 +1,17 @@ +'use strict'; + +const PassThrough = require('stream').PassThrough; +const mimicResponse = require('mimic-response'); + +const cloneResponse = response => { + if (!(response && response.pipe)) { + throw new TypeError('Parameter `response` must be a response stream.'); + } + + const clone = new PassThrough(); + mimicResponse(response, clone); + + return response.pipe(clone); +}; + +module.exports = cloneResponse; diff --git a/setup-pandoc/node_modules/form-data-encoder/lib/index.cjs b/setup-pandoc/node_modules/form-data-encoder/lib/index.cjs deleted file mode 100644 index 026add5fb..000000000 --- a/setup-pandoc/node_modules/form-data-encoder/lib/index.cjs +++ /dev/null @@ -1,393 +0,0 @@ -"use strict"; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -var __accessCheck = (obj, member, msg) => { - if (!member.has(obj)) - throw TypeError("Cannot " + msg); -}; -var __privateGet = (obj, member, getter) => { - __accessCheck(obj, member, "read from private field"); - return getter ? getter.call(obj) : member.get(obj); -}; -var __privateAdd = (obj, member, value) => { - if (member.has(obj)) - throw TypeError("Cannot add the same private member more than once"); - member instanceof WeakSet ? member.add(obj) : member.set(obj, value); -}; -var __privateSet = (obj, member, value, setter) => { - __accessCheck(obj, member, "write to private field"); - setter ? setter.call(obj, value) : member.set(obj, value); - return value; -}; -var __privateMethod = (obj, member, method) => { - __accessCheck(obj, member, "access private method"); - return method; -}; - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - FormDataEncoder: () => FormDataEncoder, - isFile: () => isFile, - isFormData: () => isFormData -}); -module.exports = __toCommonJS(src_exports); - -// src/util/isFunction.ts -var isFunction = (value) => typeof value === "function"; - -// src/util/isAsyncIterable.ts -var isAsyncIterable = (value) => isFunction(value[Symbol.asyncIterator]); - -// src/util/chunk.ts -var MAX_CHUNK_SIZE = 65536; -function* chunk(value) { - if (value.byteLength <= MAX_CHUNK_SIZE) { - yield value; - return; - } - let offset = 0; - while (offset < value.byteLength) { - const size = Math.min(value.byteLength - offset, MAX_CHUNK_SIZE); - const buffer = value.buffer.slice(offset, offset + size); - offset += buffer.byteLength; - yield new Uint8Array(buffer); - } -} - -// src/util/getStreamIterator.ts -async function* readStream(readable) { - const reader = readable.getReader(); - while (true) { - const { done, value } = await reader.read(); - if (done) { - break; - } - yield value; - } -} -async function* chunkStream(stream) { - for await (const value of stream) { - yield* chunk(value); - } -} -var getStreamIterator = (source) => { - if (isAsyncIterable(source)) { - return chunkStream(source); - } - if (isFunction(source.getReader)) { - return chunkStream(readStream(source)); - } - throw new TypeError( - "Unsupported data source: Expected either ReadableStream or async iterable." - ); -}; - -// src/util/createBoundary.ts -var alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"; -function createBoundary() { - let size = 16; - let res = ""; - while (size--) { - res += alphabet[Math.random() * alphabet.length << 0]; - } - return res; -} - -// src/util/normalizeValue.ts -var normalizeValue = (value) => String(value).replace(/\r|\n/g, (match, i, str) => { - if (match === "\r" && str[i + 1] !== "\n" || match === "\n" && str[i - 1] !== "\r") { - return "\r\n"; - } - return match; -}); - -// src/util/isPlainObject.ts -var getType = (value) => Object.prototype.toString.call(value).slice(8, -1).toLowerCase(); -function isPlainObject(value) { - if (getType(value) !== "object") { - return false; - } - const pp = Object.getPrototypeOf(value); - if (pp === null || pp === void 0) { - return true; - } - const Ctor = pp.constructor && pp.constructor.toString(); - return Ctor === Object.toString(); -} - -// src/util/proxyHeaders.ts -function getProperty(target, prop) { - if (typeof prop === "string") { - for (const [name, value] of Object.entries(target)) { - if (prop.toLowerCase() === name.toLowerCase()) { - return value; - } - } - } - return void 0; -} -var proxyHeaders = (object) => new Proxy( - object, - { - get: (target, prop) => getProperty(target, prop), - has: (target, prop) => getProperty(target, prop) !== void 0 - } -); - -// src/util/isFormData.ts -var isFormData = (value) => Boolean( - value && isFunction(value.constructor) && value[Symbol.toStringTag] === "FormData" && isFunction(value.append) && isFunction(value.getAll) && isFunction(value.entries) && isFunction(value[Symbol.iterator]) -); - -// src/util/escapeName.ts -var escapeName = (name) => String(name).replace(/\r/g, "%0D").replace(/\n/g, "%0A").replace(/"/g, "%22"); - -// src/util/isFile.ts -var isFile = (value) => Boolean( - value && typeof value === "object" && isFunction(value.constructor) && value[Symbol.toStringTag] === "File" && isFunction(value.stream) && value.name != null -); - -// src/FormDataEncoder.ts -var defaultOptions = { - enableAdditionalHeaders: false -}; -var readonlyProp = { writable: false, configurable: false }; -var _CRLF, _CRLF_BYTES, _CRLF_BYTES_LENGTH, _DASHES, _encoder, _footer, _form, _options, _getFieldHeader, getFieldHeader_fn, _getContentLength, getContentLength_fn; -var FormDataEncoder = class { - constructor(form, boundaryOrOptions, options) { - __privateAdd(this, _getFieldHeader); - /** - * Returns form-data content length - */ - __privateAdd(this, _getContentLength); - __privateAdd(this, _CRLF, "\r\n"); - __privateAdd(this, _CRLF_BYTES, void 0); - __privateAdd(this, _CRLF_BYTES_LENGTH, void 0); - __privateAdd(this, _DASHES, "-".repeat(2)); - /** - * TextEncoder instance - */ - __privateAdd(this, _encoder, new TextEncoder()); - /** - * Returns form-data footer bytes - */ - __privateAdd(this, _footer, void 0); - /** - * FormData instance - */ - __privateAdd(this, _form, void 0); - /** - * Instance options - */ - __privateAdd(this, _options, void 0); - if (!isFormData(form)) { - throw new TypeError("Expected first argument to be a FormData instance."); - } - let boundary; - if (isPlainObject(boundaryOrOptions)) { - options = boundaryOrOptions; - } else { - boundary = boundaryOrOptions; - } - if (!boundary) { - boundary = createBoundary(); - } - if (typeof boundary !== "string") { - throw new TypeError("Expected boundary argument to be a string."); - } - if (options && !isPlainObject(options)) { - throw new TypeError("Expected options argument to be an object."); - } - __privateSet(this, _form, Array.from(form.entries())); - __privateSet(this, _options, { ...defaultOptions, ...options }); - __privateSet(this, _CRLF_BYTES, __privateGet(this, _encoder).encode(__privateGet(this, _CRLF))); - __privateSet(this, _CRLF_BYTES_LENGTH, __privateGet(this, _CRLF_BYTES).byteLength); - this.boundary = `form-data-boundary-${boundary}`; - this.contentType = `multipart/form-data; boundary=${this.boundary}`; - __privateSet(this, _footer, __privateGet(this, _encoder).encode( - `${__privateGet(this, _DASHES)}${this.boundary}${__privateGet(this, _DASHES)}${__privateGet(this, _CRLF).repeat(2)}` - )); - const headers = { - "Content-Type": this.contentType - }; - const contentLength = __privateMethod(this, _getContentLength, getContentLength_fn).call(this); - if (contentLength) { - this.contentLength = contentLength; - headers["Content-Length"] = contentLength; - } - this.headers = proxyHeaders(Object.freeze(headers)); - Object.defineProperties(this, { - boundary: readonlyProp, - contentType: readonlyProp, - contentLength: readonlyProp, - headers: readonlyProp - }); - } - /** - * Creates an iterator allowing to go through form-data parts (with metadata). - * This method **will not** read the files and **will not** split values big into smaller chunks. - * - * Using this method, you can convert form-data content into Blob: - * - * @example - * - * ```ts - * import {Readable} from "stream" - * - * import {FormDataEncoder} from "form-data-encoder" - * - * import {FormData} from "formdata-polyfill/esm-min.js" - * import {fileFrom} from "fetch-blob/form.js" - * import {File} from "fetch-blob/file.js" - * import {Blob} from "fetch-blob" - * - * import fetch from "node-fetch" - * - * const form = new FormData() - * - * form.set("field", "Just a random string") - * form.set("file", new File(["Using files is class amazing"])) - * form.set("fileFromPath", await fileFrom("path/to/a/file.txt")) - * - * const encoder = new FormDataEncoder(form) - * - * const options = { - * method: "post", - * body: new Blob(encoder, {type: encoder.contentType}) - * } - * - * const response = await fetch("https://httpbin.org/post", options) - * - * console.log(await response.json()) - * ``` - */ - *values() { - for (const [name, raw] of __privateGet(this, _form)) { - const value = isFile(raw) ? raw : __privateGet(this, _encoder).encode( - normalizeValue(raw) - ); - yield __privateMethod(this, _getFieldHeader, getFieldHeader_fn).call(this, name, value); - yield value; - yield __privateGet(this, _CRLF_BYTES); - } - yield __privateGet(this, _footer); - } - /** - * Creates an async iterator allowing to perform the encoding by portions. - * This method reads through files and splits big values into smaller pieces (65536 bytes per each). - * - * @example - * - * ```ts - * import {Readable} from "stream" - * - * import {FormData, File, fileFromPath} from "formdata-node" - * import {FormDataEncoder} from "form-data-encoder" - * - * import fetch from "node-fetch" - * - * const form = new FormData() - * - * form.set("field", "Just a random string") - * form.set("file", new File(["Using files is class amazing"], "file.txt")) - * form.set("fileFromPath", await fileFromPath("path/to/a/file.txt")) - * - * const encoder = new FormDataEncoder(form) - * - * const options = { - * method: "post", - * headers: encoder.headers, - * body: Readable.from(encoder.encode()) // or Readable.from(encoder) - * } - * - * const response = await fetch("https://httpbin.org/post", options) - * - * console.log(await response.json()) - * ``` - */ - async *encode() { - for (const part of this.values()) { - if (isFile(part)) { - yield* getStreamIterator(part.stream()); - } else { - yield* chunk(part); - } - } - } - /** - * Creates an iterator allowing to read through the encoder data using for...of loops - */ - [Symbol.iterator]() { - return this.values(); - } - /** - * Creates an **async** iterator allowing to read through the encoder data using for-await...of loops - */ - [Symbol.asyncIterator]() { - return this.encode(); - } -}; -_CRLF = new WeakMap(); -_CRLF_BYTES = new WeakMap(); -_CRLF_BYTES_LENGTH = new WeakMap(); -_DASHES = new WeakMap(); -_encoder = new WeakMap(); -_footer = new WeakMap(); -_form = new WeakMap(); -_options = new WeakMap(); -_getFieldHeader = new WeakSet(); -getFieldHeader_fn = function(name, value) { - let header = ""; - header += `${__privateGet(this, _DASHES)}${this.boundary}${__privateGet(this, _CRLF)}`; - header += `Content-Disposition: form-data; name="${escapeName(name)}"`; - if (isFile(value)) { - header += `; filename="${escapeName(value.name)}"${__privateGet(this, _CRLF)}`; - header += `Content-Type: ${value.type || "application/octet-stream"}`; - } - if (__privateGet(this, _options).enableAdditionalHeaders === true) { - const size = isFile(value) ? value.size : value.byteLength; - if (size != null && !isNaN(size)) { - header += `${__privateGet(this, _CRLF)}Content-Length: ${size}`; - } - } - return __privateGet(this, _encoder).encode(`${header}${__privateGet(this, _CRLF).repeat(2)}`); -}; -_getContentLength = new WeakSet(); -getContentLength_fn = function() { - let length = 0; - for (const [name, raw] of __privateGet(this, _form)) { - const value = isFile(raw) ? raw : __privateGet(this, _encoder).encode( - normalizeValue(raw) - ); - const size = isFile(value) ? value.size : value.byteLength; - if (size == null || isNaN(size)) { - return void 0; - } - length += __privateMethod(this, _getFieldHeader, getFieldHeader_fn).call(this, name, value).byteLength; - length += size; - length += __privateGet(this, _CRLF_BYTES_LENGTH); - } - return String(length + __privateGet(this, _footer).byteLength); -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - FormDataEncoder, - isFile, - isFormData -}); diff --git a/setup-pandoc/node_modules/form-data-encoder/lib/index.d.cts b/setup-pandoc/node_modules/form-data-encoder/lib/index.d.cts deleted file mode 100644 index b79e49ab4..000000000 --- a/setup-pandoc/node_modules/form-data-encoder/lib/index.d.cts +++ /dev/null @@ -1,277 +0,0 @@ -interface RawHeaders { - "Content-Type": string; - "Content-Length"?: string; -} -interface FormDataEncoderHeaders extends RawHeaders { - "content-type": string; - "content-length"?: string; -} - -interface FileLike { - /** - * Name of the file referenced by the File object. - */ - readonly name: string; - /** - * Returns the media type ([`MIME`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types)) of the file represented by a `File` object. - */ - readonly type: string; - /** - * Size of the file parts in bytes - */ - readonly size: number; - /** - * The last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date. - */ - readonly lastModified: number; - /** - * Returns a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) which upon reading returns the data contained within the [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). - */ - stream(): ReadableStream | AsyncIterable; - readonly [Symbol.toStringTag]?: string; -} - -/** - * A `string` or `File` that represents a single value from a set of `FormData` key-value pairs. - */ -type FormDataEntryValue = string | FileLike; -/** - * This interface reflects minimal shape of the FormData - */ -interface FormDataLike { - /** - * Appends a new value onto an existing key inside a FormData object, - * or adds the key if it does not already exist. - * - * The difference between `set()` and `append()` is that if the specified key already exists, `set()` will overwrite all existing values with the new one, whereas `append()` will append the new value onto the end of the existing set of values. - * - * @param name The name of the field whose data is contained in `value`. - * @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) - or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string. - * @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename. - */ - append(name: string, value: unknown, fileName?: string): void; - /** - * Returns all the values associated with a given key from within a `FormData` object. - * - * @param {string} name A name of the value you want to retrieve. - * - * @returns An array of `FormDataEntryValue` whose key matches the value passed in the `name` parameter. If the key doesn't exist, the method returns an empty list. - */ - getAll(name: string): FormDataEntryValue[]; - /** - * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through the `FormData` key/value pairs. - * The key of each pair is a string; the value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue). - */ - entries(): IterableIterator<[string, FormDataEntryValue]>; - /** - * An alias for FormDataLike#entries() - */ - [Symbol.iterator](): IterableIterator<[string, FormDataEntryValue]>; - readonly [Symbol.toStringTag]?: string; -} - -interface FormDataEncoderOptions { - /** - * When enabled, the encoder will emit additional per part headers, such as `Content-Length`. - * - * Please note that the web clients do not include these, so when enabled this option might cause an error if `multipart/form-data` does not consider additional headers. - * - * Defaults to `false`. - */ - enableAdditionalHeaders?: boolean; -} -/** - * Implements [`multipart/form-data` encoding algorithm](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#multipart/form-data-encoding-algorithm), - * allowing to add support for spec-comliant [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) to an HTTP client. - */ -declare class FormDataEncoder { - #private; - /** - * Returns boundary string - */ - readonly boundary: string; - /** - * Returns Content-Type header - */ - readonly contentType: string; - /** - * Returns Content-Length header - */ - readonly contentLength: string | undefined; - /** - * Returns headers object with Content-Type and Content-Length header - */ - readonly headers: Readonly; - /** - * Creates a multipart/form-data encoder. - * - * @param form FormData object to encode. This object must be a spec-compatible FormData implementation. - * - * @example - * - * ```js - * import {Readable} from "stream" - * - * import {FormData, File, fileFromPath} from "formdata-node" - * import {FormDataEncoder} from "form-data-encoder" - * - * import fetch from "node-fetch" - * - * const form = new FormData() - * - * form.set("field", "Just a random string") - * form.set("file", new File(["Using files is class amazing"], "file.txt")) - * form.set("fileFromPath", await fileFromPath("path/to/a/file.txt")) - * - * const encoder = new FormDataEncoder(form) - * - * const options = { - * method: "post", - * headers: encoder.headers, - * body: Readable.from(encoder) - * } - * - * const response = await fetch("https://httpbin.org/post", options) - * - * console.log(await response.json()) - * ``` - */ - constructor(form: FormDataLike); - /** - * Creates multipart/form-data encoder with custom boundary string. - * - * @param form FormData object to encode. This object must be a spec-compatible FormData implementation. - * @param boundary An optional boundary string that will be used by the encoder. If there's no boundary string is present, Encoder will generate it automatically. - */ - constructor(form: FormDataLike, boundary: string); - /** - * Creates multipart/form-data encoder with additional options. - * - * @param form FormData object to encode. This object must be a spec-compatible FormData implementation. - * @param options Additional options - */ - constructor(form: FormDataLike, options: FormDataEncoderOptions); - constructor(form: FormDataLike, boundary: string, options?: FormDataEncoderOptions); - /** - * Creates an iterator allowing to go through form-data parts (with metadata). - * This method **will not** read the files and **will not** split values big into smaller chunks. - * - * Using this method, you can convert form-data content into Blob: - * - * @example - * - * ```ts - * import {Readable} from "stream" - * - * import {FormDataEncoder} from "form-data-encoder" - * - * import {FormData} from "formdata-polyfill/esm-min.js" - * import {fileFrom} from "fetch-blob/form.js" - * import {File} from "fetch-blob/file.js" - * import {Blob} from "fetch-blob" - * - * import fetch from "node-fetch" - * - * const form = new FormData() - * - * form.set("field", "Just a random string") - * form.set("file", new File(["Using files is class amazing"])) - * form.set("fileFromPath", await fileFrom("path/to/a/file.txt")) - * - * const encoder = new FormDataEncoder(form) - * - * const options = { - * method: "post", - * body: new Blob(encoder, {type: encoder.contentType}) - * } - * - * const response = await fetch("https://httpbin.org/post", options) - * - * console.log(await response.json()) - * ``` - */ - values(): Generator; - /** - * Creates an async iterator allowing to perform the encoding by portions. - * This method reads through files and splits big values into smaller pieces (65536 bytes per each). - * - * @example - * - * ```ts - * import {Readable} from "stream" - * - * import {FormData, File, fileFromPath} from "formdata-node" - * import {FormDataEncoder} from "form-data-encoder" - * - * import fetch from "node-fetch" - * - * const form = new FormData() - * - * form.set("field", "Just a random string") - * form.set("file", new File(["Using files is class amazing"], "file.txt")) - * form.set("fileFromPath", await fileFromPath("path/to/a/file.txt")) - * - * const encoder = new FormDataEncoder(form) - * - * const options = { - * method: "post", - * headers: encoder.headers, - * body: Readable.from(encoder.encode()) // or Readable.from(encoder) - * } - * - * const response = await fetch("https://httpbin.org/post", options) - * - * console.log(await response.json()) - * ``` - */ - encode(): AsyncGenerator; - /** - * Creates an iterator allowing to read through the encoder data using for...of loops - */ - [Symbol.iterator](): Generator; - /** - * Creates an **async** iterator allowing to read through the encoder data using for-await...of loops - */ - [Symbol.asyncIterator](): AsyncGenerator; -} - -/** - * Check if given object is `File`. - * - * Note that this function will return `false` for Blob, because the FormDataEncoder expects FormData to return File when a value is binary data. - * - * @param value an object to test - * - * @api public - * - * This function will return `true` for FileAPI compatible `File` objects: - * - * ```ts - * import {createReadStream} from "node:fs" - * - * import {isFile} from "form-data-encoder" - * - * isFile(new File(["Content"], "file.txt")) // -> true - * ``` - * - * However, if you pass a Node.js `Buffer`, or `Blob`, or `ReadStream`, it will return `false`: - * - * ```js - * import {isFile} from "form-data-encoder" - * - * isFile(Buffer.from("Content")) // -> false - * isFile(new Blob(["Content"])) // -> false - * isFile(createReadStream("path/to/a/file.txt")) // -> false - * ``` - */ -declare const isFile: (value: unknown) => value is FileLike; - -/** - * Check if given object is FormData - * - * @param value an object to test - */ -declare const isFormData: (value: unknown) => value is FormDataLike; - -export { FileLike, FormDataEncoder, FormDataEncoderOptions, FormDataEntryValue, FormDataLike, isFile, isFormData }; diff --git a/setup-pandoc/node_modules/form-data-encoder/lib/index.d.ts b/setup-pandoc/node_modules/form-data-encoder/lib/index.d.ts deleted file mode 100644 index b79e49ab4..000000000 --- a/setup-pandoc/node_modules/form-data-encoder/lib/index.d.ts +++ /dev/null @@ -1,277 +0,0 @@ -interface RawHeaders { - "Content-Type": string; - "Content-Length"?: string; -} -interface FormDataEncoderHeaders extends RawHeaders { - "content-type": string; - "content-length"?: string; -} - -interface FileLike { - /** - * Name of the file referenced by the File object. - */ - readonly name: string; - /** - * Returns the media type ([`MIME`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types)) of the file represented by a `File` object. - */ - readonly type: string; - /** - * Size of the file parts in bytes - */ - readonly size: number; - /** - * The last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date. - */ - readonly lastModified: number; - /** - * Returns a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) which upon reading returns the data contained within the [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). - */ - stream(): ReadableStream | AsyncIterable; - readonly [Symbol.toStringTag]?: string; -} - -/** - * A `string` or `File` that represents a single value from a set of `FormData` key-value pairs. - */ -type FormDataEntryValue = string | FileLike; -/** - * This interface reflects minimal shape of the FormData - */ -interface FormDataLike { - /** - * Appends a new value onto an existing key inside a FormData object, - * or adds the key if it does not already exist. - * - * The difference between `set()` and `append()` is that if the specified key already exists, `set()` will overwrite all existing values with the new one, whereas `append()` will append the new value onto the end of the existing set of values. - * - * @param name The name of the field whose data is contained in `value`. - * @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) - or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string. - * @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename. - */ - append(name: string, value: unknown, fileName?: string): void; - /** - * Returns all the values associated with a given key from within a `FormData` object. - * - * @param {string} name A name of the value you want to retrieve. - * - * @returns An array of `FormDataEntryValue` whose key matches the value passed in the `name` parameter. If the key doesn't exist, the method returns an empty list. - */ - getAll(name: string): FormDataEntryValue[]; - /** - * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through the `FormData` key/value pairs. - * The key of each pair is a string; the value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue). - */ - entries(): IterableIterator<[string, FormDataEntryValue]>; - /** - * An alias for FormDataLike#entries() - */ - [Symbol.iterator](): IterableIterator<[string, FormDataEntryValue]>; - readonly [Symbol.toStringTag]?: string; -} - -interface FormDataEncoderOptions { - /** - * When enabled, the encoder will emit additional per part headers, such as `Content-Length`. - * - * Please note that the web clients do not include these, so when enabled this option might cause an error if `multipart/form-data` does not consider additional headers. - * - * Defaults to `false`. - */ - enableAdditionalHeaders?: boolean; -} -/** - * Implements [`multipart/form-data` encoding algorithm](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#multipart/form-data-encoding-algorithm), - * allowing to add support for spec-comliant [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) to an HTTP client. - */ -declare class FormDataEncoder { - #private; - /** - * Returns boundary string - */ - readonly boundary: string; - /** - * Returns Content-Type header - */ - readonly contentType: string; - /** - * Returns Content-Length header - */ - readonly contentLength: string | undefined; - /** - * Returns headers object with Content-Type and Content-Length header - */ - readonly headers: Readonly; - /** - * Creates a multipart/form-data encoder. - * - * @param form FormData object to encode. This object must be a spec-compatible FormData implementation. - * - * @example - * - * ```js - * import {Readable} from "stream" - * - * import {FormData, File, fileFromPath} from "formdata-node" - * import {FormDataEncoder} from "form-data-encoder" - * - * import fetch from "node-fetch" - * - * const form = new FormData() - * - * form.set("field", "Just a random string") - * form.set("file", new File(["Using files is class amazing"], "file.txt")) - * form.set("fileFromPath", await fileFromPath("path/to/a/file.txt")) - * - * const encoder = new FormDataEncoder(form) - * - * const options = { - * method: "post", - * headers: encoder.headers, - * body: Readable.from(encoder) - * } - * - * const response = await fetch("https://httpbin.org/post", options) - * - * console.log(await response.json()) - * ``` - */ - constructor(form: FormDataLike); - /** - * Creates multipart/form-data encoder with custom boundary string. - * - * @param form FormData object to encode. This object must be a spec-compatible FormData implementation. - * @param boundary An optional boundary string that will be used by the encoder. If there's no boundary string is present, Encoder will generate it automatically. - */ - constructor(form: FormDataLike, boundary: string); - /** - * Creates multipart/form-data encoder with additional options. - * - * @param form FormData object to encode. This object must be a spec-compatible FormData implementation. - * @param options Additional options - */ - constructor(form: FormDataLike, options: FormDataEncoderOptions); - constructor(form: FormDataLike, boundary: string, options?: FormDataEncoderOptions); - /** - * Creates an iterator allowing to go through form-data parts (with metadata). - * This method **will not** read the files and **will not** split values big into smaller chunks. - * - * Using this method, you can convert form-data content into Blob: - * - * @example - * - * ```ts - * import {Readable} from "stream" - * - * import {FormDataEncoder} from "form-data-encoder" - * - * import {FormData} from "formdata-polyfill/esm-min.js" - * import {fileFrom} from "fetch-blob/form.js" - * import {File} from "fetch-blob/file.js" - * import {Blob} from "fetch-blob" - * - * import fetch from "node-fetch" - * - * const form = new FormData() - * - * form.set("field", "Just a random string") - * form.set("file", new File(["Using files is class amazing"])) - * form.set("fileFromPath", await fileFrom("path/to/a/file.txt")) - * - * const encoder = new FormDataEncoder(form) - * - * const options = { - * method: "post", - * body: new Blob(encoder, {type: encoder.contentType}) - * } - * - * const response = await fetch("https://httpbin.org/post", options) - * - * console.log(await response.json()) - * ``` - */ - values(): Generator; - /** - * Creates an async iterator allowing to perform the encoding by portions. - * This method reads through files and splits big values into smaller pieces (65536 bytes per each). - * - * @example - * - * ```ts - * import {Readable} from "stream" - * - * import {FormData, File, fileFromPath} from "formdata-node" - * import {FormDataEncoder} from "form-data-encoder" - * - * import fetch from "node-fetch" - * - * const form = new FormData() - * - * form.set("field", "Just a random string") - * form.set("file", new File(["Using files is class amazing"], "file.txt")) - * form.set("fileFromPath", await fileFromPath("path/to/a/file.txt")) - * - * const encoder = new FormDataEncoder(form) - * - * const options = { - * method: "post", - * headers: encoder.headers, - * body: Readable.from(encoder.encode()) // or Readable.from(encoder) - * } - * - * const response = await fetch("https://httpbin.org/post", options) - * - * console.log(await response.json()) - * ``` - */ - encode(): AsyncGenerator; - /** - * Creates an iterator allowing to read through the encoder data using for...of loops - */ - [Symbol.iterator](): Generator; - /** - * Creates an **async** iterator allowing to read through the encoder data using for-await...of loops - */ - [Symbol.asyncIterator](): AsyncGenerator; -} - -/** - * Check if given object is `File`. - * - * Note that this function will return `false` for Blob, because the FormDataEncoder expects FormData to return File when a value is binary data. - * - * @param value an object to test - * - * @api public - * - * This function will return `true` for FileAPI compatible `File` objects: - * - * ```ts - * import {createReadStream} from "node:fs" - * - * import {isFile} from "form-data-encoder" - * - * isFile(new File(["Content"], "file.txt")) // -> true - * ``` - * - * However, if you pass a Node.js `Buffer`, or `Blob`, or `ReadStream`, it will return `false`: - * - * ```js - * import {isFile} from "form-data-encoder" - * - * isFile(Buffer.from("Content")) // -> false - * isFile(new Blob(["Content"])) // -> false - * isFile(createReadStream("path/to/a/file.txt")) // -> false - * ``` - */ -declare const isFile: (value: unknown) => value is FileLike; - -/** - * Check if given object is FormData - * - * @param value an object to test - */ -declare const isFormData: (value: unknown) => value is FormDataLike; - -export { FileLike, FormDataEncoder, FormDataEncoderOptions, FormDataEntryValue, FormDataLike, isFile, isFormData }; diff --git a/setup-pandoc/node_modules/form-data-encoder/lib/index.js b/setup-pandoc/node_modules/form-data-encoder/lib/index.js deleted file mode 100644 index 96a8046b1..000000000 --- a/setup-pandoc/node_modules/form-data-encoder/lib/index.js +++ /dev/null @@ -1,365 +0,0 @@ -var __accessCheck = (obj, member, msg) => { - if (!member.has(obj)) - throw TypeError("Cannot " + msg); -}; -var __privateGet = (obj, member, getter) => { - __accessCheck(obj, member, "read from private field"); - return getter ? getter.call(obj) : member.get(obj); -}; -var __privateAdd = (obj, member, value) => { - if (member.has(obj)) - throw TypeError("Cannot add the same private member more than once"); - member instanceof WeakSet ? member.add(obj) : member.set(obj, value); -}; -var __privateSet = (obj, member, value, setter) => { - __accessCheck(obj, member, "write to private field"); - setter ? setter.call(obj, value) : member.set(obj, value); - return value; -}; -var __privateMethod = (obj, member, method) => { - __accessCheck(obj, member, "access private method"); - return method; -}; - -// src/util/isFunction.ts -var isFunction = (value) => typeof value === "function"; - -// src/util/isAsyncIterable.ts -var isAsyncIterable = (value) => isFunction(value[Symbol.asyncIterator]); - -// src/util/chunk.ts -var MAX_CHUNK_SIZE = 65536; -function* chunk(value) { - if (value.byteLength <= MAX_CHUNK_SIZE) { - yield value; - return; - } - let offset = 0; - while (offset < value.byteLength) { - const size = Math.min(value.byteLength - offset, MAX_CHUNK_SIZE); - const buffer = value.buffer.slice(offset, offset + size); - offset += buffer.byteLength; - yield new Uint8Array(buffer); - } -} - -// src/util/getStreamIterator.ts -async function* readStream(readable) { - const reader = readable.getReader(); - while (true) { - const { done, value } = await reader.read(); - if (done) { - break; - } - yield value; - } -} -async function* chunkStream(stream) { - for await (const value of stream) { - yield* chunk(value); - } -} -var getStreamIterator = (source) => { - if (isAsyncIterable(source)) { - return chunkStream(source); - } - if (isFunction(source.getReader)) { - return chunkStream(readStream(source)); - } - throw new TypeError( - "Unsupported data source: Expected either ReadableStream or async iterable." - ); -}; - -// src/util/createBoundary.ts -var alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"; -function createBoundary() { - let size = 16; - let res = ""; - while (size--) { - res += alphabet[Math.random() * alphabet.length << 0]; - } - return res; -} - -// src/util/normalizeValue.ts -var normalizeValue = (value) => String(value).replace(/\r|\n/g, (match, i, str) => { - if (match === "\r" && str[i + 1] !== "\n" || match === "\n" && str[i - 1] !== "\r") { - return "\r\n"; - } - return match; -}); - -// src/util/isPlainObject.ts -var getType = (value) => Object.prototype.toString.call(value).slice(8, -1).toLowerCase(); -function isPlainObject(value) { - if (getType(value) !== "object") { - return false; - } - const pp = Object.getPrototypeOf(value); - if (pp === null || pp === void 0) { - return true; - } - const Ctor = pp.constructor && pp.constructor.toString(); - return Ctor === Object.toString(); -} - -// src/util/proxyHeaders.ts -function getProperty(target, prop) { - if (typeof prop === "string") { - for (const [name, value] of Object.entries(target)) { - if (prop.toLowerCase() === name.toLowerCase()) { - return value; - } - } - } - return void 0; -} -var proxyHeaders = (object) => new Proxy( - object, - { - get: (target, prop) => getProperty(target, prop), - has: (target, prop) => getProperty(target, prop) !== void 0 - } -); - -// src/util/isFormData.ts -var isFormData = (value) => Boolean( - value && isFunction(value.constructor) && value[Symbol.toStringTag] === "FormData" && isFunction(value.append) && isFunction(value.getAll) && isFunction(value.entries) && isFunction(value[Symbol.iterator]) -); - -// src/util/escapeName.ts -var escapeName = (name) => String(name).replace(/\r/g, "%0D").replace(/\n/g, "%0A").replace(/"/g, "%22"); - -// src/util/isFile.ts -var isFile = (value) => Boolean( - value && typeof value === "object" && isFunction(value.constructor) && value[Symbol.toStringTag] === "File" && isFunction(value.stream) && value.name != null -); - -// src/FormDataEncoder.ts -var defaultOptions = { - enableAdditionalHeaders: false -}; -var readonlyProp = { writable: false, configurable: false }; -var _CRLF, _CRLF_BYTES, _CRLF_BYTES_LENGTH, _DASHES, _encoder, _footer, _form, _options, _getFieldHeader, getFieldHeader_fn, _getContentLength, getContentLength_fn; -var FormDataEncoder = class { - constructor(form, boundaryOrOptions, options) { - __privateAdd(this, _getFieldHeader); - /** - * Returns form-data content length - */ - __privateAdd(this, _getContentLength); - __privateAdd(this, _CRLF, "\r\n"); - __privateAdd(this, _CRLF_BYTES, void 0); - __privateAdd(this, _CRLF_BYTES_LENGTH, void 0); - __privateAdd(this, _DASHES, "-".repeat(2)); - /** - * TextEncoder instance - */ - __privateAdd(this, _encoder, new TextEncoder()); - /** - * Returns form-data footer bytes - */ - __privateAdd(this, _footer, void 0); - /** - * FormData instance - */ - __privateAdd(this, _form, void 0); - /** - * Instance options - */ - __privateAdd(this, _options, void 0); - if (!isFormData(form)) { - throw new TypeError("Expected first argument to be a FormData instance."); - } - let boundary; - if (isPlainObject(boundaryOrOptions)) { - options = boundaryOrOptions; - } else { - boundary = boundaryOrOptions; - } - if (!boundary) { - boundary = createBoundary(); - } - if (typeof boundary !== "string") { - throw new TypeError("Expected boundary argument to be a string."); - } - if (options && !isPlainObject(options)) { - throw new TypeError("Expected options argument to be an object."); - } - __privateSet(this, _form, Array.from(form.entries())); - __privateSet(this, _options, { ...defaultOptions, ...options }); - __privateSet(this, _CRLF_BYTES, __privateGet(this, _encoder).encode(__privateGet(this, _CRLF))); - __privateSet(this, _CRLF_BYTES_LENGTH, __privateGet(this, _CRLF_BYTES).byteLength); - this.boundary = `form-data-boundary-${boundary}`; - this.contentType = `multipart/form-data; boundary=${this.boundary}`; - __privateSet(this, _footer, __privateGet(this, _encoder).encode( - `${__privateGet(this, _DASHES)}${this.boundary}${__privateGet(this, _DASHES)}${__privateGet(this, _CRLF).repeat(2)}` - )); - const headers = { - "Content-Type": this.contentType - }; - const contentLength = __privateMethod(this, _getContentLength, getContentLength_fn).call(this); - if (contentLength) { - this.contentLength = contentLength; - headers["Content-Length"] = contentLength; - } - this.headers = proxyHeaders(Object.freeze(headers)); - Object.defineProperties(this, { - boundary: readonlyProp, - contentType: readonlyProp, - contentLength: readonlyProp, - headers: readonlyProp - }); - } - /** - * Creates an iterator allowing to go through form-data parts (with metadata). - * This method **will not** read the files and **will not** split values big into smaller chunks. - * - * Using this method, you can convert form-data content into Blob: - * - * @example - * - * ```ts - * import {Readable} from "stream" - * - * import {FormDataEncoder} from "form-data-encoder" - * - * import {FormData} from "formdata-polyfill/esm-min.js" - * import {fileFrom} from "fetch-blob/form.js" - * import {File} from "fetch-blob/file.js" - * import {Blob} from "fetch-blob" - * - * import fetch from "node-fetch" - * - * const form = new FormData() - * - * form.set("field", "Just a random string") - * form.set("file", new File(["Using files is class amazing"])) - * form.set("fileFromPath", await fileFrom("path/to/a/file.txt")) - * - * const encoder = new FormDataEncoder(form) - * - * const options = { - * method: "post", - * body: new Blob(encoder, {type: encoder.contentType}) - * } - * - * const response = await fetch("https://httpbin.org/post", options) - * - * console.log(await response.json()) - * ``` - */ - *values() { - for (const [name, raw] of __privateGet(this, _form)) { - const value = isFile(raw) ? raw : __privateGet(this, _encoder).encode( - normalizeValue(raw) - ); - yield __privateMethod(this, _getFieldHeader, getFieldHeader_fn).call(this, name, value); - yield value; - yield __privateGet(this, _CRLF_BYTES); - } - yield __privateGet(this, _footer); - } - /** - * Creates an async iterator allowing to perform the encoding by portions. - * This method reads through files and splits big values into smaller pieces (65536 bytes per each). - * - * @example - * - * ```ts - * import {Readable} from "stream" - * - * import {FormData, File, fileFromPath} from "formdata-node" - * import {FormDataEncoder} from "form-data-encoder" - * - * import fetch from "node-fetch" - * - * const form = new FormData() - * - * form.set("field", "Just a random string") - * form.set("file", new File(["Using files is class amazing"], "file.txt")) - * form.set("fileFromPath", await fileFromPath("path/to/a/file.txt")) - * - * const encoder = new FormDataEncoder(form) - * - * const options = { - * method: "post", - * headers: encoder.headers, - * body: Readable.from(encoder.encode()) // or Readable.from(encoder) - * } - * - * const response = await fetch("https://httpbin.org/post", options) - * - * console.log(await response.json()) - * ``` - */ - async *encode() { - for (const part of this.values()) { - if (isFile(part)) { - yield* getStreamIterator(part.stream()); - } else { - yield* chunk(part); - } - } - } - /** - * Creates an iterator allowing to read through the encoder data using for...of loops - */ - [Symbol.iterator]() { - return this.values(); - } - /** - * Creates an **async** iterator allowing to read through the encoder data using for-await...of loops - */ - [Symbol.asyncIterator]() { - return this.encode(); - } -}; -_CRLF = new WeakMap(); -_CRLF_BYTES = new WeakMap(); -_CRLF_BYTES_LENGTH = new WeakMap(); -_DASHES = new WeakMap(); -_encoder = new WeakMap(); -_footer = new WeakMap(); -_form = new WeakMap(); -_options = new WeakMap(); -_getFieldHeader = new WeakSet(); -getFieldHeader_fn = function(name, value) { - let header = ""; - header += `${__privateGet(this, _DASHES)}${this.boundary}${__privateGet(this, _CRLF)}`; - header += `Content-Disposition: form-data; name="${escapeName(name)}"`; - if (isFile(value)) { - header += `; filename="${escapeName(value.name)}"${__privateGet(this, _CRLF)}`; - header += `Content-Type: ${value.type || "application/octet-stream"}`; - } - if (__privateGet(this, _options).enableAdditionalHeaders === true) { - const size = isFile(value) ? value.size : value.byteLength; - if (size != null && !isNaN(size)) { - header += `${__privateGet(this, _CRLF)}Content-Length: ${size}`; - } - } - return __privateGet(this, _encoder).encode(`${header}${__privateGet(this, _CRLF).repeat(2)}`); -}; -_getContentLength = new WeakSet(); -getContentLength_fn = function() { - let length = 0; - for (const [name, raw] of __privateGet(this, _form)) { - const value = isFile(raw) ? raw : __privateGet(this, _encoder).encode( - normalizeValue(raw) - ); - const size = isFile(value) ? value.size : value.byteLength; - if (size == null || isNaN(size)) { - return void 0; - } - length += __privateMethod(this, _getFieldHeader, getFieldHeader_fn).call(this, name, value).byteLength; - length += size; - length += __privateGet(this, _CRLF_BYTES_LENGTH); - } - return String(length + __privateGet(this, _footer).byteLength); -}; -export { - FormDataEncoder, - isFile, - isFormData -}; diff --git a/setup-pandoc/node_modules/form-data-encoder/package.json b/setup-pandoc/node_modules/form-data-encoder/package.json deleted file mode 100644 index 57070f857..000000000 --- a/setup-pandoc/node_modules/form-data-encoder/package.json +++ /dev/null @@ -1,84 +0,0 @@ -{ - "type": "module", - "name": "form-data-encoder", - "description": "Encode FormData content into the multipart/form-data format", - "version": "4.0.2", - "author": "Nick K.", - "license": "MIT", - "repository": "octet-stream/form-data-encoder", - "sideEffects": false, - "packageManager": "pnpm@8.5.1", - "engines": { - "node": ">= 18" - }, - "keywords": [ - "form-data", - "encoder", - "multipart", - "files-upload", - "async-iterator", - "spec-compatible", - "form" - ], - "main": "./lib/index.js", - "module": "./lib/index.js", - "exports": { - "./package.json": "./package.json", - ".": { - "import": { - "types": "./lib/index.d.ts", - "default": "./lib/index.js" - }, - "require": { - "types": "./lib/index.d.cts", - "default": "./lib/index.cjs" - } - } - }, - "types": "./lib/index.d.ts", - "devDependencies": { - "@changesets/changelog-github": "0.4.8", - "@changesets/cli": "2.26.2", - "@octetstream/eslint-config": "7.2.1", - "@types/mime-types": "2.1.1", - "@types/node": "20.2.1", - "@types/sinon": "10.0.15", - "@typescript-eslint/eslint-plugin": "5.59.6", - "@typescript-eslint/parser": "5.59.6", - "ava": "5.2.0", - "c8": "7.13.0", - "cross-env": "7.0.3", - "del-cli": "5.0.0", - "eslint": "8.40.0", - "eslint-config-airbnb-typescript": "17.0.0", - "eslint-import-resolver-typescript": "3.5.5", - "eslint-plugin-ava": "14.0.0", - "eslint-plugin-import": "2.27.5", - "eslint-plugin-jsx-a11y": "6.7.1", - "eslint-plugin-react": "7.32.2", - "formdata-node": "6.0.2", - "husky": "8.0.3", - "lint-staged": "13.2.2", - "node-fetch": "^3.3.2", - "pinst": "3.0.0", - "sinon": "15.0.4", - "ts-expect": "^1.3.0", - "ts-node": "10.9.1", - "tsup": "7.2.0", - "ttypescript": "1.5.15", - "typescript": "5.0.4", - "undici": "^5.26.5", - "web-streams-polyfill": "4.0.0-beta.3" - }, - "scripts": { - "eslint": "eslint src/**/*.ts", - "lint:types": "tsc --noEmit", - "lint": "pnpm eslint && pnpm lint:types", - "staged": "lint-staged", - "coverage": "c8 pnpm test", - "ci": "c8 pnpm test && c8 report --reporter=json", - "build": "pnpm exec del-cli lib && pnpm exec tsup", - "test": "cross-env NODE_OPTIONS=\"--no-warnings --experimental-fetch --loader=ts-node/esm\" ava", - "release": "pnpm build && pnpm changeset publish" - } -} \ No newline at end of file diff --git a/setup-pandoc/node_modules/form-data-encoder/readme.md b/setup-pandoc/node_modules/form-data-encoder/readme.md deleted file mode 100644 index 20192e479..000000000 --- a/setup-pandoc/node_modules/form-data-encoder/readme.md +++ /dev/null @@ -1,369 +0,0 @@ -# form-data-encoder - -Encode `FormData` content into the `multipart/form-data` format - -[![Code Coverage](https://codecov.io/github/octet-stream/form-data-encoder/coverage.svg?branch=main)](https://codecov.io/github/octet-stream/form-data-encoder?branch=main) -[![CI](https://github.com/octet-stream/form-data-encoder/workflows/CI/badge.svg)](https://github.com/octet-stream/form-data-encoder/actions/workflows/ci.yml) -[![ESLint](https://github.com/octet-stream/form-data-encoder/workflows/ESLint/badge.svg)](https://github.com/octet-stream/form-data-encoder/actions/workflows/eslint.yml) -[![TypeScript Types](https://github.com/octet-stream/form-data-encoder/actions/workflows/typescript.yml/badge.svg)](https://github.com/octet-stream/form-data-encoder/actions/workflows/typescript.yml) - -## Requirements - -- Node.js v18.0.0 or higher; -- Runtime should support `TextEncoder`, `TextDecoder`, `WeakMap`, `WeakSet` and async generator functions; -- For TypeScript users: tsc v4.3 or higher. - -## Installation - -You can install this package using npm: - -```sh -npm install form-data-encoder -``` - -Or yarn: - -```sh -yarn add form-data-encoder -``` - -Or pnpm: - -```sh -pnpm add form-data-encoder -``` - -## Usage - -1. To start the encoding process, you need to create a new Encoder instance with the FormData you want to encode: - -```js -import {Readable} from "stream" - -import {FormData, File} from "formdata-node" -import {FormDataEncoder} from "form-data-encoder" - -import fetch from "node-fetch" - -const form = new FormData() - -form.set("greeting", "Hello, World!") -form.set("file", new File(["On Soviet Moon landscape see binoculars through YOU"], "file.txt")) - -const encoder = new FormDataEncoder(form) - -const options = { - method: "post", - - // Set request headers provided by the Encoder. - // The `headers` property has `Content-Type` and `Content-Length` headers. - headers: encoder.headers, - - // Create a Readable stream from the Encoder. - // You can omit usage of `Readable.from` for HTTP clients whose support async iterables in request body. - // The Encoder will yield FormData content portions encoded into the multipart/form-data format as node-fetch consumes the stream. - body: Readable.from(encoder.encode()) // or just Readable.from(encoder) -} - -const response = await fetch("https://httpbin.org/post", options) - -console.log(await response.json()) -``` - -2. Encoder support different spec-compatible FormData implementations. Let's try it with [`formdata-polyfill`](https://github.com/jimmywarting/FormData): - -```js -import {Readable} from "stream" - -import {FormDataEncoder} from "form-data-encoder" -import {FormData} from "formdata-polyfill/esm-min.js" -import {File} from "fetch-blob" // v3 - -const form = new FormData() - -form.set("field", "Some value") -form.set("file", new File(["File content goes here"], "file.txt")) - -const encoder = new FormDataEncoder(form) - -const options = { - method: "post", - headers: encoder.headers, - body: Readable.from(encoder) -} - -await fetch("https://httpbin.org/post", options) -``` - -3. Because the Encoder is iterable (it has both Symbol.asyncIterator and Symbol.iterator methods), you can use it with different targets. Let's say you want to convert FormData content into `Blob`, for that you can write a function like this: - -```js -import {Readable} from "stream" - -import {FormDataEncoder} from "form-data-encoder" -import {FormData, File, Blob} from "formdata-node" -import {fileFromPath} from "formdata-node/file-from-path" - -import fetch from "node-fetch" - -const form = new FormData() - -form.set("field", "Just a random string") -form.set("file", new File(["Using files is class amazing"], "file.txt")) -form.set("fileFromPath", await fileFromPath("path/to/a/file.txt")) - -// Note 1: When using with native Blob or fetch-blob@2 you might also need to generate boundary string for your FormDataEncoder instance -// because Blob will lowercase value of the `type` option and default boundary generator produces a string with both lower and upper cased alphabetical characters. Math.random() should be enough to fix this: -// const encoder = new FormDataEncoder(form, String(Math.random())) -const encoder = new FormDataEncoder(form) - -const options = { - method: "post", - - // Note 2: To use this approach with fetch-blob@2 you probably gonna need to convert the encoder parts output to an array first: - // new Blob([...encoder], {type: encoder.contentType}) - body: new Blob(encoder, {type: encoder.contentType}) -} - -const response = await fetch("https://httpbin.org/post", options) - -console.log(await response.json()) -``` - -4. Here's FormData to Blob conversion with async-iterator approach: - -```js -import {FormData} from "formdata-polyfill/esm-min.js" -import {FormDataEncoder} from "form-data-encoder" -import {blobFrom} from "fetch-blob/from.js" - -import Blob from "fetch-blob" -import fetch from "node-fetch" - -// This approach may require much more RAM compared to the previous one, but it works too. -async function toBlob(form) { - const encoder = new Encoder(form) - const chunks = [] - - for await (const chunk of encoder) { - chunks.push(chunk) - } - - return new Blob(chunks, {type: encoder.contentType}) -} - -const form = new FormData() - -form.set("name", "John Doe") -form.set("avatar", await blobFrom("path/to/an/avatar.png"), "avatar.png") - -const options = { - method: "post", - body: await toBlob(form) -} - -await fetch("https://httpbin.org/post", options) -``` - -5. Another way to convert FormData parts to blob using `form-data-encoder` is making a Blob-ish class: - -```js -import {Readable} from "stream" - -import {FormDataEncoder} from "form-data-encoder" -import {FormData} from "formdata-polyfill/esm-min.js" -import {blobFrom} from "fetch-blob/from.js" - -import Blob from "fetch-blob" -import fetch from "node-fetch" - -class BlobDataItem { - constructor(encoder) { - this.#encoder = encoder - this.#size = encoder.headers["Content-Length"] - this.#type = encoder.headers["Content-Type"] - } - - get type() { - return this.#type - } - - get size() { - return this.#size - } - - stream() { - return Readable.from(this.#encoder) - } - - get [Symbol.toStringTag]() { - return "Blob" - } -} - -const form = new FormData() - -form.set("name", "John Doe") -form.set("avatar", await blobFrom("path/to/an/avatar.png"), "avatar.png") - -const encoder = new FormDataEncoder(form) - -// Note that node-fetch@2 performs more strictness tests for Blob objects, so you may need to do extra steps before you set up request body (like, maybe you'll need to instaniate a Blob with BlobDataItem as one of its blobPart) -const blob = new BlobDataItem(enocoder) // or new Blob([new BlobDataItem(enocoder)], {type: encoder.contentType}) - -const options = { - method: "post", - body: blob -} - -await fetch("https://httpbin.org/post", options) -``` - -6. In this example we will pull FormData content into the ReadableStream: - -```js - // This module is only necessary when you targeting Node.js or need web streams that implement Symbol.asyncIterator -import {ReadableStream} from "web-streams-polyfill/ponyfill/es2018" - -import {FormDataEncoder} from "form-data-encoder" -import {FormData} from "formdata-node" - -import fetch from "node-fetch" - -function toReadableStream(encoder) { - const iterator = encoder.encode() - - return new ReadableStream({ - async pull(controller) { - const {value, done} = await iterator.next() - - if (done) { - return controller.close() - } - - controller.enqueue(value) - } - }) -} - -const form = new FormData() - -form.set("field", "My hovercraft is full of eels") - -const encoder = new FormDataEncoder(form) - -const options = { - method: "post", - headers: encoder.headers, - body: toReadableStream(encoder) -} - -// Note that this example requires `fetch` to support Symbol.asyncIterator, which node-fetch lacks of (but will support eventually) -await fetch("https://httpbin.org/post", options) -``` - -7. Speaking of async iterables - if HTTP client supports them, you can use encoder like this: - -```js -import {FormDataEncoder} from "form-data-encoder" -import {FormData} from "formdata-node" - -import fetch from "node-fetch" - -const form = new FormData() - -form.set("field", "My hovercraft is full of eels") - -const encoder = new FormDataEncoder(form) - -const options = { - method: "post", - headers: encoder.headers, - body: encoder -} - -await fetch("https://httpbin.org/post", options) -``` - -8. ...And for those client whose supporting form-data-encoder out of the box, the usage will be much, much more simpler: - -```js -import {FormData} from "formdata-node" // Or any other spec-compatible implementation - -import fetch from "node-fetch" - -const form = new FormData() - -form.set("field", "My hovercraft is full of eels") - -const options = { - method: "post", - body: form -} - -// Note that node-fetch does NOT support form-data-encoder -await fetch("https://httpbin.org/post", options) -``` - -## API - -### `class FormDataEncoder` - -##### `constructor(form[, boundary, options]) -> {FormDataEncoder}` - - - **{FormDataLike}** form - FormData object to encode. This object must be a spec-compatible FormData implementation. - - **{string}** [boundary] - An optional boundary string that will be used by the encoder. If there's no boundary string is present, FormDataEncoder will generate it automatically. - - **{object}** [options] - FormDataEncoder options. - - **{boolean}** [options.enableAdditionalHeaders = false] - When enabled, the encoder will emit additional per part headers, such as `Content-Length`. Please note that the web clients do not include these, so when enabled this option might cause an error if `multipart/form-data` does not consider additional headers. - -Creates a `multipart/form-data` encoder. - -#### Instance properties - -##### `boundary -> {string}` - -Returns boundary string. - -##### `contentType -> {string}` - -Returns Content-Type header. - -##### `contentLength -> {string}` - -Return Content-Length header. - -##### `headers -> {object}` - -Returns headers object with Content-Type and Content-Length header. - -#### Instance methods - -##### `values() -> {Generator}` - -Creates an iterator allowing to go through form-data parts (with metadata). -This method **will not** read the files and **will not** split values big into smaller chunks. - -##### `encode() -> {AsyncGenerator}` - -Creates an async iterator allowing to perform the encoding by portions. -This method reads through files and splits big values into smaller pieces (65536 bytes per each). - -##### `[Symbol.iterator]() -> {Generator}` - -An alias for `Encoder#values()` method. - -##### `[Symbol.asyncIterator]() -> {AsyncGenerator}` - -An alias for `Encoder#encode()` method. - -### `isFile(value) -> {boolean}` - -Check if a value is File-ish object. - - - **{unknown}** value - a value to test - -### `isFormData(value) -> {boolean}` - -Check if a value is FormData-ish object. - - - **{unknown}** value - a value to test diff --git a/setup-pandoc/node_modules/got/dist/source/as-promise/create-rejection.d.ts b/setup-pandoc/node_modules/got/dist/source/as-promise/create-rejection.d.ts new file mode 100644 index 000000000..f125a77f1 --- /dev/null +++ b/setup-pandoc/node_modules/got/dist/source/as-promise/create-rejection.d.ts @@ -0,0 +1,2 @@ +import { CancelableRequest, BeforeErrorHook } from './types'; +export default function createRejection(error: Error, ...beforeErrorGroups: Array): CancelableRequest; diff --git a/setup-pandoc/node_modules/got/dist/source/as-promise/create-rejection.js b/setup-pandoc/node_modules/got/dist/source/as-promise/create-rejection.js new file mode 100644 index 000000000..ce626040e --- /dev/null +++ b/setup-pandoc/node_modules/got/dist/source/as-promise/create-rejection.js @@ -0,0 +1,30 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const types_1 = require("./types"); +function createRejection(error, ...beforeErrorGroups) { + const promise = (async () => { + if (error instanceof types_1.RequestError) { + try { + for (const hooks of beforeErrorGroups) { + if (hooks) { + for (const hook of hooks) { + // eslint-disable-next-line no-await-in-loop + error = await hook(error); + } + } + } + } + catch (error_) { + error = error_; + } + } + throw error; + })(); + const returnPromise = () => promise; + promise.json = returnPromise; + promise.text = returnPromise; + promise.buffer = returnPromise; + promise.on = returnPromise; + return promise; +} +exports.default = createRejection; diff --git a/setup-pandoc/node_modules/got/dist/source/as-promise/index.d.ts b/setup-pandoc/node_modules/got/dist/source/as-promise/index.d.ts index e56088048..f06720ee0 100644 --- a/setup-pandoc/node_modules/got/dist/source/as-promise/index.d.ts +++ b/setup-pandoc/node_modules/got/dist/source/as-promise/index.d.ts @@ -1,3 +1,3 @@ -import Request from '../core/index.js'; -import { type CancelableRequest } from './types.js'; -export default function asPromise(firstRequest?: Request): CancelableRequest; +import { NormalizedOptions, CancelableRequest } from './types'; +export default function asPromise(normalizedOptions: NormalizedOptions): CancelableRequest; +export * from './types'; diff --git a/setup-pandoc/node_modules/got/dist/source/as-promise/index.js b/setup-pandoc/node_modules/got/dist/source/as-promise/index.js index d91fd0964..2a98ce609 100644 --- a/setup-pandoc/node_modules/got/dist/source/as-promise/index.js +++ b/setup-pandoc/node_modules/got/dist/source/as-promise/index.js @@ -1,89 +1,121 @@ -import { EventEmitter } from 'node:events'; -import is from '@sindresorhus/is'; -import PCancelable from 'p-cancelable'; -import { HTTPError, RetryError, } from '../core/errors.js'; -import Request from '../core/index.js'; -import { parseBody, isResponseOk } from '../core/response.js'; -import proxyEvents from '../core/utils/proxy-events.js'; -import { CancelError } from './types.js'; +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const events_1 = require("events"); +const is_1 = require("@sindresorhus/is"); +const PCancelable = require("p-cancelable"); +const types_1 = require("./types"); +const parse_body_1 = require("./parse-body"); +const core_1 = require("../core"); +const proxy_events_1 = require("../core/utils/proxy-events"); +const get_buffer_1 = require("../core/utils/get-buffer"); +const is_response_ok_1 = require("../core/utils/is-response-ok"); const proxiedRequestEvents = [ 'request', 'response', 'redirect', 'uploadProgress', - 'downloadProgress', + 'downloadProgress' ]; -export default function asPromise(firstRequest) { +function asPromise(normalizedOptions) { let globalRequest; let globalResponse; - let normalizedOptions; - const emitter = new EventEmitter(); + const emitter = new events_1.EventEmitter(); const promise = new PCancelable((resolve, reject, onCancel) => { - onCancel(() => { - globalRequest.destroy(); - }); - onCancel.shouldReject = false; - onCancel(() => { - reject(new CancelError(globalRequest)); - }); const makeRequest = (retryCount) => { - // Errors when a new request is made after the promise settles. - // Used to detect a race condition. - // See https://github.com/sindresorhus/got/issues/1489 - onCancel(() => { }); - const request = firstRequest ?? new Request(undefined, undefined, normalizedOptions); + const request = new core_1.default(undefined, normalizedOptions); request.retryCount = retryCount; request._noPipe = true; + onCancel(() => request.destroy()); + onCancel.shouldReject = false; + onCancel(() => reject(new types_1.CancelError(request))); globalRequest = request; request.once('response', async (response) => { + var _a; + response.retryCount = retryCount; + if (response.request.aborted) { + // Canceled while downloading - will throw a `CancelError` or `TimeoutError` error + return; + } + // Download body + let rawBody; + try { + rawBody = await get_buffer_1.default(request); + response.rawBody = rawBody; + } + catch (_b) { + // The same error is caught below. + // See request.once('error') + return; + } + if (request._isAboutToError) { + return; + } // Parse body - const contentEncoding = (response.headers['content-encoding'] ?? '').toLowerCase(); - const isCompressed = contentEncoding === 'gzip' || contentEncoding === 'deflate' || contentEncoding === 'br'; + const contentEncoding = ((_a = response.headers['content-encoding']) !== null && _a !== void 0 ? _a : '').toLowerCase(); + const isCompressed = ['gzip', 'deflate', 'br'].includes(contentEncoding); const { options } = request; if (isCompressed && !options.decompress) { - response.body = response.rawBody; + response.body = rawBody; } else { try { - response.body = parseBody(response, options.responseType, options.parseJson, options.encoding); + response.body = parse_body_1.default(response, options.responseType, options.parseJson, options.encoding); } catch (error) { - // Fall back to `utf8` - response.body = response.rawBody.toString(); - if (isResponseOk(response)) { + // Fallback to `utf8` + response.body = rawBody.toString(); + if (is_response_ok_1.isResponseOk(response)) { request._beforeError(error); return; } } } try { - const hooks = options.hooks.afterResponse; - for (const [index, hook] of hooks.entries()) { + for (const [index, hook] of options.hooks.afterResponse.entries()) { // @ts-expect-error TS doesn't notice that CancelableRequest is a Promise // eslint-disable-next-line no-await-in-loop response = await hook(response, async (updatedOptions) => { - options.merge(updatedOptions); - options.prefixUrl = ''; - if (updatedOptions.url) { - options.url = updatedOptions.url; - } + const typedOptions = core_1.default.normalizeArguments(undefined, { + ...updatedOptions, + retry: { + calculateDelay: () => 0 + }, + throwHttpErrors: false, + resolveBodyOnly: false + }, options); // Remove any further hooks for that request, because we'll call them anyway. // The loop continues. We don't want duplicates (asPromise recursion). - options.hooks.afterResponse = options.hooks.afterResponse.slice(0, index); - throw new RetryError(request); + typedOptions.hooks.afterResponse = typedOptions.hooks.afterResponse.slice(0, index); + for (const hook of typedOptions.hooks.beforeRetry) { + // eslint-disable-next-line no-await-in-loop + await hook(typedOptions); + } + const promise = asPromise(typedOptions); + onCancel(() => { + promise.catch(() => { }); + promise.cancel(); + }); + return promise; }); - if (!(is.object(response) && is.number(response.statusCode) && !is.nullOrUndefined(response.body))) { - throw new TypeError('The `afterResponse` hook returned an invalid value'); - } } } catch (error) { - request._beforeError(error); + request._beforeError(new types_1.RequestError(error.message, error, request)); return; } globalResponse = response; - if (!isResponseOk(response)) { - request._beforeError(new HTTPError(response)); + if (!is_response_ok_1.isResponseOk(response)) { + request._beforeError(new types_1.HTTPError(response)); return; } request.destroy(); @@ -94,33 +126,24 @@ export default function asPromise(firstRequest) { return; } const { options } = request; - if (error instanceof HTTPError && !options.throwHttpErrors) { + if (error instanceof types_1.HTTPError && !options.throwHttpErrors) { const { response } = error; - request.destroy(); resolve(request.options.resolveBodyOnly ? response.body : response); return; } reject(error); }; request.once('error', onError); - const previousBody = request.options?.body; + const previousBody = request.options.body; request.once('retry', (newRetryCount, error) => { - firstRequest = undefined; - const newBody = request.options.body; - if (previousBody === newBody && is.nodeStream(newBody)) { - error.message = 'Cannot retry with consumed body stream'; + var _a, _b; + if (previousBody === ((_a = error.request) === null || _a === void 0 ? void 0 : _a.options.body) && is_1.default.nodeStream((_b = error.request) === null || _b === void 0 ? void 0 : _b.options.body)) { onError(error); return; } - // This is needed! We need to reuse `request.options` because they can get modified! - // For example, by calling `promise.json()`. - normalizedOptions = request.options; makeRequest(newRetryCount); }); - proxyEvents(request, emitter, proxiedRequestEvents); - if (is.undefined(firstRequest)) { - void request.flush(); - } + proxy_events_1.default(request, emitter, proxiedRequestEvents); }; makeRequest(0); }); @@ -128,27 +151,20 @@ export default function asPromise(firstRequest) { emitter.on(event, fn); return promise; }; - promise.off = (event, fn) => { - emitter.off(event, fn); - return promise; - }; const shortcut = (responseType) => { const newPromise = (async () => { // Wait until downloading has ended await promise; const { options } = globalResponse.request; - return parseBody(globalResponse, responseType, options.parseJson, options.encoding); + return parse_body_1.default(globalResponse, responseType, options.parseJson, options.encoding); })(); - // eslint-disable-next-line @typescript-eslint/no-floating-promises Object.defineProperties(newPromise, Object.getOwnPropertyDescriptors(promise)); return newPromise; }; promise.json = () => { - if (globalRequest.options) { - const { headers } = globalRequest.options; - if (!globalRequest.writableFinished && !('accept' in headers)) { - headers.accept = 'application/json'; - } + const { headers } = globalRequest.options; + if (!globalRequest.writableFinished && headers.accept === undefined) { + headers.accept = 'application/json'; } return shortcut('json'); }; @@ -156,3 +172,5 @@ export default function asPromise(firstRequest) { promise.text = () => shortcut('text'); return promise; } +exports.default = asPromise; +__exportStar(require("./types"), exports); diff --git a/setup-pandoc/node_modules/got/dist/source/as-promise/normalize-arguments.d.ts b/setup-pandoc/node_modules/got/dist/source/as-promise/normalize-arguments.d.ts new file mode 100644 index 000000000..0b1e95fa5 --- /dev/null +++ b/setup-pandoc/node_modules/got/dist/source/as-promise/normalize-arguments.d.ts @@ -0,0 +1,3 @@ +import { NormalizedOptions, Defaults } from './types'; +declare const normalizeArguments: (options: NormalizedOptions, defaults?: Defaults | undefined) => NormalizedOptions; +export default normalizeArguments; diff --git a/setup-pandoc/node_modules/got/dist/source/as-promise/normalize-arguments.js b/setup-pandoc/node_modules/got/dist/source/as-promise/normalize-arguments.js new file mode 100644 index 000000000..859feb99f --- /dev/null +++ b/setup-pandoc/node_modules/got/dist/source/as-promise/normalize-arguments.js @@ -0,0 +1,78 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const is_1 = require("@sindresorhus/is"); +const normalizeArguments = (options, defaults) => { + if (is_1.default.null_(options.encoding)) { + throw new TypeError('To get a Buffer, set `options.responseType` to `buffer` instead'); + } + is_1.assert.any([is_1.default.string, is_1.default.undefined], options.encoding); + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.resolveBodyOnly); + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.methodRewriting); + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.isStream); + is_1.assert.any([is_1.default.string, is_1.default.undefined], options.responseType); + // `options.responseType` + if (options.responseType === undefined) { + options.responseType = 'text'; + } + // `options.retry` + const { retry } = options; + if (defaults) { + options.retry = { ...defaults.retry }; + } + else { + options.retry = { + calculateDelay: retryObject => retryObject.computedValue, + limit: 0, + methods: [], + statusCodes: [], + errorCodes: [], + maxRetryAfter: undefined + }; + } + if (is_1.default.object(retry)) { + options.retry = { + ...options.retry, + ...retry + }; + options.retry.methods = [...new Set(options.retry.methods.map(method => method.toUpperCase()))]; + options.retry.statusCodes = [...new Set(options.retry.statusCodes)]; + options.retry.errorCodes = [...new Set(options.retry.errorCodes)]; + } + else if (is_1.default.number(retry)) { + options.retry.limit = retry; + } + if (is_1.default.undefined(options.retry.maxRetryAfter)) { + options.retry.maxRetryAfter = Math.min( + // TypeScript is not smart enough to handle `.filter(x => is.number(x))`. + // eslint-disable-next-line unicorn/no-fn-reference-in-iterator + ...[options.timeout.request, options.timeout.connect].filter(is_1.default.number)); + } + // `options.pagination` + if (is_1.default.object(options.pagination)) { + if (defaults) { + options.pagination = { + ...defaults.pagination, + ...options.pagination + }; + } + const { pagination } = options; + if (!is_1.default.function_(pagination.transform)) { + throw new Error('`options.pagination.transform` must be implemented'); + } + if (!is_1.default.function_(pagination.shouldContinue)) { + throw new Error('`options.pagination.shouldContinue` must be implemented'); + } + if (!is_1.default.function_(pagination.filter)) { + throw new TypeError('`options.pagination.filter` must be implemented'); + } + if (!is_1.default.function_(pagination.paginate)) { + throw new Error('`options.pagination.paginate` must be implemented'); + } + } + // JSON mode + if (options.responseType === 'json' && options.headers.accept === undefined) { + options.headers.accept = 'application/json'; + } + return options; +}; +exports.default = normalizeArguments; diff --git a/setup-pandoc/node_modules/got/dist/source/as-promise/parse-body.d.ts b/setup-pandoc/node_modules/got/dist/source/as-promise/parse-body.d.ts new file mode 100644 index 000000000..39d0b41ac --- /dev/null +++ b/setup-pandoc/node_modules/got/dist/source/as-promise/parse-body.d.ts @@ -0,0 +1,3 @@ +import { ResponseType, Response, ParseJsonFunction } from './types'; +declare const parseBody: (response: Response, responseType: ResponseType, parseJson: ParseJsonFunction, encoding?: "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "base64url" | "latin1" | "binary" | "hex" | undefined) => unknown; +export default parseBody; diff --git a/setup-pandoc/node_modules/got/dist/source/as-promise/parse-body.js b/setup-pandoc/node_modules/got/dist/source/as-promise/parse-body.js new file mode 100644 index 000000000..cc2b8060f --- /dev/null +++ b/setup-pandoc/node_modules/got/dist/source/as-promise/parse-body.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const types_1 = require("./types"); +const parseBody = (response, responseType, parseJson, encoding) => { + const { rawBody } = response; + try { + if (responseType === 'text') { + return rawBody.toString(encoding); + } + if (responseType === 'json') { + return rawBody.length === 0 ? '' : parseJson(rawBody.toString()); + } + if (responseType === 'buffer') { + return rawBody; + } + throw new types_1.ParseError({ + message: `Unknown body type '${responseType}'`, + name: 'Error' + }, response); + } + catch (error) { + throw new types_1.ParseError(error, response); + } +}; +exports.default = parseBody; diff --git a/setup-pandoc/node_modules/got/dist/source/as-promise/types.d.ts b/setup-pandoc/node_modules/got/dist/source/as-promise/types.d.ts index 251fb8989..16bb4cbbf 100644 --- a/setup-pandoc/node_modules/got/dist/source/as-promise/types.d.ts +++ b/setup-pandoc/node_modules/got/dist/source/as-promise/types.d.ts @@ -1,38 +1,256 @@ -/// -import type { Buffer } from 'node:buffer'; -import type PCancelable from 'p-cancelable'; -import { RequestError } from '../core/errors.js'; -import type Request from '../core/index.js'; -import { type RequestEvents } from '../core/index.js'; -import type { Response } from '../core/response.js'; +/// +import PCancelable = require('p-cancelable'); +import Request, { Options, Response, RequestError, RequestEvents } from '../core'; +/** +All parsing methods supported by Got. +*/ +export declare type ResponseType = 'json' | 'buffer' | 'text'; +export interface PaginationOptions { + /** + All options accepted by `got.paginate()`. + */ + pagination?: { + /** + A function that transform [`Response`](#response) into an array of items. + This is where you should do the parsing. + + @default response => JSON.parse(response.body) + */ + transform?: (response: Response) => Promise | T[]; + /** + Checks whether the item should be emitted or not. + + @default (item, allItems, currentItems) => true + */ + filter?: (item: T, allItems: T[], currentItems: T[]) => boolean; + /** + The function takes three arguments: + - `response` - The current response object. + - `allItems` - An array of the emitted items. + - `currentItems` - Items from the current response. + + It should return an object representing Got options pointing to the next page. + The options are merged automatically with the previous request, therefore the options returned `pagination.paginate(...)` must reflect changes only. + If there are no more pages, `false` should be returned. + + @example + ``` + const got = require('got'); + + (async () => { + const limit = 10; + + const items = got.paginate('https://example.com/items', { + searchParams: { + limit, + offset: 0 + }, + pagination: { + paginate: (response, allItems, currentItems) => { + const previousSearchParams = response.request.options.searchParams; + const previousOffset = previousSearchParams.get('offset'); + + if (currentItems.length < limit) { + return false; + } + + return { + searchParams: { + ...previousSearchParams, + offset: Number(previousOffset) + limit, + } + }; + } + } + }); + + console.log('Items from all pages:', items); + })(); + ``` + */ + paginate?: (response: Response, allItems: T[], currentItems: T[]) => Options | false; + /** + Checks whether the pagination should continue. + + For example, if you need to stop **before** emitting an entry with some flag, you should use `(item, allItems, currentItems) => !item.flag`. + If you want to stop **after** emitting the entry, you should use `(item, allItems, currentItems) => allItems.some(entry => entry.flag)` instead. + + @default (item, allItems, currentItems) => true + */ + shouldContinue?: (item: T, allItems: T[], currentItems: T[]) => boolean; + /** + The maximum amount of items that should be emitted. + + @default Infinity + */ + countLimit?: number; + /** + Milliseconds to wait before the next request is triggered. + + @default 0 + */ + backoff?: number; + /** + The maximum amount of request that should be triggered. + Retries on failure are not counted towards this limit. + + For example, it can be helpful during development to avoid an infinite number of requests. + + @default 10000 + */ + requestLimit?: number; + /** + Defines how the parameter `allItems` in pagination.paginate, pagination.filter and pagination.shouldContinue is managed. + When set to `false`, the parameter `allItems` is always an empty array. + + This option can be helpful to save on memory usage when working with a large dataset. + */ + stackAllItems?: boolean; + }; +} +export declare type AfterResponseHook = (response: Response, retryWithMergedOptions: (options: Options) => CancelableRequest) => Response | CancelableRequest | Promise>; +export declare namespace PromiseOnly { + interface Hooks { + /** + Called with [response object](#response) and a retry function. + Calling the retry function will trigger `beforeRetry` hooks. + + Each function should return the response. + This is especially useful when you want to refresh an access token. + + __Note__: When using streams, this hook is ignored. + + @example + ``` + const got = require('got'); + + const instance = got.extend({ + hooks: { + afterResponse: [ + (response, retryWithMergedOptions) => { + if (response.statusCode === 401) { // Unauthorized + const updatedOptions = { + headers: { + token: getNewToken() // Refresh the access token + } + }; + + // Save for further requests + instance.defaults.options = got.mergeOptions(instance.defaults.options, updatedOptions); + + // Make a new retry + return retryWithMergedOptions(updatedOptions); + } + + // No changes otherwise + return response; + } + ], + beforeRetry: [ + (options, error, retryCount) => { + // This will be called on `retryWithMergedOptions(...)` + } + ] + }, + mutableDefaults: true + }); + ``` + */ + afterResponse?: AfterResponseHook[]; + } + interface Options extends PaginationOptions { + /** + The parsing method. + + The promise also has `.text()`, `.json()` and `.buffer()` methods which return another Got promise for the parsed body. + + It's like setting the options to `{responseType: 'json', resolveBodyOnly: true}` but without affecting the main Got promise. + + __Note__: When using streams, this option is ignored. + + @example + ``` + (async () => { + const responsePromise = got(url); + const bufferPromise = responsePromise.buffer(); + const jsonPromise = responsePromise.json(); + + const [response, buffer, json] = Promise.all([responsePromise, bufferPromise, jsonPromise]); + // `response` is an instance of Got Response + // `buffer` is an instance of Buffer + // `json` is an object + })(); + ``` + + @example + ``` + // This + const body = await got(url).json(); + + // is semantically the same as this + const body = await got(url, {responseType: 'json', resolveBodyOnly: true}); + ``` + */ + responseType?: ResponseType; + /** + When set to `true` the promise will return the Response body instead of the Response object. + + @default false + */ + resolveBodyOnly?: boolean; + /** + Returns a `Stream` instead of a `Promise`. + This is equivalent to calling `got.stream(url, options?)`. + + @default false + */ + isStream?: boolean; + /** + [Encoding](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings) to be used on `setEncoding` of the response data. + + To get a [`Buffer`](https://nodejs.org/api/buffer.html), you need to set `responseType` to `buffer` instead. + Don't set this option to `null`. + + __Note__: This doesn't affect streams! Instead, you need to do `got.stream(...).setEncoding(encoding)`. + + @default 'utf-8' + */ + encoding?: BufferEncoding; + } + interface NormalizedOptions { + responseType: ResponseType; + resolveBodyOnly: boolean; + isStream: boolean; + encoding?: BufferEncoding; + pagination?: Required['pagination']>; + } + interface Defaults { + responseType: ResponseType; + resolveBodyOnly: boolean; + isStream: boolean; + pagination?: Required['pagination']>; + } + type HookEvent = 'afterResponse'; +} +/** +An error to be thrown when server response code is 2xx, and parsing body fails. +Includes a `response` property. +*/ +export declare class ParseError extends RequestError { + readonly response: Response; + constructor(error: Error, response: Response); +} /** An error to be thrown when the request is aborted with `.cancel()`. */ export declare class CancelError extends RequestError { readonly response: Response; constructor(request: Request); - /** - Whether the promise is canceled. - */ get isCanceled(): boolean; } export interface CancelableRequest extends PCancelable, RequestEvents> { - /** - A shortcut method that gives a Promise returning a JSON object. - - It is semantically the same as settings `options.resolveBodyOnly` to `true` and `options.responseType` to `'json'`. - */ json: () => CancelableRequest; - /** - A shortcut method that gives a Promise returning a [Buffer](https://nodejs.org/api/buffer.html). - - It is semantically the same as settings `options.resolveBodyOnly` to `true` and `options.responseType` to `'buffer'`. - */ buffer: () => CancelableRequest; - /** - A shortcut method that gives a Promise returning a string. - - It is semantically the same as settings `options.resolveBodyOnly` to `true` and `options.responseType` to `'text'`. - */ text: () => CancelableRequest; } +export * from '../core'; diff --git a/setup-pandoc/node_modules/got/dist/source/as-promise/types.js b/setup-pandoc/node_modules/got/dist/source/as-promise/types.js index eda617e73..b73110a4a 100644 --- a/setup-pandoc/node_modules/got/dist/source/as-promise/types.js +++ b/setup-pandoc/node_modules/got/dist/source/as-promise/types.js @@ -1,17 +1,42 @@ -import { RequestError } from '../core/errors.js'; +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CancelError = exports.ParseError = void 0; +const core_1 = require("../core"); +/** +An error to be thrown when server response code is 2xx, and parsing body fails. +Includes a `response` property. +*/ +class ParseError extends core_1.RequestError { + constructor(error, response) { + const { options } = response.request; + super(`${error.message} in "${options.url.toString()}"`, error, response.request); + this.name = 'ParseError'; + this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_BODY_PARSE_FAILURE' : this.code; + } +} +exports.ParseError = ParseError; /** An error to be thrown when the request is aborted with `.cancel()`. */ -export class CancelError extends RequestError { +class CancelError extends core_1.RequestError { constructor(request) { super('Promise was canceled', {}, request); this.name = 'CancelError'; this.code = 'ERR_CANCELED'; } - /** - Whether the promise is canceled. - */ get isCanceled() { return true; } } +exports.CancelError = CancelError; +__exportStar(require("../core"), exports); diff --git a/setup-pandoc/node_modules/got/dist/source/core/calculate-retry-delay.d.ts b/setup-pandoc/node_modules/got/dist/source/core/calculate-retry-delay.d.ts index c38ae4d15..86eca8f90 100644 --- a/setup-pandoc/node_modules/got/dist/source/core/calculate-retry-delay.d.ts +++ b/setup-pandoc/node_modules/got/dist/source/core/calculate-retry-delay.d.ts @@ -1,4 +1,5 @@ -import type { RetryFunction } from './options.js'; -type Returns unknown, V> = (...args: Parameters) => V; +import { RetryFunction } from '.'; +declare type Returns unknown, V> = (...args: Parameters) => V; +export declare const retryAfterStatusCodes: ReadonlySet; declare const calculateRetryDelay: Returns; export default calculateRetryDelay; diff --git a/setup-pandoc/node_modules/got/dist/source/core/calculate-retry-delay.js b/setup-pandoc/node_modules/got/dist/source/core/calculate-retry-delay.js index 5407da809..99f604aba 100644 --- a/setup-pandoc/node_modules/got/dist/source/core/calculate-retry-delay.js +++ b/setup-pandoc/node_modules/got/dist/source/core/calculate-retry-delay.js @@ -1,7 +1,8 @@ -const calculateRetryDelay = ({ attemptCount, retryOptions, error, retryAfter, computedValue, }) => { - if (error.name === 'RetryError') { - return 1; - } +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.retryAfterStatusCodes = void 0; +exports.retryAfterStatusCodes = new Set([413, 429, 503]); +const calculateRetryDelay = ({ attemptCount, retryOptions, error, retryAfter }) => { if (attemptCount > retryOptions.limit) { return 0; } @@ -13,8 +14,7 @@ const calculateRetryDelay = ({ attemptCount, retryOptions, error, retryAfter, co } if (error.response) { if (retryAfter) { - // In this case `computedValue` is `options.request.timeout` - if (retryAfter > computedValue) { + if (retryOptions.maxRetryAfter === undefined || retryAfter > retryOptions.maxRetryAfter) { return 0; } return retryAfter; @@ -23,7 +23,7 @@ const calculateRetryDelay = ({ attemptCount, retryOptions, error, retryAfter, co return 0; } } - const noise = Math.random() * retryOptions.noise; - return Math.min(((2 ** (attemptCount - 1)) * 1000), retryOptions.backoffLimit) + noise; + const noise = Math.random() * 100; + return ((2 ** (attemptCount - 1)) * 1000) + noise; }; -export default calculateRetryDelay; +exports.default = calculateRetryDelay; diff --git a/setup-pandoc/node_modules/got/dist/source/core/errors.d.ts b/setup-pandoc/node_modules/got/dist/source/core/errors.d.ts deleted file mode 100644 index 1f4268b63..000000000 --- a/setup-pandoc/node_modules/got/dist/source/core/errors.d.ts +++ /dev/null @@ -1,90 +0,0 @@ -/// -import type { Timings } from '@szmarczak/http-timer'; -import type Options from './options.js'; -import type { TimeoutError as TimedOutTimeoutError } from './timed-out.js'; -import type { PlainResponse, Response } from './response.js'; -import type Request from './index.js'; -type Error = NodeJS.ErrnoException; -/** -An error to be thrown when a request fails. -Contains a `code` property with error class code, like `ECONNREFUSED`. -*/ -export declare class RequestError extends Error { - input?: string; - code: string; - stack: string; - readonly options: Options; - readonly response?: Response; - readonly request?: Request; - readonly timings?: Timings; - constructor(message: string, error: Partial, self: Request | Options); -} -/** -An error to be thrown when the server redirects you more than ten times. -Includes a `response` property. -*/ -export declare class MaxRedirectsError extends RequestError { - readonly response: Response; - readonly request: Request; - readonly timings: Timings; - constructor(request: Request); -} -/** -An error to be thrown when the server response code is not 2xx nor 3xx if `options.followRedirect` is `true`, but always except for 304. -Includes a `response` property. -*/ -export declare class HTTPError extends RequestError { - readonly response: Response; - readonly request: Request; - readonly timings: Timings; - constructor(response: PlainResponse); -} -/** -An error to be thrown when a cache method fails. -For example, if the database goes down or there's a filesystem error. -*/ -export declare class CacheError extends RequestError { - readonly request: Request; - constructor(error: Error, request: Request); -} -/** -An error to be thrown when the request body is a stream and an error occurs while reading from that stream. -*/ -export declare class UploadError extends RequestError { - readonly request: Request; - constructor(error: Error, request: Request); -} -/** -An error to be thrown when the request is aborted due to a timeout. -Includes an `event` and `timings` property. -*/ -export declare class TimeoutError extends RequestError { - readonly request: Request; - readonly timings: Timings; - readonly event: string; - constructor(error: TimedOutTimeoutError, timings: Timings, request: Request); -} -/** -An error to be thrown when reading from response stream fails. -*/ -export declare class ReadError extends RequestError { - readonly request: Request; - readonly response: Response; - readonly timings: Timings; - constructor(error: Error, request: Request); -} -/** -An error which always triggers a new retry when thrown. -*/ -export declare class RetryError extends RequestError { - constructor(request: Request); -} -/** -An error to be thrown when the request is aborted by AbortController. -*/ -export declare class AbortError extends RequestError { - constructor(request: Request); -} -export {}; diff --git a/setup-pandoc/node_modules/got/dist/source/core/errors.js b/setup-pandoc/node_modules/got/dist/source/core/errors.js deleted file mode 100644 index 353890e36..000000000 --- a/setup-pandoc/node_modules/got/dist/source/core/errors.js +++ /dev/null @@ -1,139 +0,0 @@ -import is from '@sindresorhus/is'; -// A hacky check to prevent circular references. -function isRequest(x) { - return is.object(x) && '_onResponse' in x; -} -/** -An error to be thrown when a request fails. -Contains a `code` property with error class code, like `ECONNREFUSED`. -*/ -export class RequestError extends Error { - input; - code; - stack; - response; - request; - timings; - constructor(message, error, self) { - super(message, { cause: error }); - Error.captureStackTrace(this, this.constructor); - this.name = 'RequestError'; - this.code = error.code ?? 'ERR_GOT_REQUEST_ERROR'; - this.input = error.input; - if (isRequest(self)) { - Object.defineProperty(this, 'request', { - enumerable: false, - value: self, - }); - Object.defineProperty(this, 'response', { - enumerable: false, - value: self.response, - }); - this.options = self.options; - } - else { - this.options = self; - } - this.timings = this.request?.timings; - // Recover the original stacktrace - if (is.string(error.stack) && is.string(this.stack)) { - const indexOfMessage = this.stack.indexOf(this.message) + this.message.length; - const thisStackTrace = this.stack.slice(indexOfMessage).split('\n').reverse(); - const errorStackTrace = error.stack.slice(error.stack.indexOf(error.message) + error.message.length).split('\n').reverse(); - // Remove duplicated traces - while (errorStackTrace.length > 0 && errorStackTrace[0] === thisStackTrace[0]) { - thisStackTrace.shift(); - } - this.stack = `${this.stack.slice(0, indexOfMessage)}${thisStackTrace.reverse().join('\n')}${errorStackTrace.reverse().join('\n')}`; - } - } -} -/** -An error to be thrown when the server redirects you more than ten times. -Includes a `response` property. -*/ -export class MaxRedirectsError extends RequestError { - constructor(request) { - super(`Redirected ${request.options.maxRedirects} times. Aborting.`, {}, request); - this.name = 'MaxRedirectsError'; - this.code = 'ERR_TOO_MANY_REDIRECTS'; - } -} -/** -An error to be thrown when the server response code is not 2xx nor 3xx if `options.followRedirect` is `true`, but always except for 304. -Includes a `response` property. -*/ -// TODO: Change `HTTPError` to `HTTPError` in the next major version to enforce type usage. -// eslint-disable-next-line @typescript-eslint/naming-convention -export class HTTPError extends RequestError { - constructor(response) { - super(`Response code ${response.statusCode} (${response.statusMessage})`, {}, response.request); - this.name = 'HTTPError'; - this.code = 'ERR_NON_2XX_3XX_RESPONSE'; - } -} -/** -An error to be thrown when a cache method fails. -For example, if the database goes down or there's a filesystem error. -*/ -export class CacheError extends RequestError { - constructor(error, request) { - super(error.message, error, request); - this.name = 'CacheError'; - this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_CACHE_ACCESS' : this.code; - } -} -/** -An error to be thrown when the request body is a stream and an error occurs while reading from that stream. -*/ -export class UploadError extends RequestError { - constructor(error, request) { - super(error.message, error, request); - this.name = 'UploadError'; - this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_UPLOAD' : this.code; - } -} -/** -An error to be thrown when the request is aborted due to a timeout. -Includes an `event` and `timings` property. -*/ -export class TimeoutError extends RequestError { - timings; - event; - constructor(error, timings, request) { - super(error.message, error, request); - this.name = 'TimeoutError'; - this.event = error.event; - this.timings = timings; - } -} -/** -An error to be thrown when reading from response stream fails. -*/ -export class ReadError extends RequestError { - constructor(error, request) { - super(error.message, error, request); - this.name = 'ReadError'; - this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_READING_RESPONSE_STREAM' : this.code; - } -} -/** -An error which always triggers a new retry when thrown. -*/ -export class RetryError extends RequestError { - constructor(request) { - super('Retrying', {}, request); - this.name = 'RetryError'; - this.code = 'ERR_RETRYING'; - } -} -/** -An error to be thrown when the request is aborted by AbortController. -*/ -export class AbortError extends RequestError { - constructor(request) { - super('This operation was aborted.', {}, request); - this.code = 'ERR_ABORTED'; - this.name = 'AbortError'; - } -} diff --git a/setup-pandoc/node_modules/got/dist/source/core/index.d.ts b/setup-pandoc/node_modules/got/dist/source/core/index.d.ts index 38a81bafc..803806e54 100644 --- a/setup-pandoc/node_modules/got/dist/source/core/index.d.ts +++ b/setup-pandoc/node_modules/got/dist/source/core/index.d.ts @@ -1,141 +1,1072 @@ -/// -/// -/// -/// -/// -import { Duplex } from 'node:stream'; -import { type ClientRequest } from 'node:http'; -import type { Socket } from 'node:net'; -import { type Timings } from '@szmarczak/http-timer'; -import Options from './options.js'; -import { type PlainResponse, type Response } from './response.js'; -import { RequestError } from './errors.js'; -type Error = NodeJS.ErrnoException; -export type Progress = { - percent: number; - transferred: number; - total?: number; -}; -export type GotEventFunction = +/// +import { Duplex, Readable } from 'stream'; +import { URL, URLSearchParams } from 'url'; +import { Socket } from 'net'; +import { SecureContextOptions, DetailedPeerCertificate } from 'tls'; +import http = require('http'); +import { ClientRequest, RequestOptions, ServerResponse, request as httpRequest } from 'http'; +import https = require('https'); +import { Timings, IncomingMessageWithTimings } from '@szmarczak/http-timer'; +import CacheableLookup from 'cacheable-lookup'; +import CacheableRequest = require('cacheable-request'); +import ResponseLike = require('responselike'); +import { Delays, TimeoutError as TimedOutTimeoutError } from './utils/timed-out'; +import { URLOptions } from './utils/options-to-url'; +import { DnsLookupIpVersion } from './utils/dns-ip-version'; +import { PromiseOnly } from '../as-promise/types'; +declare type HttpRequestFunction = typeof httpRequest; +declare type Error = NodeJS.ErrnoException; +declare const kRequest: unique symbol; +declare const kResponse: unique symbol; +declare const kResponseSize: unique symbol; +declare const kDownloadedSize: unique symbol; +declare const kBodySize: unique symbol; +declare const kUploadedSize: unique symbol; +declare const kServerResponsesPiped: unique symbol; +declare const kUnproxyEvents: unique symbol; +declare const kIsFromCache: unique symbol; +declare const kCancelTimeouts: unique symbol; +declare const kStartedReading: unique symbol; +declare const kStopReading: unique symbol; +declare const kTriggerRead: unique symbol; +declare const kBody: unique symbol; +declare const kJobs: unique symbol; +declare const kOriginalResponse: unique symbol; +declare const kRetryTimeout: unique symbol; +export declare const kIsNormalizedAlready: unique symbol; +export interface Agents { + http?: http.Agent; + https?: https.Agent; + http2?: unknown; +} +export declare const withoutBody: ReadonlySet; +export interface ToughCookieJar { + getCookieString: ((currentUrl: string, options: Record, cb: (err: Error | null, cookies: string) => void) => void) & ((url: string, callback: (error: Error | null, cookieHeader: string) => void) => void); + setCookie: ((cookieOrString: unknown, currentUrl: string, options: Record, cb: (err: Error | null, cookie: unknown) => void) => void) & ((rawCookie: string, url: string, callback: (error: Error | null, result: unknown) => void) => void); +} +export interface PromiseCookieJar { + getCookieString: (url: string) => Promise; + setCookie: (rawCookie: string, url: string) => Promise; +} /** -`request` event to get the request object of the request. +All available HTTP request methods provided by Got. +*/ +export declare type Method = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'HEAD' | 'DELETE' | 'OPTIONS' | 'TRACE' | 'get' | 'post' | 'put' | 'patch' | 'head' | 'delete' | 'options' | 'trace'; +declare type Promisable = T | Promise; +export declare type InitHook = (options: Options) => void; +export declare type BeforeRequestHook = (options: NormalizedOptions) => Promisable; +export declare type BeforeRedirectHook = (options: NormalizedOptions, response: Response) => Promisable; +export declare type BeforeErrorHook = (error: RequestError) => Promisable; +export declare type BeforeRetryHook = (options: NormalizedOptions, error?: RequestError, retryCount?: number) => void | Promise; +interface PlainHooks { + /** + Called with plain request options, right before their normalization. + This is especially useful in conjunction with `got.extend()` when the input needs custom handling. - __Tip__: You can use `request` event to abort requests. + __Note #1__: This hook must be synchronous! -@example -``` -import got from 'got'; + __Note #2__: Errors in this hook will be converted into an instances of `RequestError`. -got.stream('https://github.com') - .on('request', request => setTimeout(() => request.destroy(), 50)); -``` -*/ -((name: 'request', listener: (request: ClientRequest) => void) => T) + __Note #3__: The options object may not have a `url` property. + To modify it, use a `beforeRequest` hook instead. + + @default [] + */ + init?: InitHook[]; + /** + Called with normalized request options. + Got will make no further changes to the request before it is sent. + This is especially useful in conjunction with `got.extend()` when you want to create an API client that, for example, uses HMAC-signing. + + @default [] + */ + beforeRequest?: BeforeRequestHook[]; + /** + Called with normalized request options and the redirect response. + Got will make no further changes to the request. + This is especially useful when you want to avoid dead sites. + + @default [] + + @example + ``` + const got = require('got'); + + got('https://example.com', { + hooks: { + beforeRedirect: [ + (options, response) => { + if (options.hostname === 'deadSite') { + options.hostname = 'fallbackSite'; + } + } + ] + } + }); + ``` + */ + beforeRedirect?: BeforeRedirectHook[]; + /** + Called with an `Error` instance. + The error is passed to the hook right before it's thrown. + This is especially useful when you want to have more detailed errors. + + __Note__: Errors thrown while normalizing input options are thrown directly and not part of this hook. + + @default [] + + @example + ``` + const got = require('got'); + + got('https://api.github.com/some-endpoint', { + hooks: { + beforeError: [ + error => { + const {response} = error; + if (response && response.body) { + error.name = 'GitHubError'; + error.message = `${response.body.message} (${response.statusCode})`; + } + + return error; + } + ] + } + }); + ``` + */ + beforeError?: BeforeErrorHook[]; + /** + Called with normalized request options, the error and the retry count. + Got will make no further changes to the request. + This is especially useful when some extra work is required before the next try. + + __Note__: When using streams, this hook is ignored. + __Note__: When retrying in a `afterResponse` hook, all remaining `beforeRetry` hooks will be called without the `error` and `retryCount` arguments. + + @default [] + + @example + ``` + const got = require('got'); + + got.post('https://example.com', { + hooks: { + beforeRetry: [ + (options, error, retryCount) => { + if (error.response.statusCode === 413) { // Payload too large + options.body = getNewBody(); + } + } + ] + } + }); + ``` + */ + beforeRetry?: BeforeRetryHook[]; +} /** -The `response` event to get the response object of the final request. +All available hook of Got. */ - & ((name: 'response', listener: (response: R) => void) => T) +export interface Hooks extends PromiseOnly.Hooks, PlainHooks { +} +declare type PlainHookEvent = 'init' | 'beforeRequest' | 'beforeRedirect' | 'beforeError' | 'beforeRetry'; /** -The `redirect` event to get the response object of a redirect. The second argument is options for the next request to the redirect location. +All hook events acceptable by Got. */ - & ((name: 'redirect', listener: (response: R, nextOptions: N) => void) => T) +export declare type HookEvent = PromiseOnly.HookEvent | PlainHookEvent; +export declare const knownHookEvents: HookEvent[]; +declare type AcceptableResponse = IncomingMessageWithTimings | ResponseLike; +declare type AcceptableRequestResult = AcceptableResponse | ClientRequest | Promise | undefined; +export declare type RequestFunction = (url: URL, options: RequestOptions, callback?: (response: AcceptableResponse) => void) => AcceptableRequestResult; +export declare type Headers = Record; +declare type CheckServerIdentityFunction = (hostname: string, certificate: DetailedPeerCertificate) => Error | void; +export declare type ParseJsonFunction = (text: string) => unknown; +export declare type StringifyJsonFunction = (object: unknown) => string; +export interface RetryObject { + attemptCount: number; + retryOptions: RequiredRetryOptions; + error: TimeoutError | RequestError; + computedValue: number; + retryAfter?: number; +} +export declare type RetryFunction = (retryObject: RetryObject) => number | Promise; /** -Progress events for uploading (sending a request) and downloading (receiving a response). -The `progress` argument is an object like: +An object representing `limit`, `calculateDelay`, `methods`, `statusCodes`, `maxRetryAfter` and `errorCodes` fields for maximum retry count, retry handler, allowed methods, allowed status codes, maximum [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time and allowed error codes. + +Delays between retries counts with function `1000 * Math.pow(2, retry) + Math.random() * 100`, where `retry` is attempt number (starts from 1). + +The `calculateDelay` property is a `function` that receives an object with `attemptCount`, `retryOptions`, `error` and `computedValue` properties for current retry count, the retry options, error and default computed value. +The function must return a delay in milliseconds (or a Promise resolving with it) (`0` return value cancels retry). + +By default, it retries *only* on the specified methods, status codes, and on these network errors: +- `ETIMEDOUT`: One of the [timeout](#timeout) limits were reached. +- `ECONNRESET`: Connection was forcibly closed by a peer. +- `EADDRINUSE`: Could not bind to any free port. +- `ECONNREFUSED`: Connection was refused by the server. +- `EPIPE`: The remote side of the stream being written has been closed. +- `ENOTFOUND`: Couldn't resolve the hostname to an IP address. +- `ENETUNREACH`: No internet connection. +- `EAI_AGAIN`: DNS lookup timed out. -``` -{ - percent: 0.1, - transferred: 1024, - total: 10240 +__Note__: If `maxRetryAfter` is set to `undefined`, it will use `options.timeout`. +__Note__: If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will cancel the request. +*/ +export interface RequiredRetryOptions { + limit: number; + methods: Method[]; + statusCodes: number[]; + errorCodes: string[]; + calculateDelay: RetryFunction; + maxRetryAfter?: number; +} +export interface CacheOptions { + shared?: boolean; + cacheHeuristic?: number; + immutableMinTimeToLive?: number; + ignoreCargoCult?: boolean; } -``` +interface PlainOptions extends URLOptions { + /** + Custom request function. + The main purpose of this is to [support HTTP2 using a wrapper](https://github.com/szmarczak/http2-wrapper). + + @default http.request | https.request + */ + request?: RequestFunction; + /** + An object representing `http`, `https` and `http2` keys for [`http.Agent`](https://nodejs.org/api/http.html#http_class_http_agent), [`https.Agent`](https://nodejs.org/api/https.html#https_class_https_agent) and [`http2wrapper.Agent`](https://github.com/szmarczak/http2-wrapper#new-http2agentoptions) instance. + This is necessary because a request to one protocol might redirect to another. + In such a scenario, Got will switch over to the right protocol agent for you. -If the `content-length` header is missing, `total` will be `undefined`. + If a key is not present, it will default to a global agent. -@example -``` -import got from 'got'; + @example + ``` + const got = require('got'); + const HttpAgent = require('agentkeepalive'); + const {HttpsAgent} = HttpAgent; -const response = await got('https://sindresorhus.com') - .on('downloadProgress', progress => { - // Report download progress - }) - .on('uploadProgress', progress => { - // Report upload progress + got('https://sindresorhus.com', { + agent: { + http: new HttpAgent(), + https: new HttpsAgent() + } }); + ``` + */ + agent?: Agents | false; + /** + Decompress the response automatically. + This will set the `accept-encoding` header to `gzip, deflate, br` on Node.js 11.7.0+ or `gzip, deflate` for older Node.js versions, unless you set it yourself. -console.log(response); -``` -*/ - & ((name: 'uploadProgress' | 'downloadProgress', listener: (progress: Progress) => void) => T) -/** -To enable retrying on a Got stream, it is required to have a `retry` handler attached. + Brotli (`br`) support requires Node.js 11.7.0 or later. + + If this is disabled, a compressed response is returned as a `Buffer`. + This may be useful if you want to handle decompression yourself or stream the raw compressed data. + + @default true + */ + decompress?: boolean; + /** + Milliseconds to wait for the server to end the response before aborting the request with `got.TimeoutError` error (a.k.a. `request` property). + By default, there's no timeout. + + This also accepts an `object` with the following fields to constrain the duration of each phase of the request lifecycle: + + - `lookup` starts when a socket is assigned and ends when the hostname has been resolved. + Does not apply when using a Unix domain socket. + - `connect` starts when `lookup` completes (or when the socket is assigned if lookup does not apply to the request) and ends when the socket is connected. + - `secureConnect` starts when `connect` completes and ends when the handshaking process completes (HTTPS only). + - `socket` starts when the socket is connected. See [request.setTimeout](https://nodejs.org/api/http.html#http_request_settimeout_timeout_callback). + - `response` starts when the request has been written to the socket and ends when the response headers are received. + - `send` starts when the socket is connected and ends with the request has been written to the socket. + - `request` starts when the request is initiated and ends when the response's end event fires. + */ + timeout?: Delays | number; + /** + When specified, `prefixUrl` will be prepended to `url`. + The prefix can be any valid URL, either relative or absolute. + A trailing slash `/` is optional - one will be added automatically. + + __Note__: `prefixUrl` will be ignored if the `url` argument is a URL instance. + + __Note__: Leading slashes in `input` are disallowed when using this option to enforce consistency and avoid confusion. + For example, when the prefix URL is `https://example.com/foo` and the input is `/bar`, there's ambiguity whether the resulting URL would become `https://example.com/foo/bar` or `https://example.com/bar`. + The latter is used by browsers. + + __Tip__: Useful when used with `got.extend()` to create niche-specific Got instances. + + __Tip__: You can change `prefixUrl` using hooks as long as the URL still includes the `prefixUrl`. + If the URL doesn't include it anymore, it will throw. + + @example + ``` + const got = require('got'); + + (async () => { + await got('unicorn', {prefixUrl: 'https://cats.com'}); + //=> 'https://cats.com/unicorn' + + const instance = got.extend({ + prefixUrl: 'https://google.com' + }); + + await instance('unicorn', { + hooks: { + beforeRequest: [ + options => { + options.prefixUrl = 'https://cats.com'; + } + ] + } + }); + //=> 'https://cats.com/unicorn' + })(); + ``` + */ + prefixUrl?: string | URL; + /** + __Note #1__: The `body` option cannot be used with the `json` or `form` option. + + __Note #2__: If you provide this option, `got.stream()` will be read-only. + + __Note #3__: If you provide a payload with the `GET` or `HEAD` method, it will throw a `TypeError` unless the method is `GET` and the `allowGetBody` option is set to `true`. + + __Note #4__: This option is not enumerable and will not be merged with the instance defaults. + + The `content-length` header will be automatically set if `body` is a `string` / `Buffer` / `fs.createReadStream` instance / [`form-data` instance](https://github.com/form-data/form-data), and `content-length` and `transfer-encoding` are not manually set in `options.headers`. + */ + body?: string | Buffer | Readable; + /** + The form body is converted to a query string using [`(new URLSearchParams(object)).toString()`](https://nodejs.org/api/url.html#url_constructor_new_urlsearchparams_obj). + + If the `Content-Type` header is not present, it will be set to `application/x-www-form-urlencoded`. + + __Note #1__: If you provide this option, `got.stream()` will be read-only. + + __Note #2__: This option is not enumerable and will not be merged with the instance defaults. + */ + form?: Record; + /** + JSON body. If the `Content-Type` header is not set, it will be set to `application/json`. + + __Note #1__: If you provide this option, `got.stream()` will be read-only. + + __Note #2__: This option is not enumerable and will not be merged with the instance defaults. + */ + json?: Record; + /** + The URL to request, as a string, a [`https.request` options object](https://nodejs.org/api/https.html#https_https_request_options_callback), or a [WHATWG `URL`](https://nodejs.org/api/url.html#url_class_url). + + Properties from `options` will override properties in the parsed `url`. + + If no protocol is specified, it will throw a `TypeError`. + + __Note__: The query string is **not** parsed as search params. + + @example + ``` + got('https://example.com/?query=a b'); //=> https://example.com/?query=a%20b + got('https://example.com/', {searchParams: {query: 'a b'}}); //=> https://example.com/?query=a+b + + // The query string is overridden by `searchParams` + got('https://example.com/?query=a b', {searchParams: {query: 'a b'}}); //=> https://example.com/?query=a+b + ``` + */ + url?: string | URL; + /** + Cookie support. You don't have to care about parsing or how to store them. + + __Note__: If you provide this option, `options.headers.cookie` will be overridden. + */ + cookieJar?: PromiseCookieJar | ToughCookieJar; + /** + Ignore invalid cookies instead of throwing an error. + Only useful when the `cookieJar` option has been set. Not recommended. + + @default false + */ + ignoreInvalidCookies?: boolean; + /** + Query string that will be added to the request URL. + This will override the query string in `url`. + + If you need to pass in an array, you can do it using a `URLSearchParams` instance. + + @example + ``` + const got = require('got'); + + const searchParams = new URLSearchParams([['key', 'a'], ['key', 'b']]); + + got('https://example.com', {searchParams}); + + console.log(searchParams.toString()); + //=> 'key=a&key=b' + ``` + */ + searchParams?: string | Record | URLSearchParams; + /** + An instance of [`CacheableLookup`](https://github.com/szmarczak/cacheable-lookup) used for making DNS lookups. + Useful when making lots of requests to different *public* hostnames. + + `CacheableLookup` uses `dns.resolver4(..)` and `dns.resolver6(...)` under the hood and fall backs to `dns.lookup(...)` when the first two fail, which may lead to additional delay. + + __Note__: This should stay disabled when making requests to internal hostnames such as `localhost`, `database.local` etc. + + @default false + */ + dnsCache?: CacheableLookup | boolean; + /** + User data. In contrast to other options, `context` is not enumerable. + + __Note__: The object is never merged, it's just passed through. + Got will not modify the object in any way. + + @example + ``` + const got = require('got'); + + const instance = got.extend({ + hooks: { + beforeRequest: [ + options => { + if (!options.context || !options.context.token) { + throw new Error('Token required'); + } + + options.headers.token = options.context.token; + } + ] + } + }); + + (async () => { + const context = { + token: 'secret' + }; + + const response = await instance('https://httpbin.org/headers', {context}); + + // Let's see the headers + console.log(response.body); + })(); + ``` + */ + context?: Record; + /** + Hooks allow modifications during the request lifecycle. + Hook functions may be async and are run serially. + */ + hooks?: Hooks; + /** + Defines if redirect responses should be followed automatically. + + Note that if a `303` is sent by the server in response to any request type (`POST`, `DELETE`, etc.), Got will automatically request the resource pointed to in the location header via `GET`. + This is in accordance with [the spec](https://tools.ietf.org/html/rfc7231#section-6.4.4). + + @default true + */ + followRedirect?: boolean; + /** + If exceeded, the request will be aborted and a `MaxRedirectsError` will be thrown. + + @default 10 + */ + maxRedirects?: number; + /** + A cache adapter instance for storing cached response data. + + @default false + */ + cache?: string | CacheableRequest.StorageAdapter | false; + /** + Determines if a `got.HTTPError` is thrown for unsuccessful responses. + + If this is disabled, requests that encounter an error status code will be resolved with the `response` instead of throwing. + This may be useful if you are checking for resource availability and are expecting error responses. + + @default true + */ + throwHttpErrors?: boolean; + username?: string; + password?: string; + /** + If set to `true`, Got will additionally accept HTTP2 requests. + + It will choose either HTTP/1.1 or HTTP/2 depending on the ALPN protocol. + + __Note__: Overriding `options.request` will disable HTTP2 support. + + __Note__: This option will default to `true` in the next upcoming major release. + + @default false + + @example + ``` + const got = require('got'); + + (async () => { + const {headers} = await got('https://nghttp2.org/httpbin/anything', {http2: true}); + console.log(headers.via); + //=> '2 nghttpx' + })(); + ``` + */ + http2?: boolean; + /** + Set this to `true` to allow sending body for the `GET` method. + However, the [HTTP/2 specification](https://tools.ietf.org/html/rfc7540#section-8.1.3) says that `An HTTP GET request includes request header fields and no payload body`, therefore when using the HTTP/2 protocol this option will have no effect. + This option is only meant to interact with non-compliant servers when you have no other choice. + + __Note__: The [RFC 7321](https://tools.ietf.org/html/rfc7231#section-4.3.1) doesn't specify any particular behavior for the GET method having a payload, therefore __it's considered an [anti-pattern](https://en.wikipedia.org/wiki/Anti-pattern)__. + + @default false + */ + allowGetBody?: boolean; + lookup?: CacheableLookup['lookup']; + /** + Request headers. + + Existing headers will be overwritten. Headers set to `undefined` will be omitted. + + @default {} + */ + headers?: Headers; + /** + By default, redirects will use [method rewriting](https://tools.ietf.org/html/rfc7231#section-6.4). + For example, when sending a POST request and receiving a `302`, it will resend the body to the new location using the same HTTP method (`POST` in this case). + + @default true + */ + methodRewriting?: boolean; + /** + Indicates which DNS record family to use. + + Values: + - `auto`: IPv4 (if present) or IPv6 + - `ipv4`: Only IPv4 + - `ipv6`: Only IPv6 + + __Note__: If you are using the undocumented option `family`, `dnsLookupIpVersion` will override it. + + @default 'auto' + */ + dnsLookupIpVersion?: DnsLookupIpVersion; + /** + A function used to parse JSON responses. + + @example + ``` + const got = require('got'); + const Bourne = require('@hapi/bourne'); + + (async () => { + const parsed = await got('https://example.com', { + parseJson: text => Bourne.parse(text) + }).json(); + + console.log(parsed); + })(); + ``` + */ + parseJson?: ParseJsonFunction; + /** + A function used to stringify the body of JSON requests. -When this event is emitted, you should reset the stream you were writing to and prepare the body again. + @example + ``` + const got = require('got'); -See `got.options.retry` for more information. + (async () => { + await got.post('https://example.com', { + stringifyJson: object => JSON.stringify(object, (key, value) => { + if (key.startsWith('_')) { + return; + } + + return value; + }), + json: { + some: 'payload', + _ignoreMe: 1234 + } + }); + })(); + ``` + + @example + ``` + const got = require('got'); + + (async () => { + await got.post('https://example.com', { + stringifyJson: object => JSON.stringify(object, (key, value) => { + if (typeof value === 'number') { + return value.toString(); + } + + return value; + }), + json: { + some: 'payload', + number: 1 + } + }); + })(); + ``` + */ + stringifyJson?: StringifyJsonFunction; + /** + An object representing `limit`, `calculateDelay`, `methods`, `statusCodes`, `maxRetryAfter` and `errorCodes` fields for maximum retry count, retry handler, allowed methods, allowed status codes, maximum [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time and allowed error codes. + + Delays between retries counts with function `1000 * Math.pow(2, retry) + Math.random() * 100`, where `retry` is attempt number (starts from 1). + + The `calculateDelay` property is a `function` that receives an object with `attemptCount`, `retryOptions`, `error` and `computedValue` properties for current retry count, the retry options, error and default computed value. + The function must return a delay in milliseconds (or a Promise resolving with it) (`0` return value cancels retry). + + By default, it retries *only* on the specified methods, status codes, and on these network errors: + + - `ETIMEDOUT`: One of the [timeout](#timeout) limits were reached. + - `ECONNRESET`: Connection was forcibly closed by a peer. + - `EADDRINUSE`: Could not bind to any free port. + - `ECONNREFUSED`: Connection was refused by the server. + - `EPIPE`: The remote side of the stream being written has been closed. + - `ENOTFOUND`: Couldn't resolve the hostname to an IP address. + - `ENETUNREACH`: No internet connection. + - `EAI_AGAIN`: DNS lookup timed out. + + __Note__: If `maxRetryAfter` is set to `undefined`, it will use `options.timeout`. + __Note__: If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will cancel the request. + */ + retry?: Partial | number; + /** + The IP address used to send the request from. + */ + localAddress?: string; + socketPath?: string; + /** + The HTTP method used to make the request. + + @default 'GET' + */ + method?: Method; + createConnection?: (options: http.RequestOptions, oncreate: (error: Error, socket: Socket) => void) => Socket; + cacheOptions?: CacheOptions; + /** + If set to `false`, all invalid SSL certificates will be ignored and no error will be thrown. + + If set to `true`, it will throw an error whenever an invalid SSL certificate is detected. + + We strongly recommend to have this set to `true` for security reasons. + + @default true + + @example + ``` + const got = require('got'); + + (async () => { + // Correct: + await got('https://example.com', {rejectUnauthorized: true}); + + // You can disable it when developing an HTTPS app: + await got('https://localhost', {rejectUnauthorized: false}); + + // Never do this: + await got('https://example.com', {rejectUnauthorized: false}); + })(); + ``` + */ + rejectUnauthorized?: boolean; + /** + Options for the advanced HTTPS API. + */ + https?: HTTPSOptions; +} +export interface Options extends PromiseOnly.Options, PlainOptions { +} +export interface HTTPSOptions { + rejectUnauthorized?: https.RequestOptions['rejectUnauthorized']; + checkServerIdentity?: CheckServerIdentityFunction; + /** + Override the default Certificate Authorities ([from Mozilla](https://ccadb-public.secure.force.com/mozilla/IncludedCACertificateReport)). + + @example + ``` + // Single Certificate Authority + got('https://example.com', { + https: { + certificateAuthority: fs.readFileSync('./my_ca.pem') + } + }); + ``` + */ + certificateAuthority?: SecureContextOptions['ca']; + /** + Private keys in [PEM](https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail) format. + + [PEM](https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail) allows the option of private keys being encrypted. + Encrypted keys will be decrypted with `options.https.passphrase`. + + Multiple keys with different passphrases can be provided as an array of `{pem: , passphrase: }` + */ + key?: SecureContextOptions['key']; + /** + [Certificate chains](https://en.wikipedia.org/wiki/X.509#Certificate_chains_and_cross-certification) in [PEM](https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail) format. + + One cert chain should be provided per private key (`options.https.key`). + + When providing multiple cert chains, they do not have to be in the same order as their private keys in `options.https.key`. + + If the intermediate certificates are not provided, the peer will not be able to validate the certificate, and the handshake will fail. + */ + certificate?: SecureContextOptions['cert']; + /** + The passphrase to decrypt the `options.https.key` (if different keys have different passphrases refer to `options.https.key` documentation). + */ + passphrase?: SecureContextOptions['passphrase']; + pfx?: SecureContextOptions['pfx']; +} +interface NormalizedPlainOptions extends PlainOptions { + method: Method; + url: URL; + timeout: Delays; + prefixUrl: string; + ignoreInvalidCookies: boolean; + decompress: boolean; + searchParams?: URLSearchParams; + cookieJar?: PromiseCookieJar; + headers: Headers; + context: Record; + hooks: Required; + followRedirect: boolean; + maxRedirects: number; + cache?: string | CacheableRequest.StorageAdapter; + throwHttpErrors: boolean; + dnsCache?: CacheableLookup; + http2: boolean; + allowGetBody: boolean; + rejectUnauthorized: boolean; + lookup?: CacheableLookup['lookup']; + methodRewriting: boolean; + username: string; + password: string; + parseJson: ParseJsonFunction; + stringifyJson: StringifyJsonFunction; + retry: RequiredRetryOptions; + cacheOptions: CacheOptions; + [kRequest]: HttpRequestFunction; + [kIsNormalizedAlready]?: boolean; +} +export interface NormalizedOptions extends PromiseOnly.NormalizedOptions, NormalizedPlainOptions { +} +interface PlainDefaults { + timeout: Delays; + prefixUrl: string; + method: Method; + ignoreInvalidCookies: boolean; + decompress: boolean; + context: Record; + cookieJar?: PromiseCookieJar | ToughCookieJar; + dnsCache?: CacheableLookup; + headers: Headers; + hooks: Required; + followRedirect: boolean; + maxRedirects: number; + cache?: string | CacheableRequest.StorageAdapter; + throwHttpErrors: boolean; + http2: boolean; + allowGetBody: boolean; + https?: HTTPSOptions; + methodRewriting: boolean; + parseJson: ParseJsonFunction; + stringifyJson: StringifyJsonFunction; + retry: RequiredRetryOptions; + agent?: Agents | false; + request?: RequestFunction; + searchParams?: URLSearchParams; + lookup?: CacheableLookup['lookup']; + localAddress?: string; + createConnection?: Options['createConnection']; + cacheOptions: CacheOptions; +} +export interface Defaults extends PromiseOnly.Defaults, PlainDefaults { +} +export interface Progress { + percent: number; + transferred: number; + total?: number; +} +export interface PlainResponse extends IncomingMessageWithTimings { + /** + The original request URL. + */ + requestUrl: string; + /** + The redirect URLs. + */ + redirectUrls: string[]; + /** + - `options` - The Got options that were set on this request. + + __Note__: This is not a [http.ClientRequest](https://nodejs.org/api/http.html#http_class_http_clientrequest). + */ + request: Request; + /** + The remote IP address. + + This is hopefully a temporary limitation, see [lukechilds/cacheable-request#86](https://github.com/lukechilds/cacheable-request/issues/86). + + __Note__: Not available when the response is cached. + */ + ip?: string; + /** + Whether the response was retrieved from the cache. + */ + isFromCache: boolean; + /** + The status code of the response. + */ + statusCode: number; + /** + The request URL or the final URL after redirects. + */ + url: string; + /** + The object contains the following properties: + + - `start` - Time when the request started. + - `socket` - Time when a socket was assigned to the request. + - `lookup` - Time when the DNS lookup finished. + - `connect` - Time when the socket successfully connected. + - `secureConnect` - Time when the socket securely connected. + - `upload` - Time when the request finished uploading. + - `response` - Time when the request fired `response` event. + - `end` - Time when the response fired `end` event. + - `error` - Time when the request fired `error` event. + - `abort` - Time when the request fired `abort` event. + - `phases` + - `wait` - `timings.socket - timings.start` + - `dns` - `timings.lookup - timings.socket` + - `tcp` - `timings.connect - timings.lookup` + - `tls` - `timings.secureConnect - timings.connect` + - `request` - `timings.upload - (timings.secureConnect || timings.connect)` + - `firstByte` - `timings.response - timings.upload` + - `download` - `timings.end - timings.response` + - `total` - `(timings.end || timings.error || timings.abort) - timings.start` + + If something has not been measured yet, it will be `undefined`. + + __Note__: The time is a `number` representing the milliseconds elapsed since the UNIX epoch. + */ + timings: Timings; + /** + The number of times the request was retried. + */ + retryCount: number; + /** + The raw result of the request. + */ + rawBody?: Buffer; + /** + The result of the request. + */ + body?: unknown; +} +export interface Response extends PlainResponse { + /** + The result of the request. + */ + body: T; + /** + The raw result of the request. + */ + rawBody: Buffer; +} +export interface RequestEvents { + /** + `request` event to get the request object of the request. + + __Tip__: You can use `request` event to abort requests. + + @example + ``` + got.stream('https://github.com') + .on('request', request => setTimeout(() => request.destroy(), 50)); + ``` + */ + on: ((name: 'request', listener: (request: http.ClientRequest) => void) => T) + /** + The `response` event to get the response object of the final request. + */ + & ((name: 'response', listener: (response: R) => void) => T) + /** + The `redirect` event to get the response object of a redirect. The second argument is options for the next request to the redirect location. + */ + & ((name: 'redirect', listener: (response: R, nextOptions: N) => void) => T) + /** + Progress events for uploading (sending a request) and downloading (receiving a response). + The `progress` argument is an object like: + + ```js + { + percent: 0.1, + transferred: 1024, + total: 10240 + } + ``` + + If the `content-length` header is missing, `total` will be `undefined`. + + @example + ```js + (async () => { + const response = await got('https://sindresorhus.com') + .on('downloadProgress', progress => { + // Report download progress + }) + .on('uploadProgress', progress => { + // Report upload progress + }); + + console.log(response); + })(); + ``` + */ + & ((name: 'uploadProgress' | 'downloadProgress', listener: (progress: Progress) => void) => T) + /** + To enable retrying on a Got stream, it is required to have a `retry` handler attached. + + When this event is emitted, you should reset the stream you were writing to and prepare the body again. + + See `got.options.retry` for more information. + */ + & ((name: 'retry', listener: (retryCount: number, error: RequestError) => void) => T); +} +export declare const setNonEnumerableProperties: (sources: Array, to: Options) => void; +/** +An error to be thrown when a request fails. +Contains a `code` property with error class code, like `ECONNREFUSED`. +*/ +export declare class RequestError extends Error { + code: string; + stack: string; + readonly options: NormalizedOptions; + readonly response?: Response; + readonly request?: Request; + readonly timings?: Timings; + constructor(message: string, error: Partial, self: Request | NormalizedOptions); +} +/** +An error to be thrown when the server redirects you more than ten times. +Includes a `response` property. +*/ +export declare class MaxRedirectsError extends RequestError { + readonly response: Response; + readonly request: Request; + readonly timings: Timings; + constructor(request: Request); +} +/** +An error to be thrown when the server response code is not 2xx nor 3xx if `options.followRedirect` is `true`, but always except for 304. +Includes a `response` property. +*/ +export declare class HTTPError extends RequestError { + readonly response: Response; + readonly request: Request; + readonly timings: Timings; + constructor(response: Response); +} +/** +An error to be thrown when a cache method fails. +For example, if the database goes down or there's a filesystem error. +*/ +export declare class CacheError extends RequestError { + readonly request: Request; + constructor(error: Error, request: Request); +} +/** +An error to be thrown when the request body is a stream and an error occurs while reading from that stream. +*/ +export declare class UploadError extends RequestError { + readonly request: Request; + constructor(error: Error, request: Request); +} +/** +An error to be thrown when the request is aborted due to a timeout. +Includes an `event` and `timings` property. +*/ +export declare class TimeoutError extends RequestError { + readonly request: Request; + readonly timings: Timings; + readonly event: string; + constructor(error: TimedOutTimeoutError, timings: Timings, request: Request); +} +/** +An error to be thrown when reading from response stream fails. +*/ +export declare class ReadError extends RequestError { + readonly request: Request; + readonly response: Response; + readonly timings: Timings; + constructor(error: Error, request: Request); +} +/** +An error to be thrown when given an unsupported protocol. */ - & ((name: 'retry', listener: (retryCount: number, error: RequestError) => void) => T); -export type RequestEvents = { - on: GotEventFunction; - once: GotEventFunction; - off: GotEventFunction; -}; -type UrlType = ConstructorParameters[0]; -type OptionsType = ConstructorParameters[1]; -type DefaultsType = ConstructorParameters[2]; +export declare class UnsupportedProtocolError extends RequestError { + constructor(options: NormalizedOptions); +} export default class Request extends Duplex implements RequestEvents { ['constructor']: typeof Request; + [kUnproxyEvents]: () => void; + _cannotHaveBody: boolean; + [kDownloadedSize]: number; + [kUploadedSize]: number; + [kStopReading]: boolean; + [kTriggerRead]: boolean; + [kBody]: Options['body']; + [kJobs]: Array<() => void>; + [kRetryTimeout]?: NodeJS.Timeout; + [kBodySize]?: number; + [kServerResponsesPiped]: Set; + [kIsFromCache]?: boolean; + [kStartedReading]?: boolean; + [kCancelTimeouts]?: () => void; + [kResponseSize]?: number; + [kResponse]?: IncomingMessageWithTimings; + [kOriginalResponse]?: IncomingMessageWithTimings; + [kRequest]?: ClientRequest; _noPipe?: boolean; - options: Options; - response?: PlainResponse; - requestUrl?: URL; - redirectUrls: URL[]; + _progressCallbacks: Array<() => void>; + options: NormalizedOptions; + requestUrl: string; + requestInitialized: boolean; + redirects: string[]; retryCount: number; - private _requestOptions; - private _stopRetry; - private _downloadedSize; - private _uploadedSize; - private _stopReading; - private readonly _pipedServerResponses; - private _request?; - private _responseSize?; - private _bodySize?; - private _unproxyEvents; - private _isFromCache?; - private _cannotHaveBody; - private _triggerRead; - private readonly _jobs; - private _cancelTimeouts; - private readonly _removeListeners; - private _nativeResponse?; - private _flushed; - private _aborted; - private _requestInitialized; - constructor(url: UrlType, options?: OptionsType, defaults?: DefaultsType); - flush(): Promise; + constructor(url: string | URL | undefined, options?: Options, defaults?: Defaults); + static normalizeArguments(url?: string | URL, options?: Options, defaults?: Defaults): NormalizedOptions; + _lockWrite(): void; + _unlockWrite(): void; + _finalizeBody(): Promise; + _onResponseBase(response: IncomingMessageWithTimings): Promise; + _onResponse(response: IncomingMessageWithTimings): Promise; + _onRequest(request: ClientRequest): void; + _createCacheableRequest(url: URL, options: RequestOptions): Promise; + _makeRequest(): Promise; + _error(error: RequestError): Promise; _beforeError(error: Error): void; _read(): void; - _write(chunk: unknown, encoding: BufferEncoding | undefined, callback: (error?: Error | null) => void): void; + _write(chunk: any, encoding: string | undefined, callback: (error?: Error | null) => void): void; + _writeRequest(chunk: any, encoding: BufferEncoding | undefined, callback: (error?: Error | null) => void): void; _final(callback: (error?: Error | null) => void): void; _destroy(error: Error | null, callback: (error: Error | null) => void): void; - pipe(destination: T, options?: { - end?: boolean; - }): T; - unpipe(destination: T): this; - private _finalizeBody; - private _onResponseBase; - private _setRawBody; - private _onResponse; - private _onRequest; - private _asyncWrite; - private _sendBody; - private _prepareCache; - private _createCacheableRequest; - private _makeRequest; - private _error; - private _writeRequest; + get _isAboutToError(): boolean; /** The remote IP address. */ @@ -143,7 +1074,7 @@ export default class Request extends Duplex implements RequestEvents { /** Indicates whether the request has been aborted or not. */ - get isAborted(): boolean; + get aborted(): boolean; get socket(): Socket | undefined; /** Progress event for downloading (receiving a response). @@ -185,6 +1116,9 @@ export default class Request extends Duplex implements RequestEvents { Whether the response was retrieved from the cache. */ get isFromCache(): boolean | undefined; - get reusedSocket(): boolean | undefined; + pipe(destination: T, options?: { + end?: boolean; + }): T; + unpipe(destination: T): this; } export {}; diff --git a/setup-pandoc/node_modules/got/dist/source/core/index.js b/setup-pandoc/node_modules/got/dist/source/core/index.js index 06d60d486..c6cebd594 100644 --- a/setup-pandoc/node_modules/got/dist/source/core/index.js +++ b/setup-pandoc/node_modules/got/dist/source/core/index.js @@ -1,497 +1,823 @@ -import process from 'node:process'; -import { Buffer } from 'node:buffer'; -import { Duplex } from 'node:stream'; -import http, { ServerResponse } from 'node:http'; -import timer from '@szmarczak/http-timer'; -import CacheableRequest, { CacheError as CacheableCacheError, } from 'cacheable-request'; -import decompressResponse from 'decompress-response'; -import is from '@sindresorhus/is'; -import { getStreamAsBuffer } from 'get-stream'; -import { FormDataEncoder, isFormData as isFormDataLike } from 'form-data-encoder'; -import getBodySize from './utils/get-body-size.js'; -import isFormData from './utils/is-form-data.js'; -import proxyEvents from './utils/proxy-events.js'; -import timedOut, { TimeoutError as TimedOutTimeoutError } from './timed-out.js'; -import urlToOptions from './utils/url-to-options.js'; -import WeakableMap from './utils/weakable-map.js'; -import calculateRetryDelay from './calculate-retry-delay.js'; -import Options from './options.js'; -import { isResponseOk } from './response.js'; -import isClientRequest from './utils/is-client-request.js'; -import isUnixSocketURL from './utils/is-unix-socket-url.js'; -import { RequestError, ReadError, MaxRedirectsError, HTTPError, TimeoutError, UploadError, CacheError, AbortError, } from './errors.js'; -const supportsBrotli = is.string(process.versions.brotli); -const methodsWithoutBody = new Set(['GET', 'HEAD']); -const cacheableStore = new WeakableMap(); +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.UnsupportedProtocolError = exports.ReadError = exports.TimeoutError = exports.UploadError = exports.CacheError = exports.HTTPError = exports.MaxRedirectsError = exports.RequestError = exports.setNonEnumerableProperties = exports.knownHookEvents = exports.withoutBody = exports.kIsNormalizedAlready = void 0; +const util_1 = require("util"); +const stream_1 = require("stream"); +const fs_1 = require("fs"); +const url_1 = require("url"); +const http = require("http"); +const http_1 = require("http"); +const https = require("https"); +const http_timer_1 = require("@szmarczak/http-timer"); +const cacheable_lookup_1 = require("cacheable-lookup"); +const CacheableRequest = require("cacheable-request"); +const decompressResponse = require("decompress-response"); +// @ts-expect-error Missing types +const http2wrapper = require("http2-wrapper"); +const lowercaseKeys = require("lowercase-keys"); +const is_1 = require("@sindresorhus/is"); +const get_body_size_1 = require("./utils/get-body-size"); +const is_form_data_1 = require("./utils/is-form-data"); +const proxy_events_1 = require("./utils/proxy-events"); +const timed_out_1 = require("./utils/timed-out"); +const url_to_options_1 = require("./utils/url-to-options"); +const options_to_url_1 = require("./utils/options-to-url"); +const weakable_map_1 = require("./utils/weakable-map"); +const get_buffer_1 = require("./utils/get-buffer"); +const dns_ip_version_1 = require("./utils/dns-ip-version"); +const is_response_ok_1 = require("./utils/is-response-ok"); +const deprecation_warning_1 = require("../utils/deprecation-warning"); +const normalize_arguments_1 = require("../as-promise/normalize-arguments"); +const calculate_retry_delay_1 = require("./calculate-retry-delay"); +let globalDnsCache; +const kRequest = Symbol('request'); +const kResponse = Symbol('response'); +const kResponseSize = Symbol('responseSize'); +const kDownloadedSize = Symbol('downloadedSize'); +const kBodySize = Symbol('bodySize'); +const kUploadedSize = Symbol('uploadedSize'); +const kServerResponsesPiped = Symbol('serverResponsesPiped'); +const kUnproxyEvents = Symbol('unproxyEvents'); +const kIsFromCache = Symbol('isFromCache'); +const kCancelTimeouts = Symbol('cancelTimeouts'); +const kStartedReading = Symbol('startedReading'); +const kStopReading = Symbol('stopReading'); +const kTriggerRead = Symbol('triggerRead'); +const kBody = Symbol('body'); +const kJobs = Symbol('jobs'); +const kOriginalResponse = Symbol('originalResponse'); +const kRetryTimeout = Symbol('retryTimeout'); +exports.kIsNormalizedAlready = Symbol('isNormalizedAlready'); +const supportsBrotli = is_1.default.string(process.versions.brotli); +exports.withoutBody = new Set(['GET', 'HEAD']); +exports.knownHookEvents = [ + 'init', + 'beforeRequest', + 'beforeRedirect', + 'beforeError', + 'beforeRetry', + // Promise-Only + 'afterResponse' +]; +function validateSearchParameters(searchParameters) { + // eslint-disable-next-line guard-for-in + for (const key in searchParameters) { + const value = searchParameters[key]; + if (!is_1.default.string(value) && !is_1.default.number(value) && !is_1.default.boolean(value) && !is_1.default.null_(value) && !is_1.default.undefined(value)) { + throw new TypeError(`The \`searchParams\` value '${String(value)}' must be a string, number, boolean or null`); + } + } +} +function isClientRequest(clientRequest) { + return is_1.default.object(clientRequest) && !('statusCode' in clientRequest); +} +const cacheableStore = new weakable_map_1.default(); +const waitForOpenFile = async (file) => new Promise((resolve, reject) => { + const onError = (error) => { + reject(error); + }; + // Node.js 12 has incomplete types + if (!file.pending) { + resolve(); + } + file.once('error', onError); + file.once('ready', () => { + file.off('error', onError); + resolve(); + }); +}); const redirectCodes = new Set([300, 301, 302, 303, 304, 307, 308]); +const nonEnumerableProperties = [ + 'context', + 'body', + 'json', + 'form' +]; +exports.setNonEnumerableProperties = (sources, to) => { + // Non enumerable properties shall not be merged + const properties = {}; + for (const source of sources) { + if (!source) { + continue; + } + for (const name of nonEnumerableProperties) { + if (!(name in source)) { + continue; + } + properties[name] = { + writable: true, + configurable: true, + enumerable: false, + // @ts-expect-error TS doesn't see the check above + value: source[name] + }; + } + } + Object.defineProperties(to, properties); +}; +/** +An error to be thrown when a request fails. +Contains a `code` property with error class code, like `ECONNREFUSED`. +*/ +class RequestError extends Error { + constructor(message, error, self) { + var _a, _b; + super(message); + Error.captureStackTrace(this, this.constructor); + this.name = 'RequestError'; + this.code = (_a = error.code) !== null && _a !== void 0 ? _a : 'ERR_GOT_REQUEST_ERROR'; + if (self instanceof Request) { + Object.defineProperty(this, 'request', { + enumerable: false, + value: self + }); + Object.defineProperty(this, 'response', { + enumerable: false, + value: self[kResponse] + }); + Object.defineProperty(this, 'options', { + // This fails because of TS 3.7.2 useDefineForClassFields + // Ref: https://github.com/microsoft/TypeScript/issues/34972 + enumerable: false, + value: self.options + }); + } + else { + Object.defineProperty(this, 'options', { + // This fails because of TS 3.7.2 useDefineForClassFields + // Ref: https://github.com/microsoft/TypeScript/issues/34972 + enumerable: false, + value: self + }); + } + this.timings = (_b = this.request) === null || _b === void 0 ? void 0 : _b.timings; + // Recover the original stacktrace + if (is_1.default.string(error.stack) && is_1.default.string(this.stack)) { + const indexOfMessage = this.stack.indexOf(this.message) + this.message.length; + const thisStackTrace = this.stack.slice(indexOfMessage).split('\n').reverse(); + const errorStackTrace = error.stack.slice(error.stack.indexOf(error.message) + error.message.length).split('\n').reverse(); + // Remove duplicated traces + while (errorStackTrace.length !== 0 && errorStackTrace[0] === thisStackTrace[0]) { + thisStackTrace.shift(); + } + this.stack = `${this.stack.slice(0, indexOfMessage)}${thisStackTrace.reverse().join('\n')}${errorStackTrace.reverse().join('\n')}`; + } + } +} +exports.RequestError = RequestError; +/** +An error to be thrown when the server redirects you more than ten times. +Includes a `response` property. +*/ +class MaxRedirectsError extends RequestError { + constructor(request) { + super(`Redirected ${request.options.maxRedirects} times. Aborting.`, {}, request); + this.name = 'MaxRedirectsError'; + this.code = 'ERR_TOO_MANY_REDIRECTS'; + } +} +exports.MaxRedirectsError = MaxRedirectsError; +/** +An error to be thrown when the server response code is not 2xx nor 3xx if `options.followRedirect` is `true`, but always except for 304. +Includes a `response` property. +*/ +class HTTPError extends RequestError { + constructor(response) { + super(`Response code ${response.statusCode} (${response.statusMessage})`, {}, response.request); + this.name = 'HTTPError'; + this.code = 'ERR_NON_2XX_3XX_RESPONSE'; + } +} +exports.HTTPError = HTTPError; +/** +An error to be thrown when a cache method fails. +For example, if the database goes down or there's a filesystem error. +*/ +class CacheError extends RequestError { + constructor(error, request) { + super(error.message, error, request); + this.name = 'CacheError'; + this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_CACHE_ACCESS' : this.code; + } +} +exports.CacheError = CacheError; +/** +An error to be thrown when the request body is a stream and an error occurs while reading from that stream. +*/ +class UploadError extends RequestError { + constructor(error, request) { + super(error.message, error, request); + this.name = 'UploadError'; + this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_UPLOAD' : this.code; + } +} +exports.UploadError = UploadError; +/** +An error to be thrown when the request is aborted due to a timeout. +Includes an `event` and `timings` property. +*/ +class TimeoutError extends RequestError { + constructor(error, timings, request) { + super(error.message, error, request); + this.name = 'TimeoutError'; + this.event = error.event; + this.timings = timings; + } +} +exports.TimeoutError = TimeoutError; +/** +An error to be thrown when reading from response stream fails. +*/ +class ReadError extends RequestError { + constructor(error, request) { + super(error.message, error, request); + this.name = 'ReadError'; + this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_READING_RESPONSE_STREAM' : this.code; + } +} +exports.ReadError = ReadError; +/** +An error to be thrown when given an unsupported protocol. +*/ +class UnsupportedProtocolError extends RequestError { + constructor(options) { + super(`Unsupported protocol "${options.url.protocol}"`, {}, options); + this.name = 'UnsupportedProtocolError'; + this.code = 'ERR_UNSUPPORTED_PROTOCOL'; + } +} +exports.UnsupportedProtocolError = UnsupportedProtocolError; const proxiedRequestEvents = [ 'socket', 'connect', 'continue', 'information', 'upgrade', + 'timeout' ]; -const noop = () => { }; -export default class Request extends Duplex { - // @ts-expect-error - Ignoring for now. - ['constructor']; - _noPipe; - // @ts-expect-error https://github.com/microsoft/TypeScript/issues/9568 - options; - response; - requestUrl; - redirectUrls; - retryCount; - _stopRetry; - _downloadedSize; - _uploadedSize; - _stopReading; - _pipedServerResponses; - _request; - _responseSize; - _bodySize; - _unproxyEvents; - _isFromCache; - _cannotHaveBody; - _triggerRead; - _cancelTimeouts; - _removeListeners; - _nativeResponse; - _flushed; - _aborted; - // We need this because `this._request` if `undefined` when using cache - _requestInitialized; - constructor(url, options, defaults) { +class Request extends stream_1.Duplex { + constructor(url, options = {}, defaults) { super({ - // Don't destroy immediately, as the error may be emitted on unsuccessful retry + // This must be false, to enable throwing after destroy + // It is used for retry logic in Promise API autoDestroy: false, // It needs to be zero because we're just proxying the data to another stream - highWaterMark: 0, + highWaterMark: 0 }); - this._downloadedSize = 0; - this._uploadedSize = 0; - this._stopReading = false; - this._pipedServerResponses = new Set(); - this._cannotHaveBody = false; - this._unproxyEvents = noop; - this._triggerRead = false; - this._cancelTimeouts = noop; - this._removeListeners = noop; - this._jobs = []; - this._flushed = false; - this._requestInitialized = false; - this._aborted = false; - this.redirectUrls = []; + this[kDownloadedSize] = 0; + this[kUploadedSize] = 0; + this.requestInitialized = false; + this[kServerResponsesPiped] = new Set(); + this.redirects = []; + this[kStopReading] = false; + this[kTriggerRead] = false; + this[kJobs] = []; this.retryCount = 0; - this._stopRetry = noop; + // TODO: Remove this when targeting Node.js >= 12 + this._progressCallbacks = []; + const unlockWrite = () => this._unlockWrite(); + const lockWrite = () => this._lockWrite(); this.on('pipe', (source) => { - if (source?.headers) { - Object.assign(this.options.headers, source.headers); - } + source.prependListener('data', unlockWrite); + source.on('data', lockWrite); + source.prependListener('end', unlockWrite); + source.on('end', lockWrite); }); - this.on('newListener', event => { - if (event === 'retry' && this.listenerCount('retry') > 0) { - throw new Error('A retry listener has been attached already.'); - } + this.on('unpipe', (source) => { + source.off('data', unlockWrite); + source.off('data', lockWrite); + source.off('end', unlockWrite); + source.off('end', lockWrite); }); - try { - this.options = new Options(url, options, defaults); - if (!this.options.url) { - if (this.options.prefixUrl === '') { - throw new TypeError('Missing `url` property'); - } - this.options.url = ''; + this.on('pipe', source => { + if (source instanceof http_1.IncomingMessage) { + this.options.headers = { + ...source.headers, + ...this.options.headers + }; } - this.requestUrl = this.options.url; + }); + const { json, body, form } = options; + if (json || body || form) { + this._lockWrite(); } - catch (error) { - const { options } = error; - if (options) { - this.options = options; + if (exports.kIsNormalizedAlready in options) { + this.options = options; + } + else { + try { + // @ts-expect-error Common TypeScript bug saying that `this.constructor` is not accessible + this.options = this.constructor.normalizeArguments(url, options, defaults); } - this.flush = async () => { - this.flush = async () => { }; + catch (error) { + // TODO: Move this to `_destroy()` + if (is_1.default.nodeStream(options.body)) { + options.body.destroy(); + } this.destroy(error); - }; - return; + return; + } } - // Important! If you replace `body` in a handler with another stream, make sure it's readable first. - // The below is run only once. - const { body } = this.options; - if (is.nodeStream(body)) { - body.once('error', error => { - if (this._flushed) { - this._beforeError(new UploadError(error, this)); + (async () => { + var _a; + try { + if (this.options.body instanceof fs_1.ReadStream) { + await waitForOpenFile(this.options.body); } - else { - this.flush = async () => { - this.flush = async () => { }; - this._beforeError(new UploadError(error, this)); - }; + const { url: normalizedURL } = this.options; + if (!normalizedURL) { + throw new TypeError('Missing `url` property'); } - }); - } - if (this.options.signal) { - const abort = () => { - this.destroy(new AbortError(this)); - }; - if (this.options.signal.aborted) { - abort(); + this.requestUrl = normalizedURL.toString(); + decodeURI(this.requestUrl); + await this._finalizeBody(); + await this._makeRequest(); + if (this.destroyed) { + (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.destroy(); + return; + } + // Queued writes etc. + for (const job of this[kJobs]) { + job(); + } + // Prevent memory leak + this[kJobs].length = 0; + this.requestInitialized = true; } - else { - this.options.signal.addEventListener('abort', abort); - this._removeListeners = () => { - this.options.signal?.removeEventListener('abort', abort); - }; + catch (error) { + if (error instanceof RequestError) { + this._beforeError(error); + return; + } + // This is a workaround for https://github.com/nodejs/node/issues/33335 + if (!this.destroyed) { + this.destroy(error); + } } - } + })(); } - async flush() { - if (this._flushed) { - return; + static normalizeArguments(url, options, defaults) { + var _a, _b, _c, _d, _e; + const rawOptions = options; + if (is_1.default.object(url) && !is_1.default.urlInstance(url)) { + options = { ...defaults, ...url, ...options }; } - this._flushed = true; - try { - await this._finalizeBody(); - if (this.destroyed) { - return; + else { + if (url && options && options.url !== undefined) { + throw new TypeError('The `url` option is mutually exclusive with the `input` argument'); } - await this._makeRequest(); - if (this.destroyed) { - this._request?.destroy(); - return; + options = { ...defaults, ...options }; + if (url !== undefined) { + options.url = url; } - // Queued writes etc. - for (const job of this._jobs) { - job(); + if (is_1.default.urlInstance(options.url)) { + options.url = new url_1.URL(options.url.toString()); } - // Prevent memory leak - this._jobs.length = 0; - this._requestInitialized = true; } - catch (error) { - this._beforeError(error); + // TODO: Deprecate URL options in Got 12. + // Support extend-specific options + if (options.cache === false) { + options.cache = undefined; } - } - _beforeError(error) { - if (this._stopReading) { - return; + if (options.dnsCache === false) { + options.dnsCache = undefined; } - const { response, options } = this; - const attemptCount = this.retryCount + (error.name === 'RetryError' ? 0 : 1); - this._stopReading = true; - if (!(error instanceof RequestError)) { - error = new RequestError(error.message, error, this); + // Nice type assertions + is_1.assert.any([is_1.default.string, is_1.default.undefined], options.method); + is_1.assert.any([is_1.default.object, is_1.default.undefined], options.headers); + is_1.assert.any([is_1.default.string, is_1.default.urlInstance, is_1.default.undefined], options.prefixUrl); + is_1.assert.any([is_1.default.object, is_1.default.undefined], options.cookieJar); + is_1.assert.any([is_1.default.object, is_1.default.string, is_1.default.undefined], options.searchParams); + is_1.assert.any([is_1.default.object, is_1.default.string, is_1.default.undefined], options.cache); + is_1.assert.any([is_1.default.object, is_1.default.number, is_1.default.undefined], options.timeout); + is_1.assert.any([is_1.default.object, is_1.default.undefined], options.context); + is_1.assert.any([is_1.default.object, is_1.default.undefined], options.hooks); + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.decompress); + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.ignoreInvalidCookies); + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.followRedirect); + is_1.assert.any([is_1.default.number, is_1.default.undefined], options.maxRedirects); + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.throwHttpErrors); + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.http2); + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.allowGetBody); + is_1.assert.any([is_1.default.string, is_1.default.undefined], options.localAddress); + is_1.assert.any([dns_ip_version_1.isDnsLookupIpVersion, is_1.default.undefined], options.dnsLookupIpVersion); + is_1.assert.any([is_1.default.object, is_1.default.undefined], options.https); + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.rejectUnauthorized); + if (options.https) { + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.https.rejectUnauthorized); + is_1.assert.any([is_1.default.function_, is_1.default.undefined], options.https.checkServerIdentity); + is_1.assert.any([is_1.default.string, is_1.default.object, is_1.default.array, is_1.default.undefined], options.https.certificateAuthority); + is_1.assert.any([is_1.default.string, is_1.default.object, is_1.default.array, is_1.default.undefined], options.https.key); + is_1.assert.any([is_1.default.string, is_1.default.object, is_1.default.array, is_1.default.undefined], options.https.certificate); + is_1.assert.any([is_1.default.string, is_1.default.undefined], options.https.passphrase); + is_1.assert.any([is_1.default.string, is_1.default.buffer, is_1.default.array, is_1.default.undefined], options.https.pfx); } - const typedError = error; - void (async () => { - // Node.js parser is really weird. - // It emits post-request Parse Errors on the same instance as previous request. WTF. - // Therefore, we need to check if it has been destroyed as well. - // - // Furthermore, Node.js 16 `response.destroy()` doesn't immediately destroy the socket, - // but makes the response unreadable. So we additionally need to check `response.readable`. - if (response?.readable && !response.rawBody && !this._request?.socket?.destroyed) { - // @types/node has incorrect typings. `setEncoding` accepts `null` as well. - response.setEncoding(this.readableEncoding); - const success = await this._setRawBody(response); - if (success) { - response.body = response.rawBody.toString(); + is_1.assert.any([is_1.default.object, is_1.default.undefined], options.cacheOptions); + // `options.method` + if (is_1.default.string(options.method)) { + options.method = options.method.toUpperCase(); + } + else { + options.method = 'GET'; + } + // `options.headers` + if (options.headers === (defaults === null || defaults === void 0 ? void 0 : defaults.headers)) { + options.headers = { ...options.headers }; + } + else { + options.headers = lowercaseKeys({ ...(defaults === null || defaults === void 0 ? void 0 : defaults.headers), ...options.headers }); + } + // Disallow legacy `url.Url` + if ('slashes' in options) { + throw new TypeError('The legacy `url.Url` has been deprecated. Use `URL` instead.'); + } + // `options.auth` + if ('auth' in options) { + throw new TypeError('Parameter `auth` is deprecated. Use `username` / `password` instead.'); + } + // `options.searchParams` + if ('searchParams' in options) { + if (options.searchParams && options.searchParams !== (defaults === null || defaults === void 0 ? void 0 : defaults.searchParams)) { + let searchParameters; + if (is_1.default.string(options.searchParams) || (options.searchParams instanceof url_1.URLSearchParams)) { + searchParameters = new url_1.URLSearchParams(options.searchParams); } - } - if (this.listenerCount('retry') !== 0) { - let backoff; - try { - let retryAfter; - if (response && 'retry-after' in response.headers) { - retryAfter = Number(response.headers['retry-after']); - if (Number.isNaN(retryAfter)) { - retryAfter = Date.parse(response.headers['retry-after']) - Date.now(); - if (retryAfter <= 0) { - retryAfter = 1; - } + else { + validateSearchParameters(options.searchParams); + searchParameters = new url_1.URLSearchParams(); + // eslint-disable-next-line guard-for-in + for (const key in options.searchParams) { + const value = options.searchParams[key]; + if (value === null) { + searchParameters.append(key, ''); } - else { - retryAfter *= 1000; + else if (value !== undefined) { + searchParameters.append(key, value); } } - const retryOptions = options.retry; - backoff = await retryOptions.calculateDelay({ - attemptCount, - retryOptions, - error: typedError, - retryAfter, - computedValue: calculateRetryDelay({ - attemptCount, - retryOptions, - error: typedError, - retryAfter, - computedValue: retryOptions.maxRetryAfter ?? options.timeout.request ?? Number.POSITIVE_INFINITY, - }), - }); - } - catch (error_) { - void this._error(new RequestError(error_.message, error_, this)); - return; } - if (backoff) { - await new Promise(resolve => { - const timeout = setTimeout(resolve, backoff); - this._stopRetry = () => { - clearTimeout(timeout); - resolve(); - }; - }); - // Something forced us to abort the retry - if (this.destroyed) { - return; + // `normalizeArguments()` is also used to merge options + (_a = defaults === null || defaults === void 0 ? void 0 : defaults.searchParams) === null || _a === void 0 ? void 0 : _a.forEach((value, key) => { + // Only use default if one isn't already defined + if (!searchParameters.has(key)) { + searchParameters.append(key, value); } - try { - for (const hook of this.options.hooks.beforeRetry) { - // eslint-disable-next-line no-await-in-loop - await hook(typedError, this.retryCount + 1); - } - } - catch (error_) { - void this._error(new RequestError(error_.message, error, this)); - return; - } - // Something forced us to abort the retry - if (this.destroyed) { - return; + }); + options.searchParams = searchParameters; + } + } + // `options.username` & `options.password` + options.username = (_b = options.username) !== null && _b !== void 0 ? _b : ''; + options.password = (_c = options.password) !== null && _c !== void 0 ? _c : ''; + // `options.prefixUrl` & `options.url` + if (is_1.default.undefined(options.prefixUrl)) { + options.prefixUrl = (_d = defaults === null || defaults === void 0 ? void 0 : defaults.prefixUrl) !== null && _d !== void 0 ? _d : ''; + } + else { + options.prefixUrl = options.prefixUrl.toString(); + if (options.prefixUrl !== '' && !options.prefixUrl.endsWith('/')) { + options.prefixUrl += '/'; + } + } + if (is_1.default.string(options.url)) { + if (options.url.startsWith('/')) { + throw new Error('`input` must not start with a slash when using `prefixUrl`'); + } + options.url = options_to_url_1.default(options.prefixUrl + options.url, options); + } + else if ((is_1.default.undefined(options.url) && options.prefixUrl !== '') || options.protocol) { + options.url = options_to_url_1.default(options.prefixUrl, options); + } + if (options.url) { + if ('port' in options) { + delete options.port; + } + // Make it possible to change `options.prefixUrl` + let { prefixUrl } = options; + Object.defineProperty(options, 'prefixUrl', { + set: (value) => { + const url = options.url; + if (!url.href.startsWith(value)) { + throw new Error(`Cannot change \`prefixUrl\` from ${prefixUrl} to ${value}: ${url.href}`); } - this.destroy(); - this.emit('retry', this.retryCount + 1, error, (updatedOptions) => { - const request = new Request(options.url, updatedOptions, options); - request.retryCount = this.retryCount + 1; - process.nextTick(() => { - void request.flush(); - }); - return request; - }); - return; - } + options.url = new url_1.URL(value + url.href.slice(prefixUrl.length)); + prefixUrl = value; + }, + get: () => prefixUrl + }); + // Support UNIX sockets + let { protocol } = options.url; + if (protocol === 'unix:') { + protocol = 'http:'; + options.url = new url_1.URL(`http://unix${options.url.pathname}${options.url.search}`); } - void this._error(typedError); - })(); - } - _read() { - this._triggerRead = true; - const { response } = this; - if (response && !this._stopReading) { - // We cannot put this in the `if` above - // because `.read()` also triggers the `end` event - if (response.readableLength) { - this._triggerRead = false; + // Set search params + if (options.searchParams) { + // eslint-disable-next-line @typescript-eslint/no-base-to-string + options.url.search = options.searchParams.toString(); } - let data; - while ((data = response.read()) !== null) { - this._downloadedSize += data.length; // eslint-disable-line @typescript-eslint/restrict-plus-operands - const progress = this.downloadProgress; - if (progress.percent < 1) { - this.emit('downloadProgress', progress); - } - this.push(data); + // Protocol check + if (protocol !== 'http:' && protocol !== 'https:') { + throw new UnsupportedProtocolError(options); + } + // Update `username` + if (options.username === '') { + options.username = options.url.username; + } + else { + options.url.username = options.username; + } + // Update `password` + if (options.password === '') { + options.password = options.url.password; + } + else { + options.url.password = options.password; } } - } - _write(chunk, encoding, callback) { - const write = () => { - this._writeRequest(chunk, encoding, callback); - }; - if (this._requestInitialized) { - write(); + // `options.cookieJar` + const { cookieJar } = options; + if (cookieJar) { + let { setCookie, getCookieString } = cookieJar; + is_1.assert.function_(setCookie); + is_1.assert.function_(getCookieString); + /* istanbul ignore next: Horrible `tough-cookie` v3 check */ + if (setCookie.length === 4 && getCookieString.length === 0) { + setCookie = util_1.promisify(setCookie.bind(options.cookieJar)); + getCookieString = util_1.promisify(getCookieString.bind(options.cookieJar)); + options.cookieJar = { + setCookie, + getCookieString: getCookieString + }; + } } - else { - this._jobs.push(write); + // `options.cache` + const { cache } = options; + if (cache) { + if (!cacheableStore.has(cache)) { + cacheableStore.set(cache, new CacheableRequest(((requestOptions, handler) => { + const result = requestOptions[kRequest](requestOptions, handler); + // TODO: remove this when `cacheable-request` supports async request functions. + if (is_1.default.promise(result)) { + // @ts-expect-error + // We only need to implement the error handler in order to support HTTP2 caching. + // The result will be a promise anyway. + result.once = (event, handler) => { + if (event === 'error') { + result.catch(handler); + } + else if (event === 'abort') { + // The empty catch is needed here in case when + // it rejects before it's `await`ed in `_makeRequest`. + (async () => { + try { + const request = (await result); + request.once('abort', handler); + } + catch (_a) { } + })(); + } + else { + /* istanbul ignore next: safety check */ + throw new Error(`Unknown HTTP2 promise event: ${event}`); + } + return result; + }; + } + return result; + }), cache)); + } } - } - _final(callback) { - const endRequest = () => { - // We need to check if `this._request` is present, - // because it isn't when we use cache. - if (!this._request || this._request.destroyed) { - callback(); - return; + // `options.cacheOptions` + options.cacheOptions = { ...options.cacheOptions }; + // `options.dnsCache` + if (options.dnsCache === true) { + if (!globalDnsCache) { + globalDnsCache = new cacheable_lookup_1.default(); } - this._request.end((error) => { - // The request has been destroyed before `_final` finished. - // See https://github.com/nodejs/node/issues/39356 - if (this._request._writableState?.errored) { - return; - } - if (!error) { - this._bodySize = this._uploadedSize; - this.emit('uploadProgress', this.uploadProgress); - this._request.emit('upload-complete'); - } - callback(error); - }); - }; - if (this._requestInitialized) { - endRequest(); + options.dnsCache = globalDnsCache; + } + else if (!is_1.default.undefined(options.dnsCache) && !options.dnsCache.lookup) { + throw new TypeError(`Parameter \`dnsCache\` must be a CacheableLookup instance or a boolean, got ${is_1.default(options.dnsCache)}`); + } + // `options.timeout` + if (is_1.default.number(options.timeout)) { + options.timeout = { request: options.timeout }; + } + else if (defaults && options.timeout !== defaults.timeout) { + options.timeout = { + ...defaults.timeout, + ...options.timeout + }; } else { - this._jobs.push(endRequest); + options.timeout = { ...options.timeout }; } - } - _destroy(error, callback) { - this._stopReading = true; - this.flush = async () => { }; - // Prevent further retries - this._stopRetry(); - this._cancelTimeouts(); - this._removeListeners(); - if (this.options) { - const { body } = this.options; - if (is.nodeStream(body)) { - body.destroy(); + // `options.context` + if (!options.context) { + options.context = {}; + } + // `options.hooks` + const areHooksDefault = options.hooks === (defaults === null || defaults === void 0 ? void 0 : defaults.hooks); + options.hooks = { ...options.hooks }; + for (const event of exports.knownHookEvents) { + if (event in options.hooks) { + if (is_1.default.array(options.hooks[event])) { + // See https://github.com/microsoft/TypeScript/issues/31445#issuecomment-576929044 + options.hooks[event] = [...options.hooks[event]]; + } + else { + throw new TypeError(`Parameter \`${event}\` must be an Array, got ${is_1.default(options.hooks[event])}`); + } + } + else { + options.hooks[event] = []; } } - if (this._request) { - this._request.destroy(); + if (defaults && !areHooksDefault) { + for (const event of exports.knownHookEvents) { + const defaultHooks = defaults.hooks[event]; + if (defaultHooks.length > 0) { + // See https://github.com/microsoft/TypeScript/issues/31445#issuecomment-576929044 + options.hooks[event] = [ + ...defaults.hooks[event], + ...options.hooks[event] + ]; + } + } } - if (error !== null && !is.undefined(error) && !(error instanceof RequestError)) { - error = new RequestError(error.message, error, this); + // DNS options + if ('family' in options) { + deprecation_warning_1.default('"options.family" was never documented, please use "options.dnsLookupIpVersion"'); } - callback(error); - } - pipe(destination, options) { - if (destination instanceof ServerResponse) { - this._pipedServerResponses.add(destination); + // HTTPS options + if (defaults === null || defaults === void 0 ? void 0 : defaults.https) { + options.https = { ...defaults.https, ...options.https }; } - return super.pipe(destination, options); - } - unpipe(destination) { - if (destination instanceof ServerResponse) { - this._pipedServerResponses.delete(destination); + if ('rejectUnauthorized' in options) { + deprecation_warning_1.default('"options.rejectUnauthorized" is now deprecated, please use "options.https.rejectUnauthorized"'); } - super.unpipe(destination); - return this; + if ('checkServerIdentity' in options) { + deprecation_warning_1.default('"options.checkServerIdentity" was never documented, please use "options.https.checkServerIdentity"'); + } + if ('ca' in options) { + deprecation_warning_1.default('"options.ca" was never documented, please use "options.https.certificateAuthority"'); + } + if ('key' in options) { + deprecation_warning_1.default('"options.key" was never documented, please use "options.https.key"'); + } + if ('cert' in options) { + deprecation_warning_1.default('"options.cert" was never documented, please use "options.https.certificate"'); + } + if ('passphrase' in options) { + deprecation_warning_1.default('"options.passphrase" was never documented, please use "options.https.passphrase"'); + } + if ('pfx' in options) { + deprecation_warning_1.default('"options.pfx" was never documented, please use "options.https.pfx"'); + } + // Other options + if ('followRedirects' in options) { + throw new TypeError('The `followRedirects` option does not exist. Use `followRedirect` instead.'); + } + if (options.agent) { + for (const key in options.agent) { + if (key !== 'http' && key !== 'https' && key !== 'http2') { + throw new TypeError(`Expected the \`options.agent\` properties to be \`http\`, \`https\` or \`http2\`, got \`${key}\``); + } + } + } + options.maxRedirects = (_e = options.maxRedirects) !== null && _e !== void 0 ? _e : 0; + // Set non-enumerable properties + exports.setNonEnumerableProperties([defaults, rawOptions], options); + return normalize_arguments_1.default(options, defaults); + } + _lockWrite() { + const onLockedWrite = () => { + throw new TypeError('The payload has been already provided'); + }; + this.write = onLockedWrite; + this.end = onLockedWrite; + } + _unlockWrite() { + this.write = super.write; + this.end = super.end; } async _finalizeBody() { const { options } = this; const { headers } = options; - const isForm = !is.undefined(options.form); - // eslint-disable-next-line @typescript-eslint/naming-convention - const isJSON = !is.undefined(options.json); - const isBody = !is.undefined(options.body); - const cannotHaveBody = methodsWithoutBody.has(options.method) && !(options.method === 'GET' && options.allowGetBody); + const isForm = !is_1.default.undefined(options.form); + const isJSON = !is_1.default.undefined(options.json); + const isBody = !is_1.default.undefined(options.body); + const hasPayload = isForm || isJSON || isBody; + const cannotHaveBody = exports.withoutBody.has(options.method) && !(options.method === 'GET' && options.allowGetBody); this._cannotHaveBody = cannotHaveBody; - if (isForm || isJSON || isBody) { + if (hasPayload) { if (cannotHaveBody) { throw new TypeError(`The \`${options.method}\` method cannot be used with a body`); } - // Serialize body - const noContentType = !is.string(headers['content-type']); - if (isBody) { - // Body is spec-compliant FormData - if (isFormDataLike(options.body)) { - const encoder = new FormDataEncoder(options.body); - if (noContentType) { - headers['content-type'] = encoder.headers['Content-Type']; - } - if ('Content-Length' in encoder.headers) { - headers['content-length'] = encoder.headers['Content-Length']; + if ([isBody, isForm, isJSON].filter(isTrue => isTrue).length > 1) { + throw new TypeError('The `body`, `json` and `form` options are mutually exclusive'); + } + if (isBody && + !(options.body instanceof stream_1.Readable) && + !is_1.default.string(options.body) && + !is_1.default.buffer(options.body) && + !is_form_data_1.default(options.body)) { + throw new TypeError('The `body` option must be a stream.Readable, string or Buffer'); + } + if (isForm && !is_1.default.object(options.form)) { + throw new TypeError('The `form` option must be an Object'); + } + { + // Serialize body + const noContentType = !is_1.default.string(headers['content-type']); + if (isBody) { + // Special case for https://github.com/form-data/form-data + if (is_form_data_1.default(options.body) && noContentType) { + headers['content-type'] = `multipart/form-data; boundary=${options.body.getBoundary()}`; } - options.body = encoder.encode(); + this[kBody] = options.body; } - // Special case for https://github.com/form-data/form-data - if (isFormData(options.body) && noContentType) { - headers['content-type'] = `multipart/form-data; boundary=${options.body.getBoundary()}`; + else if (isForm) { + if (noContentType) { + headers['content-type'] = 'application/x-www-form-urlencoded'; + } + this[kBody] = (new url_1.URLSearchParams(options.form)).toString(); } - } - else if (isForm) { - if (noContentType) { - headers['content-type'] = 'application/x-www-form-urlencoded'; + else { + if (noContentType) { + headers['content-type'] = 'application/json'; + } + this[kBody] = options.stringifyJson(options.json); } - const { form } = options; - options.form = undefined; - options.body = (new URLSearchParams(form)).toString(); - } - else { - if (noContentType) { - headers['content-type'] = 'application/json'; + const uploadBodySize = await get_body_size_1.default(this[kBody], options.headers); + // See https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD send a Content-Length in a request message when + // no Transfer-Encoding is sent and the request method defines a meaning + // for an enclosed payload body. For example, a Content-Length header + // field is normally sent in a POST request even when the value is 0 + // (indicating an empty payload body). A user agent SHOULD NOT send a + // Content-Length header field when the request message does not contain + // a payload body and the method semantics do not anticipate such a + // body. + if (is_1.default.undefined(headers['content-length']) && is_1.default.undefined(headers['transfer-encoding'])) { + if (!cannotHaveBody && !is_1.default.undefined(uploadBodySize)) { + headers['content-length'] = String(uploadBodySize); + } } - const { json } = options; - options.json = undefined; - options.body = options.stringifyJson(json); - } - const uploadBodySize = await getBodySize(options.body, options.headers); - // See https://tools.ietf.org/html/rfc7230#section-3.3.2 - // A user agent SHOULD send a Content-Length in a request message when - // no Transfer-Encoding is sent and the request method defines a meaning - // for an enclosed payload body. For example, a Content-Length header - // field is normally sent in a POST request even when the value is 0 - // (indicating an empty payload body). A user agent SHOULD NOT send a - // Content-Length header field when the request message does not contain - // a payload body and the method semantics do not anticipate such a - // body. - if (is.undefined(headers['content-length']) && is.undefined(headers['transfer-encoding']) && !cannotHaveBody && !is.undefined(uploadBodySize)) { - headers['content-length'] = String(uploadBodySize); } } - if (options.responseType === 'json' && !('accept' in options.headers)) { - options.headers.accept = 'application/json'; + else if (cannotHaveBody) { + this._lockWrite(); + } + else { + this._unlockWrite(); } - this._bodySize = Number(headers['content-length']) || undefined; + this[kBodySize] = Number(headers['content-length']) || undefined; } async _onResponseBase(response) { - // This will be called e.g. when using cache so we need to check if this request has been aborted. - if (this.isAborted) { - return; - } const { options } = this; const { url } = options; - this._nativeResponse = response; + this[kOriginalResponse] = response; if (options.decompress) { response = decompressResponse(response); } const statusCode = response.statusCode; const typedResponse = response; - typedResponse.statusMessage = typedResponse.statusMessage ?? http.STATUS_CODES[statusCode]; + typedResponse.statusMessage = typedResponse.statusMessage ? typedResponse.statusMessage : http.STATUS_CODES[statusCode]; typedResponse.url = options.url.toString(); typedResponse.requestUrl = this.requestUrl; - typedResponse.redirectUrls = this.redirectUrls; + typedResponse.redirectUrls = this.redirects; typedResponse.request = this; - typedResponse.isFromCache = this._nativeResponse.fromCache ?? false; + typedResponse.isFromCache = response.fromCache || false; typedResponse.ip = this.ip; typedResponse.retryCount = this.retryCount; - typedResponse.ok = isResponseOk(typedResponse); - this._isFromCache = typedResponse.isFromCache; - this._responseSize = Number(response.headers['content-length']) || undefined; - this.response = typedResponse; + this[kIsFromCache] = typedResponse.isFromCache; + this[kResponseSize] = Number(response.headers['content-length']) || undefined; + this[kResponse] = response; response.once('end', () => { - this._responseSize = this._downloadedSize; + this[kResponseSize] = this[kDownloadedSize]; this.emit('downloadProgress', this.downloadProgress); }); response.once('error', (error) => { - this._aborted = true; // Force clean-up, because some packages don't do this. // TODO: Fix decompress-response response.destroy(); this._beforeError(new ReadError(error, this)); }); response.once('aborted', () => { - this._aborted = true; this._beforeError(new ReadError({ name: 'Error', message: 'The server aborted pending request', - code: 'ECONNRESET', + code: 'ECONNRESET' }, this)); }); this.emit('downloadProgress', this.downloadProgress); const rawCookies = response.headers['set-cookie']; - if (is.object(options.cookieJar) && rawCookies) { + if (is_1.default.object(options.cookieJar) && rawCookies) { let promises = rawCookies.map(async (rawCookie) => options.cookieJar.setCookie(rawCookie, url.toString())); if (options.ignoreInvalidCookies) { - // eslint-disable-next-line @typescript-eslint/no-floating-promises - promises = promises.map(async (promise) => { - try { - await promise; - } - catch { } - }); + promises = promises.map(async (p) => p.catch(() => { })); } try { await Promise.all(promises); @@ -501,91 +827,94 @@ export default class Request extends Duplex { return; } } - // The above is running a promise, therefore we need to check if this request has been aborted yet again. - if (this.isAborted) { - return; - } - if (response.headers.location && redirectCodes.has(statusCode)) { + if (options.followRedirect && response.headers.location && redirectCodes.has(statusCode)) { // We're being redirected, we don't care about the response. // It'd be best to abort the request, but we can't because // we would have to sacrifice the TCP connection. We don't want that. - const shouldFollow = typeof options.followRedirect === 'function' ? options.followRedirect(typedResponse) : options.followRedirect; - if (shouldFollow) { - response.resume(); - this._cancelTimeouts(); - this._unproxyEvents(); - if (this.redirectUrls.length >= options.maxRedirects) { - this._beforeError(new MaxRedirectsError(this)); - return; + response.resume(); + if (this[kRequest]) { + this[kCancelTimeouts](); + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete this[kRequest]; + this[kUnproxyEvents](); + } + const shouldBeGet = statusCode === 303 && options.method !== 'GET' && options.method !== 'HEAD'; + if (shouldBeGet || !options.methodRewriting) { + // Server responded with "see other", indicating that the resource exists at another location, + // and the client should request it from that location via GET or HEAD. + options.method = 'GET'; + if ('body' in options) { + delete options.body; } - this._request = undefined; - const updatedOptions = new Options(undefined, undefined, this.options); - const serverRequestedGet = statusCode === 303 && updatedOptions.method !== 'GET' && updatedOptions.method !== 'HEAD'; - const canRewrite = statusCode !== 307 && statusCode !== 308; - const userRequestedGet = updatedOptions.methodRewriting && canRewrite; - if (serverRequestedGet || userRequestedGet) { - updatedOptions.method = 'GET'; - updatedOptions.body = undefined; - updatedOptions.json = undefined; - updatedOptions.form = undefined; - delete updatedOptions.headers['content-length']; + if ('json' in options) { + delete options.json; } - try { - // We need this in order to support UTF-8 - const redirectBuffer = Buffer.from(response.headers.location, 'binary').toString(); - const redirectUrl = new URL(redirectBuffer, url); - if (!isUnixSocketURL(url) && isUnixSocketURL(redirectUrl)) { - this._beforeError(new RequestError('Cannot redirect to UNIX socket', {}, this)); - return; + if ('form' in options) { + delete options.form; + } + this[kBody] = undefined; + delete options.headers['content-length']; + } + if (this.redirects.length >= options.maxRedirects) { + this._beforeError(new MaxRedirectsError(this)); + return; + } + try { + // Do not remove. See https://github.com/sindresorhus/got/pull/214 + const redirectBuffer = Buffer.from(response.headers.location, 'binary').toString(); + // Handles invalid URLs. See https://github.com/sindresorhus/got/issues/604 + const redirectUrl = new url_1.URL(redirectBuffer, url); + const redirectString = redirectUrl.toString(); + decodeURI(redirectString); + // eslint-disable-next-line no-inner-declarations + function isUnixSocketURL(url) { + return url.protocol === 'unix:' || url.hostname === 'unix'; + } + if (!isUnixSocketURL(url) && isUnixSocketURL(redirectUrl)) { + this._beforeError(new RequestError('Cannot redirect to UNIX socket', {}, this)); + return; + } + // Redirecting to a different site, clear sensitive data. + if (redirectUrl.hostname !== url.hostname || redirectUrl.port !== url.port) { + if ('host' in options.headers) { + delete options.headers.host; } - // Redirecting to a different site, clear sensitive data. - if (redirectUrl.hostname !== url.hostname || redirectUrl.port !== url.port) { - if ('host' in updatedOptions.headers) { - delete updatedOptions.headers.host; - } - if ('cookie' in updatedOptions.headers) { - delete updatedOptions.headers.cookie; - } - if ('authorization' in updatedOptions.headers) { - delete updatedOptions.headers.authorization; - } - if (updatedOptions.username || updatedOptions.password) { - updatedOptions.username = ''; - updatedOptions.password = ''; - } + if ('cookie' in options.headers) { + delete options.headers.cookie; } - else { - redirectUrl.username = updatedOptions.username; - redirectUrl.password = updatedOptions.password; + if ('authorization' in options.headers) { + delete options.headers.authorization; } - this.redirectUrls.push(redirectUrl); - updatedOptions.prefixUrl = ''; - updatedOptions.url = redirectUrl; - for (const hook of updatedOptions.hooks.beforeRedirect) { - // eslint-disable-next-line no-await-in-loop - await hook(updatedOptions, typedResponse); + if (options.username || options.password) { + options.username = ''; + options.password = ''; } - this.emit('redirect', updatedOptions, typedResponse); - this.options = updatedOptions; - await this._makeRequest(); } - catch (error) { - this._beforeError(error); - return; + else { + redirectUrl.username = options.username; + redirectUrl.password = options.password; } + this.redirects.push(redirectString); + options.url = redirectUrl; + for (const hook of options.hooks.beforeRedirect) { + // eslint-disable-next-line no-await-in-loop + await hook(options, typedResponse); + } + this.emit('redirect', typedResponse, options); + await this._makeRequest(); + } + catch (error) { + this._beforeError(error); return; } + return; } - // `HTTPError`s always have `error.response.body` defined. - // Therefore, we cannot retry if `options.throwHttpErrors` is false. - // On the last retry, if `options.throwHttpErrors` is false, we would need to return the body, - // but that wouldn't be possible since the body would be already read in `error.response.body`. - if (options.isStream && options.throwHttpErrors && !isResponseOk(typedResponse)) { + if (options.isStream && options.throwHttpErrors && !is_response_ok_1.isResponseOk(typedResponse)) { this._beforeError(new HTTPError(typedResponse)); return; } response.on('readable', () => { - if (this._triggerRead) { + if (this[kTriggerRead]) { this._read(); } }); @@ -598,15 +927,8 @@ export default class Request extends Duplex { response.once('end', () => { this.push(null); }); - if (this._noPipe) { - const success = await this._setRawBody(); - if (success) { - this.emit('response', response); - } - return; - } this.emit('response', response); - for (const destination of this._pipedServerResponses) { + for (const destination of this[kServerResponsesPiped]) { if (destination.headersSent) { continue; } @@ -621,26 +943,6 @@ export default class Request extends Duplex { destination.statusCode = statusCode; } } - async _setRawBody(from = this) { - if (from.readableEnded) { - return false; - } - try { - // Errors are emitted via the `error` event - const rawBody = await getStreamAsBuffer(from); - // TODO: Switch to this: - // let rawBody = await from.toArray(); - // rawBody = Buffer.concat(rawBody); - // On retry Request is destroyed with no error, therefore the above will successfully resolve. - // So in order to check if this was really successfull, we need to check if it has been properly ended. - if (!this.isAborted) { - this.response.rawBody = rawBody; - return true; - } - } - catch { } - return false; - } async _onResponse(response) { try { await this._onResponseBase(response); @@ -653,131 +955,67 @@ export default class Request extends Duplex { _onRequest(request) { const { options } = this; const { timeout, url } = options; - timer(request); - if (this.options.http2) { - // Unset stream timeout, as the `timeout` option was used only for connection timeout. - request.setTimeout(0); - } - this._cancelTimeouts = timedOut(request, timeout, url); + http_timer_1.default(request); + this[kCancelTimeouts] = timed_out_1.default(request, timeout, url); const responseEventName = options.cache ? 'cacheableResponse' : 'response'; request.once(responseEventName, (response) => { void this._onResponse(response); }); request.once('error', (error) => { - this._aborted = true; + var _a; // Force clean-up, because some packages (e.g. nock) don't do this. request.destroy(); - error = error instanceof TimedOutTimeoutError ? new TimeoutError(error, this.timings, this) : new RequestError(error.message, error, this); + // Node.js <= 12.18.2 mistakenly emits the response `end` first. + (_a = request.res) === null || _a === void 0 ? void 0 : _a.removeAllListeners('end'); + error = error instanceof timed_out_1.TimeoutError ? new TimeoutError(error, this.timings, this) : new RequestError(error.message, error, this); this._beforeError(error); }); - this._unproxyEvents = proxyEvents(request, this, proxiedRequestEvents); - this._request = request; + this[kUnproxyEvents] = proxy_events_1.default(request, this, proxiedRequestEvents); + this[kRequest] = request; this.emit('uploadProgress', this.uploadProgress); - this._sendBody(); - this.emit('request', request); - } - async _asyncWrite(chunk) { - return new Promise((resolve, reject) => { - super.write(chunk, error => { - if (error) { - reject(error); - return; - } - resolve(); - }); - }); - } - _sendBody() { // Send body - const { body } = this.options; - const currentRequest = this.redirectUrls.length === 0 ? this : this._request ?? this; - if (is.nodeStream(body)) { + const body = this[kBody]; + const currentRequest = this.redirects.length === 0 ? this : request; + if (is_1.default.nodeStream(body)) { body.pipe(currentRequest); + body.once('error', (error) => { + this._beforeError(new UploadError(error, this)); + }); } - else if (is.generator(body) || is.asyncGenerator(body)) { - (async () => { - try { - for await (const chunk of body) { - await this._asyncWrite(chunk); - } - super.end(); - } - catch (error) { - this._beforeError(error); - } - })(); - } - else if (!is.undefined(body)) { - this._writeRequest(body, undefined, () => { }); - currentRequest.end(); - } - else if (this._cannotHaveBody || this._noPipe) { - currentRequest.end(); - } - } - _prepareCache(cache) { - if (!cacheableStore.has(cache)) { - const cacheableRequest = new CacheableRequest(((requestOptions, handler) => { - const result = requestOptions._request(requestOptions, handler); - // TODO: remove this when `cacheable-request` supports async request functions. - if (is.promise(result)) { - // We only need to implement the error handler in order to support HTTP2 caching. - // The result will be a promise anyway. - // @ts-expect-error ignore - result.once = (event, handler) => { - if (event === 'error') { - (async () => { - try { - await result; - } - catch (error) { - handler(error); - } - })(); - } - else if (event === 'abort') { - // The empty catch is needed here in case when - // it rejects before it's `await`ed in `_makeRequest`. - (async () => { - try { - const request = (await result); - request.once('abort', handler); - } - catch { } - })(); - } - else { - /* istanbul ignore next: safety check */ - throw new Error(`Unknown HTTP2 promise event: ${event}`); - } - return result; - }; - } - return result; - }), cache); - cacheableStore.set(cache, cacheableRequest.request()); + else { + this._unlockWrite(); + if (!is_1.default.undefined(body)) { + this._writeRequest(body, undefined, () => { }); + currentRequest.end(); + this._lockWrite(); + } + else if (this._cannotHaveBody || this._noPipe) { + currentRequest.end(); + this._lockWrite(); + } } + this.emit('request', request); } async _createCacheableRequest(url, options) { return new Promise((resolve, reject) => { // TODO: Remove `utils/url-to-options.ts` when `cacheable-request` is fixed - Object.assign(options, urlToOptions(url)); + Object.assign(options, url_to_options_1.default(url)); + // `http-cache-semantics` checks this + // TODO: Fix this ignore. + // @ts-expect-error + delete options.url; let request; - // TODO: Fix `cacheable-response`. This is ugly. + // This is ugly const cacheRequest = cacheableStore.get(options.cache)(options, async (response) => { + // TODO: Fix `cacheable-response` response._readableState.autoDestroy = false; if (request) { - const fix = () => { - if (response.req) { - response.complete = response.req.res.complete; - } - }; - response.prependOnceListener('end', fix); - fix(); (await request).emit('cacheableResponse', response); } resolve(response); }); + // Restore options + options.url = url; cacheRequest.once('error', reject); cacheRequest.once('request', async (requestOrPromise) => { request = requestOrPromise; @@ -786,103 +1024,178 @@ export default class Request extends Duplex { }); } async _makeRequest() { + var _a, _b, _c, _d, _e; const { options } = this; - const { headers, username, password } = options; - const cookieJar = options.cookieJar; + const { headers } = options; for (const key in headers) { - if (is.undefined(headers[key])) { + if (is_1.default.undefined(headers[key])) { // eslint-disable-next-line @typescript-eslint/no-dynamic-delete delete headers[key]; } - else if (is.null_(headers[key])) { + else if (is_1.default.null_(headers[key])) { throw new TypeError(`Use \`undefined\` instead of \`null\` to delete the \`${key}\` header`); } } - if (options.decompress && is.undefined(headers['accept-encoding'])) { + if (options.decompress && is_1.default.undefined(headers['accept-encoding'])) { headers['accept-encoding'] = supportsBrotli ? 'gzip, deflate, br' : 'gzip, deflate'; } - if (username || password) { - const credentials = Buffer.from(`${username}:${password}`).toString('base64'); - headers.authorization = `Basic ${credentials}`; - } // Set cookies - if (cookieJar) { - const cookieString = await cookieJar.getCookieString(options.url.toString()); - if (is.nonEmptyString(cookieString)) { - headers.cookie = cookieString; + if (options.cookieJar) { + const cookieString = await options.cookieJar.getCookieString(options.url.toString()); + if (is_1.default.nonEmptyString(cookieString)) { + options.headers.cookie = cookieString; } } - // Reset `prefixUrl` - options.prefixUrl = ''; - let request; for (const hook of options.hooks.beforeRequest) { // eslint-disable-next-line no-await-in-loop const result = await hook(options); - if (!is.undefined(result)) { + if (!is_1.default.undefined(result)) { // @ts-expect-error Skip the type mismatch to support abstract responses - request = () => result; + options.request = () => result; break; } } - if (!request) { - request = options.getRequestFunction(); + if (options.body && this[kBody] !== options.body) { + this[kBody] = options.body; + } + const { agent, request, timeout, url } = options; + if (options.dnsCache && !('lookup' in options)) { + options.lookup = options.dnsCache.lookup; + } + // UNIX sockets + if (url.hostname === 'unix') { + const matches = /(?.+?):(?.+)/.exec(`${url.pathname}${url.search}`); + if (matches === null || matches === void 0 ? void 0 : matches.groups) { + const { socketPath, path } = matches.groups; + Object.assign(options, { + socketPath, + path, + host: '' + }); + } + } + const isHttps = url.protocol === 'https:'; + // Fallback function + let fallbackFn; + if (options.http2) { + fallbackFn = http2wrapper.auto; } - const url = options.url; - this._requestOptions = options.createNativeRequestOptions(); - if (options.cache) { - this._requestOptions._request = request; - this._requestOptions.cache = options.cache; - this._requestOptions.body = options.body; - this._prepareCache(options.cache); + else { + fallbackFn = isHttps ? https.request : http.request; } + const realFn = (_a = options.request) !== null && _a !== void 0 ? _a : fallbackFn; // Cache support - const fn = options.cache ? this._createCacheableRequest : request; + const fn = options.cache ? this._createCacheableRequest : realFn; + // Pass an agent directly when HTTP2 is disabled + if (agent && !options.http2) { + options.agent = agent[isHttps ? 'https' : 'http']; + } + // Prepare plain HTTP request options + options[kRequest] = realFn; + delete options.request; + // TODO: Fix this ignore. + // @ts-expect-error + delete options.timeout; + const requestOptions = options; + requestOptions.shared = (_b = options.cacheOptions) === null || _b === void 0 ? void 0 : _b.shared; + requestOptions.cacheHeuristic = (_c = options.cacheOptions) === null || _c === void 0 ? void 0 : _c.cacheHeuristic; + requestOptions.immutableMinTimeToLive = (_d = options.cacheOptions) === null || _d === void 0 ? void 0 : _d.immutableMinTimeToLive; + requestOptions.ignoreCargoCult = (_e = options.cacheOptions) === null || _e === void 0 ? void 0 : _e.ignoreCargoCult; + // If `dnsLookupIpVersion` is not present do not override `family` + if (options.dnsLookupIpVersion !== undefined) { + try { + requestOptions.family = dns_ip_version_1.dnsLookupIpVersionToFamily(options.dnsLookupIpVersion); + } + catch (_f) { + throw new Error('Invalid `dnsLookupIpVersion` option value'); + } + } + // HTTPS options remapping + if (options.https) { + if ('rejectUnauthorized' in options.https) { + requestOptions.rejectUnauthorized = options.https.rejectUnauthorized; + } + if (options.https.checkServerIdentity) { + requestOptions.checkServerIdentity = options.https.checkServerIdentity; + } + if (options.https.certificateAuthority) { + requestOptions.ca = options.https.certificateAuthority; + } + if (options.https.certificate) { + requestOptions.cert = options.https.certificate; + } + if (options.https.key) { + requestOptions.key = options.https.key; + } + if (options.https.passphrase) { + requestOptions.passphrase = options.https.passphrase; + } + if (options.https.pfx) { + requestOptions.pfx = options.https.pfx; + } + } try { - // We can't do `await fn(...)`, - // because stream `error` event can be emitted before `Promise.resolve()`. - let requestOrResponse = fn(url, this._requestOptions); - if (is.promise(requestOrResponse)) { - requestOrResponse = await requestOrResponse; + let requestOrResponse = await fn(url, requestOptions); + if (is_1.default.undefined(requestOrResponse)) { + requestOrResponse = fallbackFn(url, requestOptions); } - // Fallback - if (is.undefined(requestOrResponse)) { - requestOrResponse = options.getFallbackRequestFunction()(url, this._requestOptions); - if (is.promise(requestOrResponse)) { - requestOrResponse = await requestOrResponse; + // Restore options + options.request = request; + options.timeout = timeout; + options.agent = agent; + // HTTPS options restore + if (options.https) { + if ('rejectUnauthorized' in options.https) { + delete requestOptions.rejectUnauthorized; + } + if (options.https.checkServerIdentity) { + // @ts-expect-error - This one will be removed when we remove the alias. + delete requestOptions.checkServerIdentity; + } + if (options.https.certificateAuthority) { + delete requestOptions.ca; + } + if (options.https.certificate) { + delete requestOptions.cert; + } + if (options.https.key) { + delete requestOptions.key; + } + if (options.https.passphrase) { + delete requestOptions.passphrase; + } + if (options.https.pfx) { + delete requestOptions.pfx; } } if (isClientRequest(requestOrResponse)) { this._onRequest(requestOrResponse); + // Emit the response after the stream has been ended } else if (this.writable) { this.once('finish', () => { void this._onResponse(requestOrResponse); }); - this._sendBody(); + this._unlockWrite(); + this.end(); + this._lockWrite(); } else { void this._onResponse(requestOrResponse); } } catch (error) { - if (error instanceof CacheableCacheError) { + if (error instanceof CacheableRequest.CacheError) { throw new CacheError(error, this); } - throw error; + throw new RequestError(error.message, error, this); } } async _error(error) { try { - if (error instanceof HTTPError && !this.options.throwHttpErrors) { - // This branch can be reached only when using the Promise API - // Skip calling the hooks on purpose. - // See https://github.com/sindresorhus/got/issues/2103 - } - else { - for (const hook of this.options.hooks.beforeError) { - // eslint-disable-next-line no-await-in-loop - error = await hook(error); - } + for (const hook of this.options.hooks.beforeError) { + // eslint-disable-next-line no-await-in-loop + error = await hook(error); } } catch (error_) { @@ -890,47 +1203,220 @@ export default class Request extends Duplex { } this.destroy(error); } - _writeRequest(chunk, encoding, callback) { - if (!this._request || this._request.destroyed) { - // Probably the `ClientRequest` instance will throw + _beforeError(error) { + if (this[kStopReading]) { return; } - this._request.write(chunk, encoding, (error) => { - // The `!destroyed` check is required to prevent `uploadProgress` being emitted after the stream was destroyed - if (!error && !this._request.destroyed) { - this._uploadedSize += Buffer.byteLength(chunk, encoding); - const progress = this.uploadProgress; + const { options } = this; + const retryCount = this.retryCount + 1; + this[kStopReading] = true; + if (!(error instanceof RequestError)) { + error = new RequestError(error.message, error, this); + } + const typedError = error; + const { response } = typedError; + void (async () => { + if (response && !response.body) { + response.setEncoding(this._readableState.encoding); + try { + response.rawBody = await get_buffer_1.default(response); + response.body = response.rawBody.toString(); + } + catch (_a) { } + } + if (this.listenerCount('retry') !== 0) { + let backoff; + try { + let retryAfter; + if (response && 'retry-after' in response.headers) { + retryAfter = Number(response.headers['retry-after']); + if (Number.isNaN(retryAfter)) { + retryAfter = Date.parse(response.headers['retry-after']) - Date.now(); + if (retryAfter <= 0) { + retryAfter = 1; + } + } + else { + retryAfter *= 1000; + } + } + backoff = await options.retry.calculateDelay({ + attemptCount: retryCount, + retryOptions: options.retry, + error: typedError, + retryAfter, + computedValue: calculate_retry_delay_1.default({ + attemptCount: retryCount, + retryOptions: options.retry, + error: typedError, + retryAfter, + computedValue: 0 + }) + }); + } + catch (error_) { + void this._error(new RequestError(error_.message, error_, this)); + return; + } + if (backoff) { + const retry = async () => { + try { + for (const hook of this.options.hooks.beforeRetry) { + // eslint-disable-next-line no-await-in-loop + await hook(this.options, typedError, retryCount); + } + } + catch (error_) { + void this._error(new RequestError(error_.message, error, this)); + return; + } + // Something forced us to abort the retry + if (this.destroyed) { + return; + } + this.destroy(); + this.emit('retry', retryCount, error); + }; + this[kRetryTimeout] = setTimeout(retry, backoff); + return; + } + } + void this._error(typedError); + })(); + } + _read() { + this[kTriggerRead] = true; + const response = this[kResponse]; + if (response && !this[kStopReading]) { + // We cannot put this in the `if` above + // because `.read()` also triggers the `end` event + if (response.readableLength) { + this[kTriggerRead] = false; + } + let data; + while ((data = response.read()) !== null) { + this[kDownloadedSize] += data.length; + this[kStartedReading] = true; + const progress = this.downloadProgress; if (progress.percent < 1) { - this.emit('uploadProgress', progress); + this.emit('downloadProgress', progress); } + this.push(data); + } + } + } + // Node.js 12 has incorrect types, so the encoding must be a string + _write(chunk, encoding, callback) { + const write = () => { + this._writeRequest(chunk, encoding, callback); + }; + if (this.requestInitialized) { + write(); + } + else { + this[kJobs].push(write); + } + } + _writeRequest(chunk, encoding, callback) { + if (this[kRequest].destroyed) { + // Probably the `ClientRequest` instance will throw + return; + } + this._progressCallbacks.push(() => { + this[kUploadedSize] += Buffer.byteLength(chunk, encoding); + const progress = this.uploadProgress; + if (progress.percent < 1) { + this.emit('uploadProgress', progress); + } + }); + // TODO: What happens if it's from cache? Then this[kRequest] won't be defined. + this[kRequest].write(chunk, encoding, (error) => { + if (!error && this._progressCallbacks.length > 0) { + this._progressCallbacks.shift()(); } callback(error); }); } + _final(callback) { + const endRequest = () => { + // FIX: Node.js 10 calls the write callback AFTER the end callback! + while (this._progressCallbacks.length !== 0) { + this._progressCallbacks.shift()(); + } + // We need to check if `this[kRequest]` is present, + // because it isn't when we use cache. + if (!(kRequest in this)) { + callback(); + return; + } + if (this[kRequest].destroyed) { + callback(); + return; + } + this[kRequest].end((error) => { + if (!error) { + this[kBodySize] = this[kUploadedSize]; + this.emit('uploadProgress', this.uploadProgress); + this[kRequest].emit('upload-complete'); + } + callback(error); + }); + }; + if (this.requestInitialized) { + endRequest(); + } + else { + this[kJobs].push(endRequest); + } + } + _destroy(error, callback) { + var _a; + this[kStopReading] = true; + // Prevent further retries + clearTimeout(this[kRetryTimeout]); + if (kRequest in this) { + this[kCancelTimeouts](); + // TODO: Remove the next `if` when these get fixed: + // - https://github.com/nodejs/node/issues/32851 + if (!((_a = this[kResponse]) === null || _a === void 0 ? void 0 : _a.complete)) { + this[kRequest].destroy(); + } + } + if (error !== null && !is_1.default.undefined(error) && !(error instanceof RequestError)) { + error = new RequestError(error.message, error, this); + } + callback(error); + } + get _isAboutToError() { + return this[kStopReading]; + } /** The remote IP address. */ get ip() { - return this.socket?.remoteAddress; + var _a; + return (_a = this.socket) === null || _a === void 0 ? void 0 : _a.remoteAddress; } /** Indicates whether the request has been aborted or not. */ - get isAborted() { - return this._aborted; + get aborted() { + var _a, _b, _c; + return ((_b = (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.destroyed) !== null && _b !== void 0 ? _b : this.destroyed) && !((_c = this[kOriginalResponse]) === null || _c === void 0 ? void 0 : _c.complete); } get socket() { - return this._request?.socket ?? undefined; + var _a, _b; + return (_b = (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.socket) !== null && _b !== void 0 ? _b : undefined; } /** Progress event for downloading (receiving a response). */ get downloadProgress() { let percent; - if (this._responseSize) { - percent = this._downloadedSize / this._responseSize; + if (this[kResponseSize]) { + percent = this[kDownloadedSize] / this[kResponseSize]; } - else if (this._responseSize === this._downloadedSize) { + else if (this[kResponseSize] === this[kDownloadedSize]) { percent = 1; } else { @@ -938,8 +1424,8 @@ export default class Request extends Duplex { } return { percent, - transferred: this._downloadedSize, - total: this._responseSize, + transferred: this[kDownloadedSize], + total: this[kResponseSize] }; } /** @@ -947,10 +1433,10 @@ export default class Request extends Duplex { */ get uploadProgress() { let percent; - if (this._bodySize) { - percent = this._uploadedSize / this._bodySize; + if (this[kBodySize]) { + percent = this[kUploadedSize] / this[kBodySize]; } - else if (this._bodySize === this._uploadedSize) { + else if (this[kBodySize] === this[kUploadedSize]) { percent = 1; } else { @@ -958,8 +1444,8 @@ export default class Request extends Duplex { } return { percent, - transferred: this._uploadedSize, - total: this._bodySize, + transferred: this[kUploadedSize], + total: this[kBodySize] }; } /** @@ -990,15 +1476,30 @@ export default class Request extends Duplex { __Note__: The time is a `number` representing the milliseconds elapsed since the UNIX epoch. */ get timings() { - return this._request?.timings; + var _a; + return (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.timings; } /** Whether the response was retrieved from the cache. */ get isFromCache() { - return this._isFromCache; + return this[kIsFromCache]; + } + pipe(destination, options) { + if (this[kStartedReading]) { + throw new Error('Failed to pipe. The response has been emitted already.'); + } + if (destination instanceof http_1.ServerResponse) { + this[kServerResponsesPiped].add(destination); + } + return super.pipe(destination, options); } - get reusedSocket() { - return this._request?.reusedSocket; + unpipe(destination) { + if (destination instanceof http_1.ServerResponse) { + this[kServerResponsesPiped].delete(destination); + } + super.unpipe(destination); + return this; } } +exports.default = Request; diff --git a/setup-pandoc/node_modules/got/dist/source/core/options.d.ts b/setup-pandoc/node_modules/got/dist/source/core/options.d.ts deleted file mode 100644 index b4c191ab9..000000000 --- a/setup-pandoc/node_modules/got/dist/source/core/options.d.ts +++ /dev/null @@ -1,1255 +0,0 @@ -/// -/// -/// -/// -/// -/// -/// -/// -import type { Buffer } from 'node:buffer'; -import { checkServerIdentity, type SecureContextOptions, type DetailedPeerCertificate } from 'node:tls'; -import https, { type RequestOptions as HttpsRequestOptions, type Agent as HttpsAgent } from 'node:https'; -import http, { type Agent as HttpAgent, type ClientRequest } from 'node:http'; -import type { Readable } from 'node:stream'; -import type { Socket } from 'node:net'; -import CacheableLookup from 'cacheable-lookup'; -import http2wrapper, { type ClientHttp2Session } from 'http2-wrapper'; -import { type FormDataLike } from 'form-data-encoder'; -import type { StorageAdapter } from 'cacheable-request'; -import type ResponseLike from 'responselike'; -import type { IncomingMessageWithTimings } from '@szmarczak/http-timer'; -import type { CancelableRequest } from '../as-promise/types.js'; -import type { PlainResponse, Response } from './response.js'; -import type { RequestError } from './errors.js'; -import type { Delays } from './timed-out.js'; -type Promisable = T | Promise; -export type DnsLookupIpVersion = undefined | 4 | 6; -type Except = Pick>; -export type NativeRequestOptions = HttpsRequestOptions & CacheOptions & { - checkServerIdentity?: CheckServerIdentityFunction; -}; -type AcceptableResponse = IncomingMessageWithTimings | ResponseLike; -type AcceptableRequestResult = Promisable | undefined; -export type RequestFunction = (url: URL, options: NativeRequestOptions, callback?: (response: AcceptableResponse) => void) => AcceptableRequestResult; -export type Agents = { - http?: HttpAgent | false; - https?: HttpsAgent | false; - http2?: unknown | false; -}; -export type Headers = Record; -export type ToughCookieJar = { - getCookieString: ((currentUrl: string, options: Record, cb: (error: Error | null, cookies: string) => void) => void) & ((url: string, callback: (error: Error | null, cookieHeader: string) => void) => void); - setCookie: ((cookieOrString: unknown, currentUrl: string, options: Record, cb: (error: Error | null, cookie: unknown) => void) => void) & ((rawCookie: string, url: string, callback: (error: Error | null, result: unknown) => void) => void); -}; -export type PromiseCookieJar = { - getCookieString: (url: string) => Promise; - setCookie: (rawCookie: string, url: string) => Promise; -}; -export type InitHook = (init: OptionsInit, self: Options) => void; -export type BeforeRequestHook = (options: Options) => Promisable; -export type BeforeRedirectHook = (updatedOptions: Options, plainResponse: PlainResponse) => Promisable; -export type BeforeErrorHook = (error: RequestError) => Promisable; -export type BeforeRetryHook = (error: RequestError, retryCount: number) => Promisable; -export type AfterResponseHook = (response: Response, retryWithMergedOptions: (options: OptionsInit) => never) => Promisable>; -/** -All available hooks of Got. -*/ -export type Hooks = { - /** - Called with the plain request options, right before their normalization. - - The second argument represents the current `Options` instance. - - @default [] - - **Note:** - > - This hook must be synchronous. - - **Note:** - > - This is called every time options are merged. - - **Note:** - > - The `options` object may not have the `url` property. To modify it, use a `beforeRequest` hook instead. - - **Note:** - > - This hook is called when a new instance of `Options` is created. - > - Do not confuse this with the creation of `Request` or `got(…)`. - - **Note:** - > - When using `got(url)` or `got(url, undefined, defaults)` this hook will **not** be called. - - This is especially useful in conjunction with `got.extend()` when the input needs custom handling. - - For example, this can be used to fix typos to migrate from older versions faster. - - @example - ``` - import got from 'got'; - - const instance = got.extend({ - hooks: { - init: [ - plain => { - if ('followRedirects' in plain) { - plain.followRedirect = plain.followRedirects; - delete plain.followRedirects; - } - } - ] - } - }); - - // Normally, the following would throw: - const response = await instance( - 'https://example.com', - { - followRedirects: true - } - ); - - // There is no option named `followRedirects`, but we correct it in an `init` hook. - ``` - - Or you can create your own option and store it in a context: - - ``` - import got from 'got'; - - const instance = got.extend({ - hooks: { - init: [ - (plain, options) => { - if ('secret' in plain) { - options.context.secret = plain.secret; - delete plain.secret; - } - } - ], - beforeRequest: [ - options => { - options.headers.secret = options.context.secret; - } - ] - } - }); - - const {headers} = await instance( - 'https://httpbin.org/anything', - { - secret: 'passphrase' - } - ).json(); - - console.log(headers.Secret); - //=> 'passphrase' - ``` - */ - init: InitHook[]; - /** - Called right before making the request with `options.createNativeRequestOptions()`. - - This hook is especially useful in conjunction with `got.extend()` when you want to sign your request. - - @default [] - - **Note:** - > - Got will make no further changes to the request before it is sent. - - **Note:** - > - Changing `options.json` or `options.form` has no effect on the request. You should change `options.body` instead. If needed, update the `options.headers` accordingly. - - @example - ``` - import got from 'got'; - - const response = await got.post( - 'https://httpbin.org/anything', - { - json: {payload: 'old'}, - hooks: { - beforeRequest: [ - options => { - options.body = JSON.stringify({payload: 'new'}); - options.headers['content-length'] = options.body.length.toString(); - } - ] - } - } - ); - ``` - - **Tip:** - > - You can indirectly override the `request` function by early returning a [`ClientRequest`-like](https://nodejs.org/api/http.html#http_class_http_clientrequest) instance or a [`IncomingMessage`-like](https://nodejs.org/api/http.html#http_class_http_incomingmessage) instance. This is very useful when creating a custom cache mechanism. - > - [Read more about this tip](https://github.com/sindresorhus/got/blob/main/documentation/cache.md#advanced-caching-mechanisms). - */ - beforeRequest: BeforeRequestHook[]; - /** - The equivalent of `beforeRequest` but when redirecting. - - @default [] - - **Tip:** - > - This is especially useful when you want to avoid dead sites. - - @example - ``` - import got from 'got'; - - const response = await got('https://example.com', { - hooks: { - beforeRedirect: [ - (options, response) => { - if (options.hostname === 'deadSite') { - options.hostname = 'fallbackSite'; - } - } - ] - } - }); - ``` - */ - beforeRedirect: BeforeRedirectHook[]; - /** - Called with a `RequestError` instance. The error is passed to the hook right before it's thrown. - - This is especially useful when you want to have more detailed errors. - - @default [] - - ``` - import got from 'got'; - - await got('https://api.github.com/repos/sindresorhus/got/commits', { - responseType: 'json', - hooks: { - beforeError: [ - error => { - const {response} = error; - if (response && response.body) { - error.name = 'GitHubError'; - error.message = `${response.body.message} (${response.statusCode})`; - } - - return error; - } - ] - } - }); - ``` - */ - beforeError: BeforeErrorHook[]; - /** - The equivalent of `beforeError` but when retrying. Additionally, there is a second argument `retryCount`, the current retry number. - - @default [] - - **Note:** - > - When using the Stream API, this hook is ignored. - - **Note:** - > - When retrying, the `beforeRequest` hook is called afterwards. - - **Note:** - > - If no retry occurs, the `beforeError` hook is called instead. - - This hook is especially useful when you want to retrieve the cause of a retry. - - @example - ``` - import got from 'got'; - - await got('https://httpbin.org/status/500', { - hooks: { - beforeRetry: [ - (error, retryCount) => { - console.log(`Retrying [${retryCount}]: ${error.code}`); - // Retrying [1]: ERR_NON_2XX_3XX_RESPONSE - } - ] - } - }); - ``` - */ - beforeRetry: BeforeRetryHook[]; - /** - Each function should return the response. This is especially useful when you want to refresh an access token. - - @default [] - - **Note:** - > - When using the Stream API, this hook is ignored. - - **Note:** - > - Calling the `retryWithMergedOptions` function will trigger `beforeRetry` hooks. If the retry is successful, all remaining `afterResponse` hooks will be called. In case of an error, `beforeRetry` hooks will be called instead. - Meanwhile the `init`, `beforeRequest` , `beforeRedirect` as well as already executed `afterResponse` hooks will be skipped. - - @example - ``` - import got from 'got'; - - const instance = got.extend({ - hooks: { - afterResponse: [ - (response, retryWithMergedOptions) => { - // Unauthorized - if (response.statusCode === 401) { - // Refresh the access token - const updatedOptions = { - headers: { - token: getNewToken() - } - }; - - // Update the defaults - instance.defaults.options.merge(updatedOptions); - - // Make a new retry - return retryWithMergedOptions(updatedOptions); - } - - // No changes otherwise - return response; - } - ], - beforeRetry: [ - error => { - // This will be called on `retryWithMergedOptions(...)` - } - ] - }, - mutableDefaults: true - }); - ``` - */ - afterResponse: AfterResponseHook[]; -}; -export type ParseJsonFunction = (text: string) => unknown; -export type StringifyJsonFunction = (object: unknown) => string; -/** -All available HTTP request methods provided by Got. -*/ -export type Method = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'HEAD' | 'DELETE' | 'OPTIONS' | 'TRACE' | 'get' | 'post' | 'put' | 'patch' | 'head' | 'delete' | 'options' | 'trace'; -export type RetryObject = { - attemptCount: number; - retryOptions: RetryOptions; - error: RequestError; - computedValue: number; - retryAfter?: number; -}; -export type RetryFunction = (retryObject: RetryObject) => Promisable; -/** -An object representing `limit`, `calculateDelay`, `methods`, `statusCodes`, `maxRetryAfter` and `errorCodes` fields for maximum retry count, retry handler, allowed methods, allowed status codes, maximum [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time and allowed error codes. - -Delays between retries counts with function `1000 * Math.pow(2, retry) + Math.random() * 100`, where `retry` is attempt number (starts from 1). - -The `calculateDelay` property is a `function` that receives an object with `attemptCount`, `retryOptions`, `error` and `computedValue` properties for current retry count, the retry options, error and default computed value. -The function must return a delay in milliseconds (or a Promise resolving with it) (`0` return value cancels retry). - -By default, it retries *only* on the specified methods, status codes, and on these network errors: -- `ETIMEDOUT`: One of the [timeout](#timeout) limits were reached. -- `ECONNRESET`: Connection was forcibly closed by a peer. -- `EADDRINUSE`: Could not bind to any free port. -- `ECONNREFUSED`: Connection was refused by the server. -- `EPIPE`: The remote side of the stream being written has been closed. -- `ENOTFOUND`: Couldn't resolve the hostname to an IP address. -- `ENETUNREACH`: No internet connection. -- `EAI_AGAIN`: DNS lookup timed out. - -__Note:__ Got does not retry on `POST` by default. -__Note:__ If `maxRetryAfter` is set to `undefined`, it will use `options.timeout`. -__Note:__ If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will cancel the request. -*/ -export type RetryOptions = { - limit: number; - methods: Method[]; - statusCodes: number[]; - errorCodes: string[]; - calculateDelay: RetryFunction; - backoffLimit: number; - noise: number; - maxRetryAfter?: number; -}; -export type CreateConnectionFunction = (options: NativeRequestOptions, oncreate: (error: NodeJS.ErrnoException, socket: Socket) => void) => Socket; -export type CheckServerIdentityFunction = (hostname: string, certificate: DetailedPeerCertificate) => NodeJS.ErrnoException | void; -export type CacheOptions = { - shared?: boolean; - cacheHeuristic?: number; - immutableMinTimeToLive?: number; - ignoreCargoCult?: boolean; -}; -type PfxObject = { - buffer: string | Buffer; - passphrase?: string | undefined; -}; -type PfxType = string | Buffer | Array | undefined; -export type HttpsOptions = { - alpnProtocols?: string[]; - rejectUnauthorized?: NativeRequestOptions['rejectUnauthorized']; - checkServerIdentity?: CheckServerIdentityFunction; - /** - Override the default Certificate Authorities ([from Mozilla](https://ccadb-public.secure.force.com/mozilla/IncludedCACertificateReport)). - - @example - ``` - // Single Certificate Authority - await got('https://example.com', { - https: { - certificateAuthority: fs.readFileSync('./my_ca.pem') - } - }); - ``` - */ - certificateAuthority?: SecureContextOptions['ca']; - /** - Private keys in [PEM](https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail) format. - - [PEM](https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail) allows the option of private keys being encrypted. - Encrypted keys will be decrypted with `options.https.passphrase`. - - Multiple keys with different passphrases can be provided as an array of `{pem: , passphrase: }` - */ - key?: SecureContextOptions['key']; - /** - [Certificate chains](https://en.wikipedia.org/wiki/X.509#Certificate_chains_and_cross-certification) in [PEM](https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail) format. - - One cert chain should be provided per private key (`options.https.key`). - - When providing multiple cert chains, they do not have to be in the same order as their private keys in `options.https.key`. - - If the intermediate certificates are not provided, the peer will not be able to validate the certificate, and the handshake will fail. - */ - certificate?: SecureContextOptions['cert']; - /** - The passphrase to decrypt the `options.https.key` (if different keys have different passphrases refer to `options.https.key` documentation). - */ - passphrase?: SecureContextOptions['passphrase']; - pfx?: PfxType; - ciphers?: SecureContextOptions['ciphers']; - honorCipherOrder?: SecureContextOptions['honorCipherOrder']; - minVersion?: SecureContextOptions['minVersion']; - maxVersion?: SecureContextOptions['maxVersion']; - signatureAlgorithms?: SecureContextOptions['sigalgs']; - tlsSessionLifetime?: SecureContextOptions['sessionTimeout']; - dhparam?: SecureContextOptions['dhparam']; - ecdhCurve?: SecureContextOptions['ecdhCurve']; - certificateRevocationLists?: SecureContextOptions['crl']; -}; -export type PaginateData = { - response: Response; - currentItems: ElementType[]; - allItems: ElementType[]; -}; -export type FilterData = { - item: ElementType; - currentItems: ElementType[]; - allItems: ElementType[]; -}; -/** -All options accepted by `got.paginate()`. -*/ -export type PaginationOptions = { - /** - A function that transform [`Response`](#response) into an array of items. - This is where you should do the parsing. - - @default response => JSON.parse(response.body) - */ - transform?: (response: Response) => Promise | ElementType[]; - /** - Checks whether the item should be emitted or not. - - @default ({item, currentItems, allItems}) => true - */ - filter?: (data: FilterData) => boolean; - /** - The function takes an object with the following properties: - - `response` - The current response object. - - `currentItems` - Items from the current response. - - `allItems` - An empty array, unless `pagination.stackAllItems` is set to `true`, in which case, it's an array of the emitted items. - - It should return an object representing Got options pointing to the next page. The options are merged automatically with the previous request, therefore the options returned `pagination.paginate(...)` must reflect changes only. If there are no more pages, `false` should be returned. - - @example - ``` - import got from 'got'; - - const limit = 10; - - const items = got.paginate('https://example.com/items', { - searchParams: { - limit, - offset: 0 - }, - pagination: { - paginate: ({response, currentItems}) => { - const previousSearchParams = response.request.options.searchParams; - const previousOffset = previousSearchParams.get('offset'); - - if (currentItems.length < limit) { - return false; - } - - return { - searchParams: { - ...previousSearchParams, - offset: Number(previousOffset) + limit, - } - }; - } - } - }); - - console.log('Items from all pages:', items); - ``` - */ - paginate?: (data: PaginateData) => OptionsInit | false; - /** - Checks whether the pagination should continue. - - For example, if you need to stop **before** emitting an entry with some flag, you should use `({item}) => !item.flag`. - - If you want to stop **after** emitting the entry, you should use - `({item, allItems}) => allItems.some(item => item.flag)` instead. - - @default ({item, currentItems, allItems}) => true - */ - shouldContinue?: (data: FilterData) => boolean; - /** - The maximum amount of items that should be emitted. - - @default Infinity - */ - countLimit?: number; - /** - Milliseconds to wait before the next request is triggered. - - @default 0 - */ - backoff?: number; - /** - The maximum amount of request that should be triggered. - Retries on failure are not counted towards this limit. - - For example, it can be helpful during development to avoid an infinite number of requests. - - @default 10000 - */ - requestLimit?: number; - /** - Defines how the property `allItems` in `pagination.paginate`, `pagination.filter` and `pagination.shouldContinue` is managed. - - By default, the property `allItems` is always an empty array. This setting can be helpful to save on memory usage when working with a large dataset. - - When set to `true`, the property `allItems` is an array of the emitted items. - - @default false - */ - stackAllItems?: boolean; -}; -export type SearchParameters = Record; -/** -All parsing methods supported by Got. -*/ -export type ResponseType = 'json' | 'buffer' | 'text'; -type OptionsToSkip = 'searchParameters' | 'followRedirects' | 'auth' | 'toJSON' | 'merge' | 'createNativeRequestOptions' | 'getRequestFunction' | 'getFallbackRequestFunction' | 'freeze'; -export type InternalsType = Except; -export type OptionsError = NodeJS.ErrnoException & { - options?: Options; -}; -export type OptionsInit = Except, 'hooks' | 'retry'> & { - hooks?: Partial; - retry?: Partial; -}; -export default class Options { - private _unixOptions?; - private readonly _internals; - private _merging; - private readonly _init; - constructor(input?: string | URL | OptionsInit, options?: OptionsInit, defaults?: Options); - merge(options?: OptionsInit | Options): void; - /** - Custom request function. - The main purpose of this is to [support HTTP2 using a wrapper](https://github.com/szmarczak/http2-wrapper). - - @default http.request | https.request - */ - get request(): RequestFunction | undefined; - set request(value: RequestFunction | undefined); - /** - An object representing `http`, `https` and `http2` keys for [`http.Agent`](https://nodejs.org/api/http.html#http_class_http_agent), [`https.Agent`](https://nodejs.org/api/https.html#https_class_https_agent) and [`http2wrapper.Agent`](https://github.com/szmarczak/http2-wrapper#new-http2agentoptions) instance. - This is necessary because a request to one protocol might redirect to another. - In such a scenario, Got will switch over to the right protocol agent for you. - - If a key is not present, it will default to a global agent. - - @example - ``` - import got from 'got'; - import HttpAgent from 'agentkeepalive'; - - const {HttpsAgent} = HttpAgent; - - await got('https://sindresorhus.com', { - agent: { - http: new HttpAgent(), - https: new HttpsAgent() - } - }); - ``` - */ - get agent(): Agents; - set agent(value: Agents); - get h2session(): ClientHttp2Session | undefined; - set h2session(value: ClientHttp2Session | undefined); - /** - Decompress the response automatically. - - This will set the `accept-encoding` header to `gzip, deflate, br` unless you set it yourself. - - If this is disabled, a compressed response is returned as a `Buffer`. - This may be useful if you want to handle decompression yourself or stream the raw compressed data. - - @default true - */ - get decompress(): boolean; - set decompress(value: boolean); - /** - Milliseconds to wait for the server to end the response before aborting the request with `got.TimeoutError` error (a.k.a. `request` property). - By default, there's no timeout. - - This also accepts an `object` with the following fields to constrain the duration of each phase of the request lifecycle: - - - `lookup` starts when a socket is assigned and ends when the hostname has been resolved. - Does not apply when using a Unix domain socket. - - `connect` starts when `lookup` completes (or when the socket is assigned if lookup does not apply to the request) and ends when the socket is connected. - - `secureConnect` starts when `connect` completes and ends when the handshaking process completes (HTTPS only). - - `socket` starts when the socket is connected. See [request.setTimeout](https://nodejs.org/api/http.html#http_request_settimeout_timeout_callback). - - `response` starts when the request has been written to the socket and ends when the response headers are received. - - `send` starts when the socket is connected and ends with the request has been written to the socket. - - `request` starts when the request is initiated and ends when the response's end event fires. - */ - get timeout(): Delays; - set timeout(value: Delays); - /** - When specified, `prefixUrl` will be prepended to `url`. - The prefix can be any valid URL, either relative or absolute. - A trailing slash `/` is optional - one will be added automatically. - - __Note__: `prefixUrl` will be ignored if the `url` argument is a URL instance. - - __Note__: Leading slashes in `input` are disallowed when using this option to enforce consistency and avoid confusion. - For example, when the prefix URL is `https://example.com/foo` and the input is `/bar`, there's ambiguity whether the resulting URL would become `https://example.com/foo/bar` or `https://example.com/bar`. - The latter is used by browsers. - - __Tip__: Useful when used with `got.extend()` to create niche-specific Got instances. - - __Tip__: You can change `prefixUrl` using hooks as long as the URL still includes the `prefixUrl`. - If the URL doesn't include it anymore, it will throw. - - @example - ``` - import got from 'got'; - - await got('unicorn', {prefixUrl: 'https://cats.com'}); - //=> 'https://cats.com/unicorn' - - const instance = got.extend({ - prefixUrl: 'https://google.com' - }); - - await instance('unicorn', { - hooks: { - beforeRequest: [ - options => { - options.prefixUrl = 'https://cats.com'; - } - ] - } - }); - //=> 'https://cats.com/unicorn' - ``` - */ - get prefixUrl(): string | URL; - set prefixUrl(value: string | URL); - /** - __Note #1__: The `body` option cannot be used with the `json` or `form` option. - - __Note #2__: If you provide this option, `got.stream()` will be read-only. - - __Note #3__: If you provide a payload with the `GET` or `HEAD` method, it will throw a `TypeError` unless the method is `GET` and the `allowGetBody` option is set to `true`. - - __Note #4__: This option is not enumerable and will not be merged with the instance defaults. - - The `content-length` header will be automatically set if `body` is a `string` / `Buffer` / [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) / [`form-data` instance](https://github.com/form-data/form-data), and `content-length` and `transfer-encoding` are not manually set in `options.headers`. - - Since Got 12, the `content-length` is not automatically set when `body` is a `fs.createReadStream`. - */ - get body(): string | Buffer | Readable | Generator | AsyncGenerator | FormDataLike | undefined; - set body(value: string | Buffer | Readable | Generator | AsyncGenerator | FormDataLike | undefined); - /** - The form body is converted to a query string using [`(new URLSearchParams(object)).toString()`](https://nodejs.org/api/url.html#url_constructor_new_urlsearchparams_obj). - - If the `Content-Type` header is not present, it will be set to `application/x-www-form-urlencoded`. - - __Note #1__: If you provide this option, `got.stream()` will be read-only. - - __Note #2__: This option is not enumerable and will not be merged with the instance defaults. - */ - get form(): Record | undefined; - set form(value: Record | undefined); - /** - JSON body. If the `Content-Type` header is not set, it will be set to `application/json`. - - __Note #1__: If you provide this option, `got.stream()` will be read-only. - - __Note #2__: This option is not enumerable and will not be merged with the instance defaults. - */ - get json(): unknown; - set json(value: unknown); - /** - The URL to request, as a string, a [`https.request` options object](https://nodejs.org/api/https.html#https_https_request_options_callback), or a [WHATWG `URL`](https://nodejs.org/api/url.html#url_class_url). - - Properties from `options` will override properties in the parsed `url`. - - If no protocol is specified, it will throw a `TypeError`. - - __Note__: The query string is **not** parsed as search params. - - @example - ``` - await got('https://example.com/?query=a b'); //=> https://example.com/?query=a%20b - await got('https://example.com/', {searchParams: {query: 'a b'}}); //=> https://example.com/?query=a+b - - // The query string is overridden by `searchParams` - await got('https://example.com/?query=a b', {searchParams: {query: 'a b'}}); //=> https://example.com/?query=a+b - ``` - */ - get url(): string | URL | undefined; - set url(value: string | URL | undefined); - /** - Cookie support. You don't have to care about parsing or how to store them. - - __Note__: If you provide this option, `options.headers.cookie` will be overridden. - */ - get cookieJar(): PromiseCookieJar | ToughCookieJar | undefined; - set cookieJar(value: PromiseCookieJar | ToughCookieJar | undefined); - /** - You can abort the `request` using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController). - - @example - ``` - import got from 'got'; - - const abortController = new AbortController(); - - const request = got('https://httpbin.org/anything', { - signal: abortController.signal - }); - - setTimeout(() => { - abortController.abort(); - }, 100); - ``` - */ - get signal(): AbortSignal | undefined; - set signal(value: AbortSignal | undefined); - /** - Ignore invalid cookies instead of throwing an error. - Only useful when the `cookieJar` option has been set. Not recommended. - - @default false - */ - get ignoreInvalidCookies(): boolean; - set ignoreInvalidCookies(value: boolean); - /** - Query string that will be added to the request URL. - This will override the query string in `url`. - - If you need to pass in an array, you can do it using a `URLSearchParams` instance. - - @example - ``` - import got from 'got'; - - const searchParams = new URLSearchParams([['key', 'a'], ['key', 'b']]); - - await got('https://example.com', {searchParams}); - - console.log(searchParams.toString()); - //=> 'key=a&key=b' - ``` - */ - get searchParams(): string | SearchParameters | URLSearchParams | undefined; - set searchParams(value: string | SearchParameters | URLSearchParams | undefined); - get searchParameters(): unknown; - set searchParameters(_value: unknown); - get dnsLookup(): CacheableLookup['lookup'] | undefined; - set dnsLookup(value: CacheableLookup['lookup'] | undefined); - /** - An instance of [`CacheableLookup`](https://github.com/szmarczak/cacheable-lookup) used for making DNS lookups. - Useful when making lots of requests to different *public* hostnames. - - `CacheableLookup` uses `dns.resolver4(..)` and `dns.resolver6(...)` under the hood and fall backs to `dns.lookup(...)` when the first two fail, which may lead to additional delay. - - __Note__: This should stay disabled when making requests to internal hostnames such as `localhost`, `database.local` etc. - - @default false - */ - get dnsCache(): CacheableLookup | boolean | undefined; - set dnsCache(value: CacheableLookup | boolean | undefined); - /** - User data. `context` is shallow merged and enumerable. If it contains non-enumerable properties they will NOT be merged. - - @example - ``` - import got from 'got'; - - const instance = got.extend({ - hooks: { - beforeRequest: [ - options => { - if (!options.context || !options.context.token) { - throw new Error('Token required'); - } - - options.headers.token = options.context.token; - } - ] - } - }); - - const context = { - token: 'secret' - }; - - const response = await instance('https://httpbin.org/headers', {context}); - - // Let's see the headers - console.log(response.body); - ``` - */ - get context(): Record; - set context(value: Record); - /** - Hooks allow modifications during the request lifecycle. - Hook functions may be async and are run serially. - */ - get hooks(): Hooks; - set hooks(value: Hooks); - /** - Whether redirect responses should be followed automatically. - - Optionally, pass a function to dynamically decide based on the response object. - - Note that if a `303` is sent by the server in response to any request type (`POST`, `DELETE`, etc.), Got will automatically request the resource pointed to in the location header via `GET`. - This is in accordance with [the spec](https://tools.ietf.org/html/rfc7231#section-6.4.4). You can optionally turn on this behavior also for other redirect codes - see `methodRewriting`. - - @default true - */ - get followRedirect(): boolean | ((response: PlainResponse) => boolean); - set followRedirect(value: boolean | ((response: PlainResponse) => boolean)); - get followRedirects(): unknown; - set followRedirects(_value: unknown); - /** - If exceeded, the request will be aborted and a `MaxRedirectsError` will be thrown. - - @default 10 - */ - get maxRedirects(): number; - set maxRedirects(value: number); - /** - A cache adapter instance for storing cached response data. - - @default false - */ - get cache(): string | StorageAdapter | boolean | undefined; - set cache(value: string | StorageAdapter | boolean | undefined); - /** - Determines if a `got.HTTPError` is thrown for unsuccessful responses. - - If this is disabled, requests that encounter an error status code will be resolved with the `response` instead of throwing. - This may be useful if you are checking for resource availability and are expecting error responses. - - @default true - */ - get throwHttpErrors(): boolean; - set throwHttpErrors(value: boolean); - get username(): string; - set username(value: string); - get password(): string; - set password(value: string); - /** - If set to `true`, Got will additionally accept HTTP2 requests. - - It will choose either HTTP/1.1 or HTTP/2 depending on the ALPN protocol. - - __Note__: This option requires Node.js 15.10.0 or newer as HTTP/2 support on older Node.js versions is very buggy. - - __Note__: Overriding `options.request` will disable HTTP2 support. - - @default false - - @example - ``` - import got from 'got'; - - const {headers} = await got('https://nghttp2.org/httpbin/anything', {http2: true}); - - console.log(headers.via); - //=> '2 nghttpx' - ``` - */ - get http2(): boolean; - set http2(value: boolean); - /** - Set this to `true` to allow sending body for the `GET` method. - However, the [HTTP/2 specification](https://tools.ietf.org/html/rfc7540#section-8.1.3) says that `An HTTP GET request includes request header fields and no payload body`, therefore when using the HTTP/2 protocol this option will have no effect. - This option is only meant to interact with non-compliant servers when you have no other choice. - - __Note__: The [RFC 7231](https://tools.ietf.org/html/rfc7231#section-4.3.1) doesn't specify any particular behavior for the GET method having a payload, therefore __it's considered an [anti-pattern](https://en.wikipedia.org/wiki/Anti-pattern)__. - - @default false - */ - get allowGetBody(): boolean; - set allowGetBody(value: boolean); - /** - Request headers. - - Existing headers will be overwritten. Headers set to `undefined` will be omitted. - - @default {} - */ - get headers(): Headers; - set headers(value: Headers); - /** - Specifies if the HTTP request method should be [rewritten as `GET`](https://tools.ietf.org/html/rfc7231#section-6.4) on redirects. - - As the [specification](https://tools.ietf.org/html/rfc7231#section-6.4) prefers to rewrite the HTTP method only on `303` responses, this is Got's default behavior. - Setting `methodRewriting` to `true` will also rewrite `301` and `302` responses, as allowed by the spec. This is the behavior followed by `curl` and browsers. - - __Note__: Got never performs method rewriting on `307` and `308` responses, as this is [explicitly prohibited by the specification](https://www.rfc-editor.org/rfc/rfc7231#section-6.4.7). - - @default false - */ - get methodRewriting(): boolean; - set methodRewriting(value: boolean); - /** - Indicates which DNS record family to use. - - Values: - - `undefined`: IPv4 (if present) or IPv6 - - `4`: Only IPv4 - - `6`: Only IPv6 - - @default undefined - */ - get dnsLookupIpVersion(): DnsLookupIpVersion; - set dnsLookupIpVersion(value: DnsLookupIpVersion); - /** - A function used to parse JSON responses. - - @example - ``` - import got from 'got'; - import Bourne from '@hapi/bourne'; - - const parsed = await got('https://example.com', { - parseJson: text => Bourne.parse(text) - }).json(); - - console.log(parsed); - ``` - */ - get parseJson(): ParseJsonFunction; - set parseJson(value: ParseJsonFunction); - /** - A function used to stringify the body of JSON requests. - - @example - ``` - import got from 'got'; - - await got.post('https://example.com', { - stringifyJson: object => JSON.stringify(object, (key, value) => { - if (key.startsWith('_')) { - return; - } - - return value; - }), - json: { - some: 'payload', - _ignoreMe: 1234 - } - }); - ``` - - @example - ``` - import got from 'got'; - - await got.post('https://example.com', { - stringifyJson: object => JSON.stringify(object, (key, value) => { - if (typeof value === 'number') { - return value.toString(); - } - - return value; - }), - json: { - some: 'payload', - number: 1 - } - }); - ``` - */ - get stringifyJson(): StringifyJsonFunction; - set stringifyJson(value: StringifyJsonFunction); - /** - An object representing `limit`, `calculateDelay`, `methods`, `statusCodes`, `maxRetryAfter` and `errorCodes` fields for maximum retry count, retry handler, allowed methods, allowed status codes, maximum [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time and allowed error codes. - - Delays between retries counts with function `1000 * Math.pow(2, retry) + Math.random() * 100`, where `retry` is attempt number (starts from 1). - - The `calculateDelay` property is a `function` that receives an object with `attemptCount`, `retryOptions`, `error` and `computedValue` properties for current retry count, the retry options, error and default computed value. - The function must return a delay in milliseconds (or a Promise resolving with it) (`0` return value cancels retry). - - By default, it retries *only* on the specified methods, status codes, and on these network errors: - - - `ETIMEDOUT`: One of the [timeout](#timeout) limits were reached. - - `ECONNRESET`: Connection was forcibly closed by a peer. - - `EADDRINUSE`: Could not bind to any free port. - - `ECONNREFUSED`: Connection was refused by the server. - - `EPIPE`: The remote side of the stream being written has been closed. - - `ENOTFOUND`: Couldn't resolve the hostname to an IP address. - - `ENETUNREACH`: No internet connection. - - `EAI_AGAIN`: DNS lookup timed out. - - __Note__: If `maxRetryAfter` is set to `undefined`, it will use `options.timeout`. - __Note__: If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will cancel the request. - */ - get retry(): Partial; - set retry(value: Partial); - /** - From `http.RequestOptions`. - - The IP address used to send the request from. - */ - get localAddress(): string | undefined; - set localAddress(value: string | undefined); - /** - The HTTP method used to make the request. - - @default 'GET' - */ - get method(): Method; - set method(value: Method); - get createConnection(): CreateConnectionFunction | undefined; - set createConnection(value: CreateConnectionFunction | undefined); - /** - From `http-cache-semantics` - - @default {} - */ - get cacheOptions(): CacheOptions; - set cacheOptions(value: CacheOptions); - /** - Options for the advanced HTTPS API. - */ - get https(): HttpsOptions; - set https(value: HttpsOptions); - /** - [Encoding](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings) to be used on `setEncoding` of the response data. - - To get a [`Buffer`](https://nodejs.org/api/buffer.html), you need to set `responseType` to `buffer` instead. - Don't set this option to `null`. - - __Note__: This doesn't affect streams! Instead, you need to do `got.stream(...).setEncoding(encoding)`. - - @default 'utf-8' - */ - get encoding(): BufferEncoding | undefined; - set encoding(value: BufferEncoding | undefined); - /** - When set to `true` the promise will return the Response body instead of the Response object. - - @default false - */ - get resolveBodyOnly(): boolean; - set resolveBodyOnly(value: boolean); - /** - Returns a `Stream` instead of a `Promise`. - This is equivalent to calling `got.stream(url, options?)`. - - @default false - */ - get isStream(): boolean; - set isStream(value: boolean); - /** - The parsing method. - - The promise also has `.text()`, `.json()` and `.buffer()` methods which return another Got promise for the parsed body. - - It's like setting the options to `{responseType: 'json', resolveBodyOnly: true}` but without affecting the main Got promise. - - __Note__: When using streams, this option is ignored. - - @example - ``` - const responsePromise = got(url); - const bufferPromise = responsePromise.buffer(); - const jsonPromise = responsePromise.json(); - - const [response, buffer, json] = Promise.all([responsePromise, bufferPromise, jsonPromise]); - // `response` is an instance of Got Response - // `buffer` is an instance of Buffer - // `json` is an object - ``` - - @example - ``` - // This - const body = await got(url).json(); - - // is semantically the same as this - const body = await got(url, {responseType: 'json', resolveBodyOnly: true}); - ``` - */ - get responseType(): ResponseType; - set responseType(value: ResponseType); - get pagination(): PaginationOptions; - set pagination(value: PaginationOptions); - get auth(): unknown; - set auth(_value: unknown); - get setHost(): boolean; - set setHost(value: boolean); - get maxHeaderSize(): number | undefined; - set maxHeaderSize(value: number | undefined); - get enableUnixSockets(): boolean; - set enableUnixSockets(value: boolean); - toJSON(): { - headers: Headers; - timeout: Delays; - request: RequestFunction | undefined; - username: string; - password: string; - json: unknown; - followRedirect: boolean | ((response: PlainResponse) => boolean); - retry: Partial; - agent: Agents; - h2session: http2wrapper.ClientHttp2Session | undefined; - decompress: boolean; - prefixUrl: string | URL; - body: string | Readable | Buffer | Generator | AsyncGenerator | FormDataLike | undefined; - form: Record | undefined; - url: string | URL | undefined; - cookieJar: PromiseCookieJar | ToughCookieJar | undefined; - signal: AbortSignal | undefined; - ignoreInvalidCookies: boolean; - searchParams: string | URLSearchParams | SearchParameters | undefined; - dnsLookup: { - (hostname: string, family: import("cacheable-lookup").IPFamily, callback: (error: NodeJS.ErrnoException | null, address: string, family: import("cacheable-lookup").IPFamily) => void): void; - (hostname: string, callback: (error: NodeJS.ErrnoException | null, address: string, family: import("cacheable-lookup").IPFamily) => void): void; - (hostname: string, options: import("cacheable-lookup").LookupOptions & { - all: true; - }, callback: (error: NodeJS.ErrnoException | null, result: readonly import("cacheable-lookup").EntryObject[]) => void): void; - (hostname: string, options: import("cacheable-lookup").LookupOptions, callback: (error: NodeJS.ErrnoException | null, address: string, family: import("cacheable-lookup").IPFamily) => void): void; - } | undefined; - dnsCache: boolean | CacheableLookup | undefined; - context: Record; - hooks: Hooks; - maxRedirects: number; - cache: string | boolean | StorageAdapter | undefined; - throwHttpErrors: boolean; - http2: boolean; - allowGetBody: boolean; - methodRewriting: boolean; - dnsLookupIpVersion: DnsLookupIpVersion; - parseJson: ParseJsonFunction; - stringifyJson: StringifyJsonFunction; - localAddress: string | undefined; - method: Method; - createConnection: CreateConnectionFunction | undefined; - cacheOptions: CacheOptions; - https: HttpsOptions; - encoding: BufferEncoding | undefined; - resolveBodyOnly: boolean; - isStream: boolean; - responseType: ResponseType; - pagination: PaginationOptions; - setHost: boolean; - maxHeaderSize: number | undefined; - enableUnixSockets: boolean; - }; - createNativeRequestOptions(): { - ALPNProtocols: string[] | undefined; - ca: string | Buffer | (string | Buffer)[] | undefined; - cert: string | Buffer | (string | Buffer)[] | undefined; - key: string | Buffer | (string | Buffer | import("tls").KeyObject)[] | undefined; - passphrase: string | undefined; - pfx: PfxType; - rejectUnauthorized: boolean | undefined; - checkServerIdentity: typeof checkServerIdentity | CheckServerIdentityFunction; - ciphers: string | undefined; - honorCipherOrder: boolean | undefined; - minVersion: import("tls").SecureVersion | undefined; - maxVersion: import("tls").SecureVersion | undefined; - sigalgs: string | undefined; - sessionTimeout: number | undefined; - dhparam: string | Buffer | undefined; - ecdhCurve: string | undefined; - crl: string | Buffer | (string | Buffer)[] | undefined; - lookup: { - (hostname: string, family: import("cacheable-lookup").IPFamily, callback: (error: NodeJS.ErrnoException | null, address: string, family: import("cacheable-lookup").IPFamily) => void): void; - (hostname: string, callback: (error: NodeJS.ErrnoException | null, address: string, family: import("cacheable-lookup").IPFamily) => void): void; - (hostname: string, options: import("cacheable-lookup").LookupOptions & { - all: true; - }, callback: (error: NodeJS.ErrnoException | null, result: readonly import("cacheable-lookup").EntryObject[]) => void): void; - (hostname: string, options: import("cacheable-lookup").LookupOptions, callback: (error: NodeJS.ErrnoException | null, address: string, family: import("cacheable-lookup").IPFamily) => void): void; - } | undefined; - family: DnsLookupIpVersion; - agent: false | http.Agent | Agents | undefined; - setHost: boolean; - method: Method; - maxHeaderSize: number | undefined; - localAddress: string | undefined; - headers: Headers; - createConnection: CreateConnectionFunction | undefined; - timeout: number | undefined; - h2session: http2wrapper.ClientHttp2Session | undefined; - _defaultAgent?: http.Agent | undefined; - auth?: string | null | undefined; - defaultPort?: string | number | undefined; - hints?: number | undefined; - host?: string | null | undefined; - hostname?: string | null | undefined; - insecureHTTPParser?: boolean | undefined; - localPort?: number | undefined; - path?: string | null | undefined; - port?: string | number | null | undefined; - protocol?: string | null | undefined; - signal?: AbortSignal | undefined; - socketPath?: string | undefined; - uniqueHeaders?: (string | string[])[] | undefined; - joinDuplicateHeaders?: boolean | undefined; - ALPNCallback?: ((arg: { - servername: string; - protocols: string[]; - }) => string | undefined) | undefined; - clientCertEngine?: string | undefined; - privateKeyEngine?: string | undefined; - privateKeyIdentifier?: string | undefined; - secureOptions?: number | undefined; - secureProtocol?: string | undefined; - sessionIdContext?: string | undefined; - ticketKeys?: Buffer | undefined; - servername?: string | undefined; - shared?: boolean | undefined; - cacheHeuristic?: number | undefined; - immutableMinTimeToLive?: number | undefined; - ignoreCargoCult?: boolean | undefined; - }; - getRequestFunction(): RequestFunction | typeof https.request | undefined; - getFallbackRequestFunction(): RequestFunction | typeof https.request | undefined; - freeze(): void; -} -export {}; diff --git a/setup-pandoc/node_modules/got/dist/source/core/options.js b/setup-pandoc/node_modules/got/dist/source/core/options.js deleted file mode 100644 index 6b5874518..000000000 --- a/setup-pandoc/node_modules/got/dist/source/core/options.js +++ /dev/null @@ -1,1635 +0,0 @@ -import process from 'node:process'; -import { promisify, inspect } from 'node:util'; -import { checkServerIdentity } from 'node:tls'; -// DO NOT use destructuring for `https.request` and `http.request` as it's not compatible with `nock`. -import https from 'node:https'; -import http from 'node:http'; -import is, { assert } from '@sindresorhus/is'; -import lowercaseKeys from 'lowercase-keys'; -import CacheableLookup from 'cacheable-lookup'; -import http2wrapper from 'http2-wrapper'; -import { isFormData } from 'form-data-encoder'; -import parseLinkHeader from './parse-link-header.js'; -const [major, minor] = process.versions.node.split('.').map(Number); -function validateSearchParameters(searchParameters) { - // eslint-disable-next-line guard-for-in - for (const key in searchParameters) { - const value = searchParameters[key]; - assert.any([is.string, is.number, is.boolean, is.null_, is.undefined], value); - } -} -const globalCache = new Map(); -let globalDnsCache; -const getGlobalDnsCache = () => { - if (globalDnsCache) { - return globalDnsCache; - } - globalDnsCache = new CacheableLookup(); - return globalDnsCache; -}; -const defaultInternals = { - request: undefined, - agent: { - http: undefined, - https: undefined, - http2: undefined, - }, - h2session: undefined, - decompress: true, - timeout: { - connect: undefined, - lookup: undefined, - read: undefined, - request: undefined, - response: undefined, - secureConnect: undefined, - send: undefined, - socket: undefined, - }, - prefixUrl: '', - body: undefined, - form: undefined, - json: undefined, - cookieJar: undefined, - ignoreInvalidCookies: false, - searchParams: undefined, - dnsLookup: undefined, - dnsCache: undefined, - context: {}, - hooks: { - init: [], - beforeRequest: [], - beforeError: [], - beforeRedirect: [], - beforeRetry: [], - afterResponse: [], - }, - followRedirect: true, - maxRedirects: 10, - cache: undefined, - throwHttpErrors: true, - username: '', - password: '', - http2: false, - allowGetBody: false, - headers: { - 'user-agent': 'got (https://github.com/sindresorhus/got)', - }, - methodRewriting: false, - dnsLookupIpVersion: undefined, - parseJson: JSON.parse, - stringifyJson: JSON.stringify, - retry: { - limit: 2, - methods: [ - 'GET', - 'PUT', - 'HEAD', - 'DELETE', - 'OPTIONS', - 'TRACE', - ], - statusCodes: [ - 408, - 413, - 429, - 500, - 502, - 503, - 504, - 521, - 522, - 524, - ], - errorCodes: [ - 'ETIMEDOUT', - 'ECONNRESET', - 'EADDRINUSE', - 'ECONNREFUSED', - 'EPIPE', - 'ENOTFOUND', - 'ENETUNREACH', - 'EAI_AGAIN', - ], - maxRetryAfter: undefined, - calculateDelay: ({ computedValue }) => computedValue, - backoffLimit: Number.POSITIVE_INFINITY, - noise: 100, - }, - localAddress: undefined, - method: 'GET', - createConnection: undefined, - cacheOptions: { - shared: undefined, - cacheHeuristic: undefined, - immutableMinTimeToLive: undefined, - ignoreCargoCult: undefined, - }, - https: { - alpnProtocols: undefined, - rejectUnauthorized: undefined, - checkServerIdentity: undefined, - certificateAuthority: undefined, - key: undefined, - certificate: undefined, - passphrase: undefined, - pfx: undefined, - ciphers: undefined, - honorCipherOrder: undefined, - minVersion: undefined, - maxVersion: undefined, - signatureAlgorithms: undefined, - tlsSessionLifetime: undefined, - dhparam: undefined, - ecdhCurve: undefined, - certificateRevocationLists: undefined, - }, - encoding: undefined, - resolveBodyOnly: false, - isStream: false, - responseType: 'text', - url: undefined, - pagination: { - transform(response) { - if (response.request.options.responseType === 'json') { - return response.body; - } - return JSON.parse(response.body); - }, - paginate({ response }) { - const rawLinkHeader = response.headers.link; - if (typeof rawLinkHeader !== 'string' || rawLinkHeader.trim() === '') { - return false; - } - const parsed = parseLinkHeader(rawLinkHeader); - const next = parsed.find(entry => entry.parameters.rel === 'next' || entry.parameters.rel === '"next"'); - if (next) { - return { - url: new URL(next.reference, response.url), - }; - } - return false; - }, - filter: () => true, - shouldContinue: () => true, - countLimit: Number.POSITIVE_INFINITY, - backoff: 0, - requestLimit: 10000, - stackAllItems: false, - }, - setHost: true, - maxHeaderSize: undefined, - signal: undefined, - enableUnixSockets: false, -}; -const cloneInternals = (internals) => { - const { hooks, retry } = internals; - const result = { - ...internals, - context: { ...internals.context }, - cacheOptions: { ...internals.cacheOptions }, - https: { ...internals.https }, - agent: { ...internals.agent }, - headers: { ...internals.headers }, - retry: { - ...retry, - errorCodes: [...retry.errorCodes], - methods: [...retry.methods], - statusCodes: [...retry.statusCodes], - }, - timeout: { ...internals.timeout }, - hooks: { - init: [...hooks.init], - beforeRequest: [...hooks.beforeRequest], - beforeError: [...hooks.beforeError], - beforeRedirect: [...hooks.beforeRedirect], - beforeRetry: [...hooks.beforeRetry], - afterResponse: [...hooks.afterResponse], - }, - searchParams: internals.searchParams ? new URLSearchParams(internals.searchParams) : undefined, - pagination: { ...internals.pagination }, - }; - if (result.url !== undefined) { - result.prefixUrl = ''; - } - return result; -}; -const cloneRaw = (raw) => { - const { hooks, retry } = raw; - const result = { ...raw }; - if (is.object(raw.context)) { - result.context = { ...raw.context }; - } - if (is.object(raw.cacheOptions)) { - result.cacheOptions = { ...raw.cacheOptions }; - } - if (is.object(raw.https)) { - result.https = { ...raw.https }; - } - if (is.object(raw.cacheOptions)) { - result.cacheOptions = { ...result.cacheOptions }; - } - if (is.object(raw.agent)) { - result.agent = { ...raw.agent }; - } - if (is.object(raw.headers)) { - result.headers = { ...raw.headers }; - } - if (is.object(retry)) { - result.retry = { ...retry }; - if (is.array(retry.errorCodes)) { - result.retry.errorCodes = [...retry.errorCodes]; - } - if (is.array(retry.methods)) { - result.retry.methods = [...retry.methods]; - } - if (is.array(retry.statusCodes)) { - result.retry.statusCodes = [...retry.statusCodes]; - } - } - if (is.object(raw.timeout)) { - result.timeout = { ...raw.timeout }; - } - if (is.object(hooks)) { - result.hooks = { - ...hooks, - }; - if (is.array(hooks.init)) { - result.hooks.init = [...hooks.init]; - } - if (is.array(hooks.beforeRequest)) { - result.hooks.beforeRequest = [...hooks.beforeRequest]; - } - if (is.array(hooks.beforeError)) { - result.hooks.beforeError = [...hooks.beforeError]; - } - if (is.array(hooks.beforeRedirect)) { - result.hooks.beforeRedirect = [...hooks.beforeRedirect]; - } - if (is.array(hooks.beforeRetry)) { - result.hooks.beforeRetry = [...hooks.beforeRetry]; - } - if (is.array(hooks.afterResponse)) { - result.hooks.afterResponse = [...hooks.afterResponse]; - } - } - // TODO: raw.searchParams - if (is.object(raw.pagination)) { - result.pagination = { ...raw.pagination }; - } - return result; -}; -const getHttp2TimeoutOption = (internals) => { - const delays = [internals.timeout.socket, internals.timeout.connect, internals.timeout.lookup, internals.timeout.request, internals.timeout.secureConnect].filter(delay => typeof delay === 'number'); - if (delays.length > 0) { - return Math.min(...delays); - } - return undefined; -}; -const init = (options, withOptions, self) => { - const initHooks = options.hooks?.init; - if (initHooks) { - for (const hook of initHooks) { - hook(withOptions, self); - } - } -}; -export default class Options { - _unixOptions; - _internals; - _merging; - _init; - constructor(input, options, defaults) { - assert.any([is.string, is.urlInstance, is.object, is.undefined], input); - assert.any([is.object, is.undefined], options); - assert.any([is.object, is.undefined], defaults); - if (input instanceof Options || options instanceof Options) { - throw new TypeError('The defaults must be passed as the third argument'); - } - this._internals = cloneInternals(defaults?._internals ?? defaults ?? defaultInternals); - this._init = [...(defaults?._init ?? [])]; - this._merging = false; - this._unixOptions = undefined; - // This rule allows `finally` to be considered more important. - // Meaning no matter the error thrown in the `try` block, - // if `finally` throws then the `finally` error will be thrown. - // - // Yes, we want this. If we set `url` first, then the `url.searchParams` - // would get merged. Instead we set the `searchParams` first, then - // `url.searchParams` is overwritten as expected. - // - /* eslint-disable no-unsafe-finally */ - try { - if (is.plainObject(input)) { - try { - this.merge(input); - this.merge(options); - } - finally { - this.url = input.url; - } - } - else { - try { - this.merge(options); - } - finally { - if (options?.url !== undefined) { - if (input === undefined) { - this.url = options.url; - } - else { - throw new TypeError('The `url` option is mutually exclusive with the `input` argument'); - } - } - else if (input !== undefined) { - this.url = input; - } - } - } - } - catch (error) { - error.options = this; - throw error; - } - /* eslint-enable no-unsafe-finally */ - } - merge(options) { - if (!options) { - return; - } - if (options instanceof Options) { - for (const init of options._init) { - this.merge(init); - } - return; - } - options = cloneRaw(options); - init(this, options, this); - init(options, options, this); - this._merging = true; - // Always merge `isStream` first - if ('isStream' in options) { - this.isStream = options.isStream; - } - try { - let push = false; - for (const key in options) { - // `got.extend()` options - if (key === 'mutableDefaults' || key === 'handlers') { - continue; - } - // Never merge `url` - if (key === 'url') { - continue; - } - if (!(key in this)) { - throw new Error(`Unexpected option: ${key}`); - } - // @ts-expect-error Type 'unknown' is not assignable to type 'never'. - const value = options[key]; - if (value === undefined) { - continue; - } - // @ts-expect-error Type 'unknown' is not assignable to type 'never'. - this[key] = value; - push = true; - } - if (push) { - this._init.push(options); - } - } - finally { - this._merging = false; - } - } - /** - Custom request function. - The main purpose of this is to [support HTTP2 using a wrapper](https://github.com/szmarczak/http2-wrapper). - - @default http.request | https.request - */ - get request() { - return this._internals.request; - } - set request(value) { - assert.any([is.function_, is.undefined], value); - this._internals.request = value; - } - /** - An object representing `http`, `https` and `http2` keys for [`http.Agent`](https://nodejs.org/api/http.html#http_class_http_agent), [`https.Agent`](https://nodejs.org/api/https.html#https_class_https_agent) and [`http2wrapper.Agent`](https://github.com/szmarczak/http2-wrapper#new-http2agentoptions) instance. - This is necessary because a request to one protocol might redirect to another. - In such a scenario, Got will switch over to the right protocol agent for you. - - If a key is not present, it will default to a global agent. - - @example - ``` - import got from 'got'; - import HttpAgent from 'agentkeepalive'; - - const {HttpsAgent} = HttpAgent; - - await got('https://sindresorhus.com', { - agent: { - http: new HttpAgent(), - https: new HttpsAgent() - } - }); - ``` - */ - get agent() { - return this._internals.agent; - } - set agent(value) { - assert.plainObject(value); - // eslint-disable-next-line guard-for-in - for (const key in value) { - if (!(key in this._internals.agent)) { - throw new TypeError(`Unexpected agent option: ${key}`); - } - // @ts-expect-error - No idea why `value[key]` doesn't work here. - assert.any([is.object, is.undefined], value[key]); - } - if (this._merging) { - Object.assign(this._internals.agent, value); - } - else { - this._internals.agent = { ...value }; - } - } - get h2session() { - return this._internals.h2session; - } - set h2session(value) { - this._internals.h2session = value; - } - /** - Decompress the response automatically. - - This will set the `accept-encoding` header to `gzip, deflate, br` unless you set it yourself. - - If this is disabled, a compressed response is returned as a `Buffer`. - This may be useful if you want to handle decompression yourself or stream the raw compressed data. - - @default true - */ - get decompress() { - return this._internals.decompress; - } - set decompress(value) { - assert.boolean(value); - this._internals.decompress = value; - } - /** - Milliseconds to wait for the server to end the response before aborting the request with `got.TimeoutError` error (a.k.a. `request` property). - By default, there's no timeout. - - This also accepts an `object` with the following fields to constrain the duration of each phase of the request lifecycle: - - - `lookup` starts when a socket is assigned and ends when the hostname has been resolved. - Does not apply when using a Unix domain socket. - - `connect` starts when `lookup` completes (or when the socket is assigned if lookup does not apply to the request) and ends when the socket is connected. - - `secureConnect` starts when `connect` completes and ends when the handshaking process completes (HTTPS only). - - `socket` starts when the socket is connected. See [request.setTimeout](https://nodejs.org/api/http.html#http_request_settimeout_timeout_callback). - - `response` starts when the request has been written to the socket and ends when the response headers are received. - - `send` starts when the socket is connected and ends with the request has been written to the socket. - - `request` starts when the request is initiated and ends when the response's end event fires. - */ - get timeout() { - // We always return `Delays` here. - // It has to be `Delays | number`, otherwise TypeScript will error because the getter and the setter have incompatible types. - return this._internals.timeout; - } - set timeout(value) { - assert.plainObject(value); - // eslint-disable-next-line guard-for-in - for (const key in value) { - if (!(key in this._internals.timeout)) { - throw new Error(`Unexpected timeout option: ${key}`); - } - // @ts-expect-error - No idea why `value[key]` doesn't work here. - assert.any([is.number, is.undefined], value[key]); - } - if (this._merging) { - Object.assign(this._internals.timeout, value); - } - else { - this._internals.timeout = { ...value }; - } - } - /** - When specified, `prefixUrl` will be prepended to `url`. - The prefix can be any valid URL, either relative or absolute. - A trailing slash `/` is optional - one will be added automatically. - - __Note__: `prefixUrl` will be ignored if the `url` argument is a URL instance. - - __Note__: Leading slashes in `input` are disallowed when using this option to enforce consistency and avoid confusion. - For example, when the prefix URL is `https://example.com/foo` and the input is `/bar`, there's ambiguity whether the resulting URL would become `https://example.com/foo/bar` or `https://example.com/bar`. - The latter is used by browsers. - - __Tip__: Useful when used with `got.extend()` to create niche-specific Got instances. - - __Tip__: You can change `prefixUrl` using hooks as long as the URL still includes the `prefixUrl`. - If the URL doesn't include it anymore, it will throw. - - @example - ``` - import got from 'got'; - - await got('unicorn', {prefixUrl: 'https://cats.com'}); - //=> 'https://cats.com/unicorn' - - const instance = got.extend({ - prefixUrl: 'https://google.com' - }); - - await instance('unicorn', { - hooks: { - beforeRequest: [ - options => { - options.prefixUrl = 'https://cats.com'; - } - ] - } - }); - //=> 'https://cats.com/unicorn' - ``` - */ - get prefixUrl() { - // We always return `string` here. - // It has to be `string | URL`, otherwise TypeScript will error because the getter and the setter have incompatible types. - return this._internals.prefixUrl; - } - set prefixUrl(value) { - assert.any([is.string, is.urlInstance], value); - if (value === '') { - this._internals.prefixUrl = ''; - return; - } - value = value.toString(); - if (!value.endsWith('/')) { - value += '/'; - } - if (this._internals.prefixUrl && this._internals.url) { - const { href } = this._internals.url; - this._internals.url.href = value + href.slice(this._internals.prefixUrl.length); - } - this._internals.prefixUrl = value; - } - /** - __Note #1__: The `body` option cannot be used with the `json` or `form` option. - - __Note #2__: If you provide this option, `got.stream()` will be read-only. - - __Note #3__: If you provide a payload with the `GET` or `HEAD` method, it will throw a `TypeError` unless the method is `GET` and the `allowGetBody` option is set to `true`. - - __Note #4__: This option is not enumerable and will not be merged with the instance defaults. - - The `content-length` header will be automatically set if `body` is a `string` / `Buffer` / [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) / [`form-data` instance](https://github.com/form-data/form-data), and `content-length` and `transfer-encoding` are not manually set in `options.headers`. - - Since Got 12, the `content-length` is not automatically set when `body` is a `fs.createReadStream`. - */ - get body() { - return this._internals.body; - } - set body(value) { - assert.any([is.string, is.buffer, is.nodeStream, is.generator, is.asyncGenerator, isFormData, is.undefined], value); - if (is.nodeStream(value)) { - assert.truthy(value.readable); - } - if (value !== undefined) { - assert.undefined(this._internals.form); - assert.undefined(this._internals.json); - } - this._internals.body = value; - } - /** - The form body is converted to a query string using [`(new URLSearchParams(object)).toString()`](https://nodejs.org/api/url.html#url_constructor_new_urlsearchparams_obj). - - If the `Content-Type` header is not present, it will be set to `application/x-www-form-urlencoded`. - - __Note #1__: If you provide this option, `got.stream()` will be read-only. - - __Note #2__: This option is not enumerable and will not be merged with the instance defaults. - */ - get form() { - return this._internals.form; - } - set form(value) { - assert.any([is.plainObject, is.undefined], value); - if (value !== undefined) { - assert.undefined(this._internals.body); - assert.undefined(this._internals.json); - } - this._internals.form = value; - } - /** - JSON body. If the `Content-Type` header is not set, it will be set to `application/json`. - - __Note #1__: If you provide this option, `got.stream()` will be read-only. - - __Note #2__: This option is not enumerable and will not be merged with the instance defaults. - */ - get json() { - return this._internals.json; - } - set json(value) { - if (value !== undefined) { - assert.undefined(this._internals.body); - assert.undefined(this._internals.form); - } - this._internals.json = value; - } - /** - The URL to request, as a string, a [`https.request` options object](https://nodejs.org/api/https.html#https_https_request_options_callback), or a [WHATWG `URL`](https://nodejs.org/api/url.html#url_class_url). - - Properties from `options` will override properties in the parsed `url`. - - If no protocol is specified, it will throw a `TypeError`. - - __Note__: The query string is **not** parsed as search params. - - @example - ``` - await got('https://example.com/?query=a b'); //=> https://example.com/?query=a%20b - await got('https://example.com/', {searchParams: {query: 'a b'}}); //=> https://example.com/?query=a+b - - // The query string is overridden by `searchParams` - await got('https://example.com/?query=a b', {searchParams: {query: 'a b'}}); //=> https://example.com/?query=a+b - ``` - */ - get url() { - return this._internals.url; - } - set url(value) { - assert.any([is.string, is.urlInstance, is.undefined], value); - if (value === undefined) { - this._internals.url = undefined; - return; - } - if (is.string(value) && value.startsWith('/')) { - throw new Error('`url` must not start with a slash'); - } - const urlString = `${this.prefixUrl}${value.toString()}`; - const url = new URL(urlString); - this._internals.url = url; - if (url.protocol === 'unix:') { - url.href = `http://unix${url.pathname}${url.search}`; - } - if (url.protocol !== 'http:' && url.protocol !== 'https:') { - const error = new Error(`Unsupported protocol: ${url.protocol}`); - error.code = 'ERR_UNSUPPORTED_PROTOCOL'; - throw error; - } - if (this._internals.username) { - url.username = this._internals.username; - this._internals.username = ''; - } - if (this._internals.password) { - url.password = this._internals.password; - this._internals.password = ''; - } - if (this._internals.searchParams) { - url.search = this._internals.searchParams.toString(); - this._internals.searchParams = undefined; - } - if (url.hostname === 'unix') { - if (!this._internals.enableUnixSockets) { - throw new Error('Using UNIX domain sockets but option `enableUnixSockets` is not enabled'); - } - const matches = /(?.+?):(?.+)/.exec(`${url.pathname}${url.search}`); - if (matches?.groups) { - const { socketPath, path } = matches.groups; - this._unixOptions = { - socketPath, - path, - host: '', - }; - } - else { - this._unixOptions = undefined; - } - return; - } - this._unixOptions = undefined; - } - /** - Cookie support. You don't have to care about parsing or how to store them. - - __Note__: If you provide this option, `options.headers.cookie` will be overridden. - */ - get cookieJar() { - return this._internals.cookieJar; - } - set cookieJar(value) { - assert.any([is.object, is.undefined], value); - if (value === undefined) { - this._internals.cookieJar = undefined; - return; - } - let { setCookie, getCookieString } = value; - assert.function_(setCookie); - assert.function_(getCookieString); - /* istanbul ignore next: Horrible `tough-cookie` v3 check */ - if (setCookie.length === 4 && getCookieString.length === 0) { - setCookie = promisify(setCookie.bind(value)); - getCookieString = promisify(getCookieString.bind(value)); - this._internals.cookieJar = { - setCookie, - getCookieString: getCookieString, - }; - } - else { - this._internals.cookieJar = value; - } - } - /** - You can abort the `request` using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController). - - @example - ``` - import got from 'got'; - - const abortController = new AbortController(); - - const request = got('https://httpbin.org/anything', { - signal: abortController.signal - }); - - setTimeout(() => { - abortController.abort(); - }, 100); - ``` - */ - get signal() { - return this._internals.signal; - } - set signal(value) { - assert.object(value); - this._internals.signal = value; - } - /** - Ignore invalid cookies instead of throwing an error. - Only useful when the `cookieJar` option has been set. Not recommended. - - @default false - */ - get ignoreInvalidCookies() { - return this._internals.ignoreInvalidCookies; - } - set ignoreInvalidCookies(value) { - assert.boolean(value); - this._internals.ignoreInvalidCookies = value; - } - /** - Query string that will be added to the request URL. - This will override the query string in `url`. - - If you need to pass in an array, you can do it using a `URLSearchParams` instance. - - @example - ``` - import got from 'got'; - - const searchParams = new URLSearchParams([['key', 'a'], ['key', 'b']]); - - await got('https://example.com', {searchParams}); - - console.log(searchParams.toString()); - //=> 'key=a&key=b' - ``` - */ - get searchParams() { - if (this._internals.url) { - return this._internals.url.searchParams; - } - if (this._internals.searchParams === undefined) { - this._internals.searchParams = new URLSearchParams(); - } - return this._internals.searchParams; - } - set searchParams(value) { - assert.any([is.string, is.object, is.undefined], value); - const url = this._internals.url; - if (value === undefined) { - this._internals.searchParams = undefined; - if (url) { - url.search = ''; - } - return; - } - const searchParameters = this.searchParams; - let updated; - if (is.string(value)) { - updated = new URLSearchParams(value); - } - else if (value instanceof URLSearchParams) { - updated = value; - } - else { - validateSearchParameters(value); - updated = new URLSearchParams(); - // eslint-disable-next-line guard-for-in - for (const key in value) { - const entry = value[key]; - if (entry === null) { - updated.append(key, ''); - } - else if (entry === undefined) { - searchParameters.delete(key); - } - else { - updated.append(key, entry); - } - } - } - if (this._merging) { - // These keys will be replaced - for (const key of updated.keys()) { - searchParameters.delete(key); - } - for (const [key, value] of updated) { - searchParameters.append(key, value); - } - } - else if (url) { - url.search = searchParameters.toString(); - } - else { - this._internals.searchParams = searchParameters; - } - } - get searchParameters() { - throw new Error('The `searchParameters` option does not exist. Use `searchParams` instead.'); - } - set searchParameters(_value) { - throw new Error('The `searchParameters` option does not exist. Use `searchParams` instead.'); - } - get dnsLookup() { - return this._internals.dnsLookup; - } - set dnsLookup(value) { - assert.any([is.function_, is.undefined], value); - this._internals.dnsLookup = value; - } - /** - An instance of [`CacheableLookup`](https://github.com/szmarczak/cacheable-lookup) used for making DNS lookups. - Useful when making lots of requests to different *public* hostnames. - - `CacheableLookup` uses `dns.resolver4(..)` and `dns.resolver6(...)` under the hood and fall backs to `dns.lookup(...)` when the first two fail, which may lead to additional delay. - - __Note__: This should stay disabled when making requests to internal hostnames such as `localhost`, `database.local` etc. - - @default false - */ - get dnsCache() { - return this._internals.dnsCache; - } - set dnsCache(value) { - assert.any([is.object, is.boolean, is.undefined], value); - if (value === true) { - this._internals.dnsCache = getGlobalDnsCache(); - } - else if (value === false) { - this._internals.dnsCache = undefined; - } - else { - this._internals.dnsCache = value; - } - } - /** - User data. `context` is shallow merged and enumerable. If it contains non-enumerable properties they will NOT be merged. - - @example - ``` - import got from 'got'; - - const instance = got.extend({ - hooks: { - beforeRequest: [ - options => { - if (!options.context || !options.context.token) { - throw new Error('Token required'); - } - - options.headers.token = options.context.token; - } - ] - } - }); - - const context = { - token: 'secret' - }; - - const response = await instance('https://httpbin.org/headers', {context}); - - // Let's see the headers - console.log(response.body); - ``` - */ - get context() { - return this._internals.context; - } - set context(value) { - assert.object(value); - if (this._merging) { - Object.assign(this._internals.context, value); - } - else { - this._internals.context = { ...value }; - } - } - /** - Hooks allow modifications during the request lifecycle. - Hook functions may be async and are run serially. - */ - get hooks() { - return this._internals.hooks; - } - set hooks(value) { - assert.object(value); - // eslint-disable-next-line guard-for-in - for (const knownHookEvent in value) { - if (!(knownHookEvent in this._internals.hooks)) { - throw new Error(`Unexpected hook event: ${knownHookEvent}`); - } - const typedKnownHookEvent = knownHookEvent; - const hooks = value[typedKnownHookEvent]; - assert.any([is.array, is.undefined], hooks); - if (hooks) { - for (const hook of hooks) { - assert.function_(hook); - } - } - if (this._merging) { - if (hooks) { - // @ts-expect-error FIXME - this._internals.hooks[typedKnownHookEvent].push(...hooks); - } - } - else { - if (!hooks) { - throw new Error(`Missing hook event: ${knownHookEvent}`); - } - // @ts-expect-error FIXME - this._internals.hooks[knownHookEvent] = [...hooks]; - } - } - } - /** - Whether redirect responses should be followed automatically. - - Optionally, pass a function to dynamically decide based on the response object. - - Note that if a `303` is sent by the server in response to any request type (`POST`, `DELETE`, etc.), Got will automatically request the resource pointed to in the location header via `GET`. - This is in accordance with [the spec](https://tools.ietf.org/html/rfc7231#section-6.4.4). You can optionally turn on this behavior also for other redirect codes - see `methodRewriting`. - - @default true - */ - get followRedirect() { - return this._internals.followRedirect; - } - set followRedirect(value) { - assert.any([is.boolean, is.function_], value); - this._internals.followRedirect = value; - } - get followRedirects() { - throw new TypeError('The `followRedirects` option does not exist. Use `followRedirect` instead.'); - } - set followRedirects(_value) { - throw new TypeError('The `followRedirects` option does not exist. Use `followRedirect` instead.'); - } - /** - If exceeded, the request will be aborted and a `MaxRedirectsError` will be thrown. - - @default 10 - */ - get maxRedirects() { - return this._internals.maxRedirects; - } - set maxRedirects(value) { - assert.number(value); - this._internals.maxRedirects = value; - } - /** - A cache adapter instance for storing cached response data. - - @default false - */ - get cache() { - return this._internals.cache; - } - set cache(value) { - assert.any([is.object, is.string, is.boolean, is.undefined], value); - if (value === true) { - this._internals.cache = globalCache; - } - else if (value === false) { - this._internals.cache = undefined; - } - else { - this._internals.cache = value; - } - } - /** - Determines if a `got.HTTPError` is thrown for unsuccessful responses. - - If this is disabled, requests that encounter an error status code will be resolved with the `response` instead of throwing. - This may be useful if you are checking for resource availability and are expecting error responses. - - @default true - */ - get throwHttpErrors() { - return this._internals.throwHttpErrors; - } - set throwHttpErrors(value) { - assert.boolean(value); - this._internals.throwHttpErrors = value; - } - get username() { - const url = this._internals.url; - const value = url ? url.username : this._internals.username; - return decodeURIComponent(value); - } - set username(value) { - assert.string(value); - const url = this._internals.url; - const fixedValue = encodeURIComponent(value); - if (url) { - url.username = fixedValue; - } - else { - this._internals.username = fixedValue; - } - } - get password() { - const url = this._internals.url; - const value = url ? url.password : this._internals.password; - return decodeURIComponent(value); - } - set password(value) { - assert.string(value); - const url = this._internals.url; - const fixedValue = encodeURIComponent(value); - if (url) { - url.password = fixedValue; - } - else { - this._internals.password = fixedValue; - } - } - /** - If set to `true`, Got will additionally accept HTTP2 requests. - - It will choose either HTTP/1.1 or HTTP/2 depending on the ALPN protocol. - - __Note__: This option requires Node.js 15.10.0 or newer as HTTP/2 support on older Node.js versions is very buggy. - - __Note__: Overriding `options.request` will disable HTTP2 support. - - @default false - - @example - ``` - import got from 'got'; - - const {headers} = await got('https://nghttp2.org/httpbin/anything', {http2: true}); - - console.log(headers.via); - //=> '2 nghttpx' - ``` - */ - get http2() { - return this._internals.http2; - } - set http2(value) { - assert.boolean(value); - this._internals.http2 = value; - } - /** - Set this to `true` to allow sending body for the `GET` method. - However, the [HTTP/2 specification](https://tools.ietf.org/html/rfc7540#section-8.1.3) says that `An HTTP GET request includes request header fields and no payload body`, therefore when using the HTTP/2 protocol this option will have no effect. - This option is only meant to interact with non-compliant servers when you have no other choice. - - __Note__: The [RFC 7231](https://tools.ietf.org/html/rfc7231#section-4.3.1) doesn't specify any particular behavior for the GET method having a payload, therefore __it's considered an [anti-pattern](https://en.wikipedia.org/wiki/Anti-pattern)__. - - @default false - */ - get allowGetBody() { - return this._internals.allowGetBody; - } - set allowGetBody(value) { - assert.boolean(value); - this._internals.allowGetBody = value; - } - /** - Request headers. - - Existing headers will be overwritten. Headers set to `undefined` will be omitted. - - @default {} - */ - get headers() { - return this._internals.headers; - } - set headers(value) { - assert.plainObject(value); - if (this._merging) { - Object.assign(this._internals.headers, lowercaseKeys(value)); - } - else { - this._internals.headers = lowercaseKeys(value); - } - } - /** - Specifies if the HTTP request method should be [rewritten as `GET`](https://tools.ietf.org/html/rfc7231#section-6.4) on redirects. - - As the [specification](https://tools.ietf.org/html/rfc7231#section-6.4) prefers to rewrite the HTTP method only on `303` responses, this is Got's default behavior. - Setting `methodRewriting` to `true` will also rewrite `301` and `302` responses, as allowed by the spec. This is the behavior followed by `curl` and browsers. - - __Note__: Got never performs method rewriting on `307` and `308` responses, as this is [explicitly prohibited by the specification](https://www.rfc-editor.org/rfc/rfc7231#section-6.4.7). - - @default false - */ - get methodRewriting() { - return this._internals.methodRewriting; - } - set methodRewriting(value) { - assert.boolean(value); - this._internals.methodRewriting = value; - } - /** - Indicates which DNS record family to use. - - Values: - - `undefined`: IPv4 (if present) or IPv6 - - `4`: Only IPv4 - - `6`: Only IPv6 - - @default undefined - */ - get dnsLookupIpVersion() { - return this._internals.dnsLookupIpVersion; - } - set dnsLookupIpVersion(value) { - if (value !== undefined && value !== 4 && value !== 6) { - throw new TypeError(`Invalid DNS lookup IP version: ${value}`); - } - this._internals.dnsLookupIpVersion = value; - } - /** - A function used to parse JSON responses. - - @example - ``` - import got from 'got'; - import Bourne from '@hapi/bourne'; - - const parsed = await got('https://example.com', { - parseJson: text => Bourne.parse(text) - }).json(); - - console.log(parsed); - ``` - */ - get parseJson() { - return this._internals.parseJson; - } - set parseJson(value) { - assert.function_(value); - this._internals.parseJson = value; - } - /** - A function used to stringify the body of JSON requests. - - @example - ``` - import got from 'got'; - - await got.post('https://example.com', { - stringifyJson: object => JSON.stringify(object, (key, value) => { - if (key.startsWith('_')) { - return; - } - - return value; - }), - json: { - some: 'payload', - _ignoreMe: 1234 - } - }); - ``` - - @example - ``` - import got from 'got'; - - await got.post('https://example.com', { - stringifyJson: object => JSON.stringify(object, (key, value) => { - if (typeof value === 'number') { - return value.toString(); - } - - return value; - }), - json: { - some: 'payload', - number: 1 - } - }); - ``` - */ - get stringifyJson() { - return this._internals.stringifyJson; - } - set stringifyJson(value) { - assert.function_(value); - this._internals.stringifyJson = value; - } - /** - An object representing `limit`, `calculateDelay`, `methods`, `statusCodes`, `maxRetryAfter` and `errorCodes` fields for maximum retry count, retry handler, allowed methods, allowed status codes, maximum [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time and allowed error codes. - - Delays between retries counts with function `1000 * Math.pow(2, retry) + Math.random() * 100`, where `retry` is attempt number (starts from 1). - - The `calculateDelay` property is a `function` that receives an object with `attemptCount`, `retryOptions`, `error` and `computedValue` properties for current retry count, the retry options, error and default computed value. - The function must return a delay in milliseconds (or a Promise resolving with it) (`0` return value cancels retry). - - By default, it retries *only* on the specified methods, status codes, and on these network errors: - - - `ETIMEDOUT`: One of the [timeout](#timeout) limits were reached. - - `ECONNRESET`: Connection was forcibly closed by a peer. - - `EADDRINUSE`: Could not bind to any free port. - - `ECONNREFUSED`: Connection was refused by the server. - - `EPIPE`: The remote side of the stream being written has been closed. - - `ENOTFOUND`: Couldn't resolve the hostname to an IP address. - - `ENETUNREACH`: No internet connection. - - `EAI_AGAIN`: DNS lookup timed out. - - __Note__: If `maxRetryAfter` is set to `undefined`, it will use `options.timeout`. - __Note__: If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will cancel the request. - */ - get retry() { - return this._internals.retry; - } - set retry(value) { - assert.plainObject(value); - assert.any([is.function_, is.undefined], value.calculateDelay); - assert.any([is.number, is.undefined], value.maxRetryAfter); - assert.any([is.number, is.undefined], value.limit); - assert.any([is.array, is.undefined], value.methods); - assert.any([is.array, is.undefined], value.statusCodes); - assert.any([is.array, is.undefined], value.errorCodes); - assert.any([is.number, is.undefined], value.noise); - if (value.noise && Math.abs(value.noise) > 100) { - throw new Error(`The maximum acceptable retry noise is +/- 100ms, got ${value.noise}`); - } - for (const key in value) { - if (!(key in this._internals.retry)) { - throw new Error(`Unexpected retry option: ${key}`); - } - } - if (this._merging) { - Object.assign(this._internals.retry, value); - } - else { - this._internals.retry = { ...value }; - } - const { retry } = this._internals; - retry.methods = [...new Set(retry.methods.map(method => method.toUpperCase()))]; - retry.statusCodes = [...new Set(retry.statusCodes)]; - retry.errorCodes = [...new Set(retry.errorCodes)]; - } - /** - From `http.RequestOptions`. - - The IP address used to send the request from. - */ - get localAddress() { - return this._internals.localAddress; - } - set localAddress(value) { - assert.any([is.string, is.undefined], value); - this._internals.localAddress = value; - } - /** - The HTTP method used to make the request. - - @default 'GET' - */ - get method() { - return this._internals.method; - } - set method(value) { - assert.string(value); - this._internals.method = value.toUpperCase(); - } - get createConnection() { - return this._internals.createConnection; - } - set createConnection(value) { - assert.any([is.function_, is.undefined], value); - this._internals.createConnection = value; - } - /** - From `http-cache-semantics` - - @default {} - */ - get cacheOptions() { - return this._internals.cacheOptions; - } - set cacheOptions(value) { - assert.plainObject(value); - assert.any([is.boolean, is.undefined], value.shared); - assert.any([is.number, is.undefined], value.cacheHeuristic); - assert.any([is.number, is.undefined], value.immutableMinTimeToLive); - assert.any([is.boolean, is.undefined], value.ignoreCargoCult); - for (const key in value) { - if (!(key in this._internals.cacheOptions)) { - throw new Error(`Cache option \`${key}\` does not exist`); - } - } - if (this._merging) { - Object.assign(this._internals.cacheOptions, value); - } - else { - this._internals.cacheOptions = { ...value }; - } - } - /** - Options for the advanced HTTPS API. - */ - get https() { - return this._internals.https; - } - set https(value) { - assert.plainObject(value); - assert.any([is.boolean, is.undefined], value.rejectUnauthorized); - assert.any([is.function_, is.undefined], value.checkServerIdentity); - assert.any([is.string, is.object, is.array, is.undefined], value.certificateAuthority); - assert.any([is.string, is.object, is.array, is.undefined], value.key); - assert.any([is.string, is.object, is.array, is.undefined], value.certificate); - assert.any([is.string, is.undefined], value.passphrase); - assert.any([is.string, is.buffer, is.array, is.undefined], value.pfx); - assert.any([is.array, is.undefined], value.alpnProtocols); - assert.any([is.string, is.undefined], value.ciphers); - assert.any([is.string, is.buffer, is.undefined], value.dhparam); - assert.any([is.string, is.undefined], value.signatureAlgorithms); - assert.any([is.string, is.undefined], value.minVersion); - assert.any([is.string, is.undefined], value.maxVersion); - assert.any([is.boolean, is.undefined], value.honorCipherOrder); - assert.any([is.number, is.undefined], value.tlsSessionLifetime); - assert.any([is.string, is.undefined], value.ecdhCurve); - assert.any([is.string, is.buffer, is.array, is.undefined], value.certificateRevocationLists); - for (const key in value) { - if (!(key in this._internals.https)) { - throw new Error(`HTTPS option \`${key}\` does not exist`); - } - } - if (this._merging) { - Object.assign(this._internals.https, value); - } - else { - this._internals.https = { ...value }; - } - } - /** - [Encoding](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings) to be used on `setEncoding` of the response data. - - To get a [`Buffer`](https://nodejs.org/api/buffer.html), you need to set `responseType` to `buffer` instead. - Don't set this option to `null`. - - __Note__: This doesn't affect streams! Instead, you need to do `got.stream(...).setEncoding(encoding)`. - - @default 'utf-8' - */ - get encoding() { - return this._internals.encoding; - } - set encoding(value) { - if (value === null) { - throw new TypeError('To get a Buffer, set `options.responseType` to `buffer` instead'); - } - assert.any([is.string, is.undefined], value); - this._internals.encoding = value; - } - /** - When set to `true` the promise will return the Response body instead of the Response object. - - @default false - */ - get resolveBodyOnly() { - return this._internals.resolveBodyOnly; - } - set resolveBodyOnly(value) { - assert.boolean(value); - this._internals.resolveBodyOnly = value; - } - /** - Returns a `Stream` instead of a `Promise`. - This is equivalent to calling `got.stream(url, options?)`. - - @default false - */ - get isStream() { - return this._internals.isStream; - } - set isStream(value) { - assert.boolean(value); - this._internals.isStream = value; - } - /** - The parsing method. - - The promise also has `.text()`, `.json()` and `.buffer()` methods which return another Got promise for the parsed body. - - It's like setting the options to `{responseType: 'json', resolveBodyOnly: true}` but without affecting the main Got promise. - - __Note__: When using streams, this option is ignored. - - @example - ``` - const responsePromise = got(url); - const bufferPromise = responsePromise.buffer(); - const jsonPromise = responsePromise.json(); - - const [response, buffer, json] = Promise.all([responsePromise, bufferPromise, jsonPromise]); - // `response` is an instance of Got Response - // `buffer` is an instance of Buffer - // `json` is an object - ``` - - @example - ``` - // This - const body = await got(url).json(); - - // is semantically the same as this - const body = await got(url, {responseType: 'json', resolveBodyOnly: true}); - ``` - */ - get responseType() { - return this._internals.responseType; - } - set responseType(value) { - if (value === undefined) { - this._internals.responseType = 'text'; - return; - } - if (value !== 'text' && value !== 'buffer' && value !== 'json') { - throw new Error(`Invalid \`responseType\` option: ${value}`); - } - this._internals.responseType = value; - } - get pagination() { - return this._internals.pagination; - } - set pagination(value) { - assert.object(value); - if (this._merging) { - Object.assign(this._internals.pagination, value); - } - else { - this._internals.pagination = value; - } - } - get auth() { - throw new Error('Parameter `auth` is deprecated. Use `username` / `password` instead.'); - } - set auth(_value) { - throw new Error('Parameter `auth` is deprecated. Use `username` / `password` instead.'); - } - get setHost() { - return this._internals.setHost; - } - set setHost(value) { - assert.boolean(value); - this._internals.setHost = value; - } - get maxHeaderSize() { - return this._internals.maxHeaderSize; - } - set maxHeaderSize(value) { - assert.any([is.number, is.undefined], value); - this._internals.maxHeaderSize = value; - } - get enableUnixSockets() { - return this._internals.enableUnixSockets; - } - set enableUnixSockets(value) { - assert.boolean(value); - this._internals.enableUnixSockets = value; - } - // eslint-disable-next-line @typescript-eslint/naming-convention - toJSON() { - return { ...this._internals }; - } - [Symbol.for('nodejs.util.inspect.custom')](_depth, options) { - return inspect(this._internals, options); - } - createNativeRequestOptions() { - const internals = this._internals; - const url = internals.url; - let agent; - if (url.protocol === 'https:') { - agent = internals.http2 ? internals.agent : internals.agent.https; - } - else { - agent = internals.agent.http; - } - const { https } = internals; - let { pfx } = https; - if (is.array(pfx) && is.plainObject(pfx[0])) { - pfx = pfx.map(object => ({ - buf: object.buffer, - passphrase: object.passphrase, - })); - } - return { - ...internals.cacheOptions, - ...this._unixOptions, - // HTTPS options - // eslint-disable-next-line @typescript-eslint/naming-convention - ALPNProtocols: https.alpnProtocols, - ca: https.certificateAuthority, - cert: https.certificate, - key: https.key, - passphrase: https.passphrase, - pfx: https.pfx, - rejectUnauthorized: https.rejectUnauthorized, - checkServerIdentity: https.checkServerIdentity ?? checkServerIdentity, - ciphers: https.ciphers, - honorCipherOrder: https.honorCipherOrder, - minVersion: https.minVersion, - maxVersion: https.maxVersion, - sigalgs: https.signatureAlgorithms, - sessionTimeout: https.tlsSessionLifetime, - dhparam: https.dhparam, - ecdhCurve: https.ecdhCurve, - crl: https.certificateRevocationLists, - // HTTP options - lookup: internals.dnsLookup ?? internals.dnsCache?.lookup, - family: internals.dnsLookupIpVersion, - agent, - setHost: internals.setHost, - method: internals.method, - maxHeaderSize: internals.maxHeaderSize, - localAddress: internals.localAddress, - headers: internals.headers, - createConnection: internals.createConnection, - timeout: internals.http2 ? getHttp2TimeoutOption(internals) : undefined, - // HTTP/2 options - h2session: internals.h2session, - }; - } - getRequestFunction() { - const url = this._internals.url; - const { request } = this._internals; - if (!request && url) { - return this.getFallbackRequestFunction(); - } - return request; - } - getFallbackRequestFunction() { - const url = this._internals.url; - if (!url) { - return; - } - if (url.protocol === 'https:') { - if (this._internals.http2) { - if (major < 15 || (major === 15 && minor < 10)) { - const error = new Error('To use the `http2` option, install Node.js 15.10.0 or above'); - error.code = 'EUNSUPPORTED'; - throw error; - } - return http2wrapper.auto; - } - return https.request; - } - return http.request; - } - freeze() { - const options = this._internals; - Object.freeze(options); - Object.freeze(options.hooks); - Object.freeze(options.hooks.afterResponse); - Object.freeze(options.hooks.beforeError); - Object.freeze(options.hooks.beforeRedirect); - Object.freeze(options.hooks.beforeRequest); - Object.freeze(options.hooks.beforeRetry); - Object.freeze(options.hooks.init); - Object.freeze(options.https); - Object.freeze(options.cacheOptions); - Object.freeze(options.agent); - Object.freeze(options.headers); - Object.freeze(options.timeout); - Object.freeze(options.retry); - Object.freeze(options.retry.errorCodes); - Object.freeze(options.retry.methods); - Object.freeze(options.retry.statusCodes); - } -} diff --git a/setup-pandoc/node_modules/got/dist/source/core/parse-link-header.d.ts b/setup-pandoc/node_modules/got/dist/source/core/parse-link-header.d.ts deleted file mode 100644 index 595e56112..000000000 --- a/setup-pandoc/node_modules/got/dist/source/core/parse-link-header.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -export default function parseLinkHeader(link: string): { - reference: string; - parameters: Record; -}[]; diff --git a/setup-pandoc/node_modules/got/dist/source/core/parse-link-header.js b/setup-pandoc/node_modules/got/dist/source/core/parse-link-header.js deleted file mode 100644 index e8cac6f7f..000000000 --- a/setup-pandoc/node_modules/got/dist/source/core/parse-link-header.js +++ /dev/null @@ -1,33 +0,0 @@ -export default function parseLinkHeader(link) { - const parsed = []; - const items = link.split(','); - for (const item of items) { - // https://tools.ietf.org/html/rfc5988#section-5 - const [rawUriReference, ...rawLinkParameters] = item.split(';'); - const trimmedUriReference = rawUriReference.trim(); - // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with - if (trimmedUriReference[0] !== '<' || trimmedUriReference.at(-1) !== '>') { - throw new Error(`Invalid format of the Link header reference: ${trimmedUriReference}`); - } - const reference = trimmedUriReference.slice(1, -1); - const parameters = {}; - if (rawLinkParameters.length === 0) { - throw new Error(`Unexpected end of Link header parameters: ${rawLinkParameters.join(';')}`); - } - for (const rawParameter of rawLinkParameters) { - const trimmedRawParameter = rawParameter.trim(); - const center = trimmedRawParameter.indexOf('='); - if (center === -1) { - throw new Error(`Failed to parse Link header: ${link}`); - } - const name = trimmedRawParameter.slice(0, center).trim(); - const value = trimmedRawParameter.slice(center + 1).trim(); - parameters[name] = value; - } - parsed.push({ - reference, - parameters, - }); - } - return parsed; -} diff --git a/setup-pandoc/node_modules/got/dist/source/core/response.d.ts b/setup-pandoc/node_modules/got/dist/source/core/response.d.ts deleted file mode 100644 index ce749aa65..000000000 --- a/setup-pandoc/node_modules/got/dist/source/core/response.d.ts +++ /dev/null @@ -1,108 +0,0 @@ -/// -import type { Buffer } from 'node:buffer'; -import type { IncomingMessageWithTimings, Timings } from '@szmarczak/http-timer'; -import { RequestError } from './errors.js'; -import type { ParseJsonFunction, ResponseType } from './options.js'; -import type Request from './index.js'; -export type PlainResponse = { - /** - The original request URL. - */ - requestUrl: URL; - /** - The redirect URLs. - */ - redirectUrls: URL[]; - /** - - `options` - The Got options that were set on this request. - - __Note__: This is not a [http.ClientRequest](https://nodejs.org/api/http.html#http_class_http_clientrequest). - */ - request: Request; - /** - The remote IP address. - - This is hopefully a temporary limitation, see [lukechilds/cacheable-request#86](https://github.com/lukechilds/cacheable-request/issues/86). - - __Note__: Not available when the response is cached. - */ - ip?: string; - /** - Whether the response was retrieved from the cache. - */ - isFromCache: boolean; - /** - The status code of the response. - */ - statusCode: number; - /** - The request URL or the final URL after redirects. - */ - url: string; - /** - The object contains the following properties: - - - `start` - Time when the request started. - - `socket` - Time when a socket was assigned to the request. - - `lookup` - Time when the DNS lookup finished. - - `connect` - Time when the socket successfully connected. - - `secureConnect` - Time when the socket securely connected. - - `upload` - Time when the request finished uploading. - - `response` - Time when the request fired `response` event. - - `end` - Time when the response fired `end` event. - - `error` - Time when the request fired `error` event. - - `abort` - Time when the request fired `abort` event. - - `phases` - - `wait` - `timings.socket - timings.start` - - `dns` - `timings.lookup - timings.socket` - - `tcp` - `timings.connect - timings.lookup` - - `tls` - `timings.secureConnect - timings.connect` - - `request` - `timings.upload - (timings.secureConnect || timings.connect)` - - `firstByte` - `timings.response - timings.upload` - - `download` - `timings.end - timings.response` - - `total` - `(timings.end || timings.error || timings.abort) - timings.start` - - If something has not been measured yet, it will be `undefined`. - - __Note__: The time is a `number` representing the milliseconds elapsed since the UNIX epoch. - */ - timings: Timings; - /** - The number of times the request was retried. - */ - retryCount: number; - /** - The raw result of the request. - */ - rawBody?: Buffer; - /** - The result of the request. - */ - body?: unknown; - /** - Whether the response was successful. - - __Note__: Got throws automatically when `response.ok` is `false` and `throwHttpErrors` is `true`. - */ - ok: boolean; -} & IncomingMessageWithTimings; -export type Response = { - /** - The result of the request. - */ - body: T; - /** - The raw result of the request. - */ - rawBody: Buffer; -} & PlainResponse; -export declare const isResponseOk: (response: PlainResponse) => boolean; -/** -An error to be thrown when server response code is 2xx, and parsing body fails. -Includes a `response` property. -*/ -export declare class ParseError extends RequestError { - readonly response: Response; - constructor(error: Error, response: Response); -} -export declare const parseBody: (response: Response, responseType: ResponseType, parseJson: ParseJsonFunction, encoding?: BufferEncoding) => unknown; diff --git a/setup-pandoc/node_modules/got/dist/source/core/response.js b/setup-pandoc/node_modules/got/dist/source/core/response.js deleted file mode 100644 index 3625249c4..000000000 --- a/setup-pandoc/node_modules/got/dist/source/core/response.js +++ /dev/null @@ -1,41 +0,0 @@ -import { RequestError } from './errors.js'; -export const isResponseOk = (response) => { - const { statusCode } = response; - const { followRedirect } = response.request.options; - const shouldFollow = typeof followRedirect === 'function' ? followRedirect(response) : followRedirect; - const limitStatusCode = shouldFollow ? 299 : 399; - return (statusCode >= 200 && statusCode <= limitStatusCode) || statusCode === 304; -}; -/** -An error to be thrown when server response code is 2xx, and parsing body fails. -Includes a `response` property. -*/ -export class ParseError extends RequestError { - constructor(error, response) { - const { options } = response.request; - super(`${error.message} in "${options.url.toString()}"`, error, response.request); - this.name = 'ParseError'; - this.code = 'ERR_BODY_PARSE_FAILURE'; - } -} -export const parseBody = (response, responseType, parseJson, encoding) => { - const { rawBody } = response; - try { - if (responseType === 'text') { - return rawBody.toString(encoding); - } - if (responseType === 'json') { - return rawBody.length === 0 ? '' : parseJson(rawBody.toString(encoding)); - } - if (responseType === 'buffer') { - return rawBody; - } - } - catch (error) { - throw new ParseError(error, response); - } - throw new ParseError({ - message: `Unknown body type '${responseType}'`, - name: 'Error', - }, response); -}; diff --git a/setup-pandoc/node_modules/got/dist/source/core/timed-out.d.ts b/setup-pandoc/node_modules/got/dist/source/core/timed-out.d.ts deleted file mode 100644 index 44781191b..000000000 --- a/setup-pandoc/node_modules/got/dist/source/core/timed-out.d.ts +++ /dev/null @@ -1,31 +0,0 @@ -/// -import type { ClientRequest } from 'node:http'; -declare const reentry: unique symbol; -type TimedOutOptions = { - host?: string; - hostname?: string; - protocol?: string; -}; -export type Delays = { - lookup?: number; - socket?: number; - connect?: number; - secureConnect?: number; - send?: number; - response?: number; - read?: number; - request?: number; -}; -export type ErrorCode = 'ETIMEDOUT' | 'ECONNRESET' | 'EADDRINUSE' | 'ECONNREFUSED' | 'EPIPE' | 'ENOTFOUND' | 'ENETUNREACH' | 'EAI_AGAIN'; -export declare class TimeoutError extends Error { - event: string; - code: ErrorCode; - constructor(threshold: number, event: string); -} -export default function timedOut(request: ClientRequest, delays: Delays, options: TimedOutOptions): () => void; -declare module 'http' { - interface ClientRequest { - [reentry]?: boolean; - } -} -export {}; diff --git a/setup-pandoc/node_modules/got/dist/source/core/timed-out.js b/setup-pandoc/node_modules/got/dist/source/core/timed-out.js deleted file mode 100644 index df8c19688..000000000 --- a/setup-pandoc/node_modules/got/dist/source/core/timed-out.js +++ /dev/null @@ -1,129 +0,0 @@ -import net from 'node:net'; -import unhandler from './utils/unhandle.js'; -const reentry = Symbol('reentry'); -const noop = () => { }; -export class TimeoutError extends Error { - event; - code; - constructor(threshold, event) { - super(`Timeout awaiting '${event}' for ${threshold}ms`); - this.event = event; - this.name = 'TimeoutError'; - this.code = 'ETIMEDOUT'; - } -} -export default function timedOut(request, delays, options) { - if (reentry in request) { - return noop; - } - request[reentry] = true; - const cancelers = []; - const { once, unhandleAll } = unhandler(); - const addTimeout = (delay, callback, event) => { - const timeout = setTimeout(callback, delay, delay, event); - timeout.unref?.(); - const cancel = () => { - clearTimeout(timeout); - }; - cancelers.push(cancel); - return cancel; - }; - const { host, hostname } = options; - const timeoutHandler = (delay, event) => { - request.destroy(new TimeoutError(delay, event)); - }; - const cancelTimeouts = () => { - for (const cancel of cancelers) { - cancel(); - } - unhandleAll(); - }; - request.once('error', error => { - cancelTimeouts(); - // Save original behavior - /* istanbul ignore next */ - if (request.listenerCount('error') === 0) { - throw error; - } - }); - if (delays.request !== undefined) { - const cancelTimeout = addTimeout(delays.request, timeoutHandler, 'request'); - once(request, 'response', (response) => { - once(response, 'end', cancelTimeout); - }); - } - if (delays.socket !== undefined) { - const { socket } = delays; - const socketTimeoutHandler = () => { - timeoutHandler(socket, 'socket'); - }; - request.setTimeout(socket, socketTimeoutHandler); - // `request.setTimeout(0)` causes a memory leak. - // We can just remove the listener and forget about the timer - it's unreffed. - // See https://github.com/sindresorhus/got/issues/690 - cancelers.push(() => { - request.removeListener('timeout', socketTimeoutHandler); - }); - } - const hasLookup = delays.lookup !== undefined; - const hasConnect = delays.connect !== undefined; - const hasSecureConnect = delays.secureConnect !== undefined; - const hasSend = delays.send !== undefined; - if (hasLookup || hasConnect || hasSecureConnect || hasSend) { - once(request, 'socket', (socket) => { - const { socketPath } = request; - /* istanbul ignore next: hard to test */ - if (socket.connecting) { - const hasPath = Boolean(socketPath ?? net.isIP(hostname ?? host ?? '') !== 0); - if (hasLookup && !hasPath && socket.address().address === undefined) { - const cancelTimeout = addTimeout(delays.lookup, timeoutHandler, 'lookup'); - once(socket, 'lookup', cancelTimeout); - } - if (hasConnect) { - const timeConnect = () => addTimeout(delays.connect, timeoutHandler, 'connect'); - if (hasPath) { - once(socket, 'connect', timeConnect()); - } - else { - once(socket, 'lookup', (error) => { - if (error === null) { - once(socket, 'connect', timeConnect()); - } - }); - } - } - if (hasSecureConnect && options.protocol === 'https:') { - once(socket, 'connect', () => { - const cancelTimeout = addTimeout(delays.secureConnect, timeoutHandler, 'secureConnect'); - once(socket, 'secureConnect', cancelTimeout); - }); - } - } - if (hasSend) { - const timeRequest = () => addTimeout(delays.send, timeoutHandler, 'send'); - /* istanbul ignore next: hard to test */ - if (socket.connecting) { - once(socket, 'connect', () => { - once(request, 'upload-complete', timeRequest()); - }); - } - else { - once(request, 'upload-complete', timeRequest()); - } - } - }); - } - if (delays.response !== undefined) { - once(request, 'upload-complete', () => { - const cancelTimeout = addTimeout(delays.response, timeoutHandler, 'response'); - once(request, 'response', cancelTimeout); - }); - } - if (delays.read !== undefined) { - once(request, 'response', (response) => { - const cancelTimeout = addTimeout(delays.read, timeoutHandler, 'read'); - once(response, 'end', cancelTimeout); - }); - } - return cancelTimeouts; -} diff --git a/setup-pandoc/node_modules/got/dist/source/core/utils/dns-ip-version.d.ts b/setup-pandoc/node_modules/got/dist/source/core/utils/dns-ip-version.d.ts new file mode 100644 index 000000000..ea547cd88 --- /dev/null +++ b/setup-pandoc/node_modules/got/dist/source/core/utils/dns-ip-version.d.ts @@ -0,0 +1,5 @@ +export declare type DnsLookupIpVersion = 'auto' | 'ipv4' | 'ipv6'; +declare type DnsIpFamily = 0 | 4 | 6; +export declare const isDnsLookupIpVersion: (value: any) => boolean; +export declare const dnsLookupIpVersionToFamily: (dnsLookupIpVersion: DnsLookupIpVersion) => DnsIpFamily; +export {}; diff --git a/setup-pandoc/node_modules/got/dist/source/core/utils/dns-ip-version.js b/setup-pandoc/node_modules/got/dist/source/core/utils/dns-ip-version.js new file mode 100644 index 000000000..6f599c223 --- /dev/null +++ b/setup-pandoc/node_modules/got/dist/source/core/utils/dns-ip-version.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.dnsLookupIpVersionToFamily = exports.isDnsLookupIpVersion = void 0; +const conversionTable = { + auto: 0, + ipv4: 4, + ipv6: 6 +}; +exports.isDnsLookupIpVersion = (value) => { + return value in conversionTable; +}; +exports.dnsLookupIpVersionToFamily = (dnsLookupIpVersion) => { + if (exports.isDnsLookupIpVersion(dnsLookupIpVersion)) { + return conversionTable[dnsLookupIpVersion]; + } + throw new Error('Invalid DNS lookup IP version'); +}; diff --git a/setup-pandoc/node_modules/got/dist/source/core/utils/get-body-size.d.ts b/setup-pandoc/node_modules/got/dist/source/core/utils/get-body-size.d.ts index 303069161..9745f69a8 100644 --- a/setup-pandoc/node_modules/got/dist/source/core/utils/get-body-size.d.ts +++ b/setup-pandoc/node_modules/got/dist/source/core/utils/get-body-size.d.ts @@ -1,3 +1,3 @@ -/// -import type { ClientRequestArgs } from 'node:http'; -export default function getBodySize(body: unknown, headers: ClientRequestArgs['headers']): Promise; +import { ClientRequestArgs } from 'http'; +declare const _default: (body: unknown, headers: ClientRequestArgs['headers']) => Promise; +export default _default; diff --git a/setup-pandoc/node_modules/got/dist/source/core/utils/get-body-size.js b/setup-pandoc/node_modules/got/dist/source/core/utils/get-body-size.js index 9a85c6480..020234230 100644 --- a/setup-pandoc/node_modules/got/dist/source/core/utils/get-body-size.js +++ b/setup-pandoc/node_modules/got/dist/source/core/utils/get-body-size.js @@ -1,22 +1,32 @@ -import { Buffer } from 'node:buffer'; -import { promisify } from 'node:util'; -import is from '@sindresorhus/is'; -import isFormData from './is-form-data.js'; -export default async function getBodySize(body, headers) { +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const fs_1 = require("fs"); +const util_1 = require("util"); +const is_1 = require("@sindresorhus/is"); +const is_form_data_1 = require("./is-form-data"); +const statAsync = util_1.promisify(fs_1.stat); +exports.default = async (body, headers) => { if (headers && 'content-length' in headers) { return Number(headers['content-length']); } if (!body) { return 0; } - if (is.string(body)) { + if (is_1.default.string(body)) { return Buffer.byteLength(body); } - if (is.buffer(body)) { + if (is_1.default.buffer(body)) { return body.length; } - if (isFormData(body)) { - return promisify(body.getLength.bind(body))(); + if (is_form_data_1.default(body)) { + return util_1.promisify(body.getLength.bind(body))(); + } + if (body instanceof fs_1.ReadStream) { + const { size } = await statAsync(body.path); + if (size === 0) { + return undefined; + } + return size; } return undefined; -} +}; diff --git a/setup-pandoc/node_modules/got/dist/source/core/utils/get-buffer.d.ts b/setup-pandoc/node_modules/got/dist/source/core/utils/get-buffer.d.ts new file mode 100644 index 000000000..66eaada9a --- /dev/null +++ b/setup-pandoc/node_modules/got/dist/source/core/utils/get-buffer.d.ts @@ -0,0 +1,4 @@ +/// +import { Readable } from 'stream'; +declare const getBuffer: (stream: Readable) => Promise; +export default getBuffer; diff --git a/setup-pandoc/node_modules/got/dist/source/core/utils/get-buffer.js b/setup-pandoc/node_modules/got/dist/source/core/utils/get-buffer.js new file mode 100644 index 000000000..0155f088a --- /dev/null +++ b/setup-pandoc/node_modules/got/dist/source/core/utils/get-buffer.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +// TODO: Update https://github.com/sindresorhus/get-stream +const getBuffer = async (stream) => { + const chunks = []; + let length = 0; + for await (const chunk of stream) { + chunks.push(chunk); + length += Buffer.byteLength(chunk); + } + if (Buffer.isBuffer(chunks[0])) { + return Buffer.concat(chunks, length); + } + return Buffer.from(chunks.join('')); +}; +exports.default = getBuffer; diff --git a/setup-pandoc/node_modules/got/dist/source/core/utils/is-client-request.d.ts b/setup-pandoc/node_modules/got/dist/source/core/utils/is-client-request.d.ts deleted file mode 100644 index 1c779569b..000000000 --- a/setup-pandoc/node_modules/got/dist/source/core/utils/is-client-request.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/// -/// -import type { Writable, Readable } from 'node:stream'; -import type { ClientRequest } from 'node:http'; -declare function isClientRequest(clientRequest: Writable | Readable): clientRequest is ClientRequest; -export default isClientRequest; diff --git a/setup-pandoc/node_modules/got/dist/source/core/utils/is-client-request.js b/setup-pandoc/node_modules/got/dist/source/core/utils/is-client-request.js deleted file mode 100644 index da80b68e3..000000000 --- a/setup-pandoc/node_modules/got/dist/source/core/utils/is-client-request.js +++ /dev/null @@ -1,4 +0,0 @@ -function isClientRequest(clientRequest) { - return clientRequest.writable && !clientRequest.writableEnded; -} -export default isClientRequest; diff --git a/setup-pandoc/node_modules/got/dist/source/core/utils/is-form-data.d.ts b/setup-pandoc/node_modules/got/dist/source/core/utils/is-form-data.d.ts index ed0805fce..02087b55d 100644 --- a/setup-pandoc/node_modules/got/dist/source/core/utils/is-form-data.d.ts +++ b/setup-pandoc/node_modules/got/dist/source/core/utils/is-form-data.d.ts @@ -1,8 +1,8 @@ -/// -import type { Readable } from 'node:stream'; -type FormData = { +/// +import { Readable } from 'stream'; +interface FormData extends Readable { getBoundary: () => string; getLength: (callback: (error: Error | null, length: number) => void) => void; -} & Readable; -export default function isFormData(body: unknown): body is FormData; -export {}; +} +declare const _default: (body: unknown) => body is FormData; +export default _default; diff --git a/setup-pandoc/node_modules/got/dist/source/core/utils/is-form-data.js b/setup-pandoc/node_modules/got/dist/source/core/utils/is-form-data.js index 13a7823af..32c16cc73 100644 --- a/setup-pandoc/node_modules/got/dist/source/core/utils/is-form-data.js +++ b/setup-pandoc/node_modules/got/dist/source/core/utils/is-form-data.js @@ -1,4 +1,4 @@ -import is from '@sindresorhus/is'; -export default function isFormData(body) { - return is.nodeStream(body) && is.function_(body.getBoundary); -} +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const is_1 = require("@sindresorhus/is"); +exports.default = (body) => is_1.default.nodeStream(body) && is_1.default.function_(body.getBoundary); diff --git a/setup-pandoc/node_modules/got/dist/source/core/utils/is-response-ok.d.ts b/setup-pandoc/node_modules/got/dist/source/core/utils/is-response-ok.d.ts new file mode 100644 index 000000000..7e1d49a2f --- /dev/null +++ b/setup-pandoc/node_modules/got/dist/source/core/utils/is-response-ok.d.ts @@ -0,0 +1,2 @@ +import { Response } from '..'; +export declare const isResponseOk: (response: Response) => boolean; diff --git a/setup-pandoc/node_modules/got/dist/source/core/utils/is-response-ok.js b/setup-pandoc/node_modules/got/dist/source/core/utils/is-response-ok.js new file mode 100644 index 000000000..84c933183 --- /dev/null +++ b/setup-pandoc/node_modules/got/dist/source/core/utils/is-response-ok.js @@ -0,0 +1,8 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isResponseOk = void 0; +exports.isResponseOk = (response) => { + const { statusCode } = response; + const limitStatusCode = response.request.options.followRedirect ? 299 : 399; + return (statusCode >= 200 && statusCode <= limitStatusCode) || statusCode === 304; +}; diff --git a/setup-pandoc/node_modules/got/dist/source/core/utils/is-unix-socket-url.d.ts b/setup-pandoc/node_modules/got/dist/source/core/utils/is-unix-socket-url.d.ts deleted file mode 100644 index 041f00696..000000000 --- a/setup-pandoc/node_modules/got/dist/source/core/utils/is-unix-socket-url.d.ts +++ /dev/null @@ -1 +0,0 @@ -export default function isUnixSocketURL(url: URL): boolean; diff --git a/setup-pandoc/node_modules/got/dist/source/core/utils/is-unix-socket-url.js b/setup-pandoc/node_modules/got/dist/source/core/utils/is-unix-socket-url.js deleted file mode 100644 index 46f7348a6..000000000 --- a/setup-pandoc/node_modules/got/dist/source/core/utils/is-unix-socket-url.js +++ /dev/null @@ -1,4 +0,0 @@ -// eslint-disable-next-line @typescript-eslint/naming-convention -export default function isUnixSocketURL(url) { - return url.protocol === 'unix:' || url.hostname === 'unix'; -} diff --git a/setup-pandoc/node_modules/got/dist/source/core/utils/options-to-url.d.ts b/setup-pandoc/node_modules/got/dist/source/core/utils/options-to-url.d.ts index 20a6e5593..c696a837e 100644 --- a/setup-pandoc/node_modules/got/dist/source/core/utils/options-to-url.d.ts +++ b/setup-pandoc/node_modules/got/dist/source/core/utils/options-to-url.d.ts @@ -1,4 +1,5 @@ -export type URLOptions = { +import { URL } from 'url'; +export interface URLOptions { href?: string; protocol?: string; host?: string; @@ -8,5 +9,6 @@ export type URLOptions = { search?: string; searchParams?: unknown; path?: string; -}; -export default function optionsToUrl(origin: string, options: URLOptions): URL; +} +declare const _default: (origin: string, options: URLOptions) => URL; +export default _default; diff --git a/setup-pandoc/node_modules/got/dist/source/core/utils/options-to-url.js b/setup-pandoc/node_modules/got/dist/source/core/utils/options-to-url.js index b33001a90..65be02f9b 100644 --- a/setup-pandoc/node_modules/got/dist/source/core/utils/options-to-url.js +++ b/setup-pandoc/node_modules/got/dist/source/core/utils/options-to-url.js @@ -1,12 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +/* istanbul ignore file: deprecated */ +const url_1 = require("url"); const keys = [ 'protocol', 'host', 'hostname', 'port', 'pathname', - 'search', + 'search' ]; -export default function optionsToUrl(origin, options) { +exports.default = (origin, options) => { + var _a, _b; if (options.path) { if (options.pathname) { throw new TypeError('Parameters `path` and `pathname` are mutually exclusive.'); @@ -25,9 +30,9 @@ export default function optionsToUrl(origin, options) { if (!options.protocol) { throw new TypeError('No URL protocol specified'); } - origin = `${options.protocol}//${options.hostname ?? options.host ?? ''}`; + origin = `${options.protocol}//${(_b = (_a = options.hostname) !== null && _a !== void 0 ? _a : options.host) !== null && _b !== void 0 ? _b : ''}`; } - const url = new URL(origin); + const url = new url_1.URL(origin); if (options.path) { const searchIndex = options.path.indexOf('?'); if (searchIndex === -1) { @@ -45,4 +50,4 @@ export default function optionsToUrl(origin, options) { } } return url; -} +}; diff --git a/setup-pandoc/node_modules/got/dist/source/core/utils/proxy-events.d.ts b/setup-pandoc/node_modules/got/dist/source/core/utils/proxy-events.d.ts index cbc818af4..b244d82ac 100644 --- a/setup-pandoc/node_modules/got/dist/source/core/utils/proxy-events.d.ts +++ b/setup-pandoc/node_modules/got/dist/source/core/utils/proxy-events.d.ts @@ -1,3 +1,3 @@ -/// -import type { EventEmitter } from 'node:events'; -export default function proxyEvents(from: EventEmitter, to: EventEmitter, events: Readonly): () => void; +/// +import { EventEmitter } from 'events'; +export default function (from: EventEmitter, to: EventEmitter, events: string[]): () => void; diff --git a/setup-pandoc/node_modules/got/dist/source/core/utils/proxy-events.js b/setup-pandoc/node_modules/got/dist/source/core/utils/proxy-events.js index d3d2f2d1c..4d47c53fb 100644 --- a/setup-pandoc/node_modules/got/dist/source/core/utils/proxy-events.js +++ b/setup-pandoc/node_modules/got/dist/source/core/utils/proxy-events.js @@ -1,15 +1,17 @@ -export default function proxyEvents(from, to, events) { - const eventFunctions = {}; +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +function default_1(from, to, events) { + const fns = {}; for (const event of events) { - const eventFunction = (...args) => { + fns[event] = (...args) => { to.emit(event, ...args); }; - eventFunctions[event] = eventFunction; - from.on(event, eventFunction); + from.on(event, fns[event]); } return () => { - for (const [event, eventFunction] of Object.entries(eventFunctions)) { - from.off(event, eventFunction); + for (const event of events) { + from.off(event, fns[event]); } }; } +exports.default = default_1; diff --git a/setup-pandoc/node_modules/got/dist/source/core/utils/timed-out.d.ts b/setup-pandoc/node_modules/got/dist/source/core/utils/timed-out.d.ts new file mode 100644 index 000000000..5b495d464 --- /dev/null +++ b/setup-pandoc/node_modules/got/dist/source/core/utils/timed-out.d.ts @@ -0,0 +1,29 @@ +import { ClientRequest } from 'http'; +declare const reentry: unique symbol; +interface TimedOutOptions { + host?: string; + hostname?: string; + protocol?: string; +} +export interface Delays { + lookup?: number; + connect?: number; + secureConnect?: number; + socket?: number; + response?: number; + send?: number; + request?: number; +} +export declare type ErrorCode = 'ETIMEDOUT' | 'ECONNRESET' | 'EADDRINUSE' | 'ECONNREFUSED' | 'EPIPE' | 'ENOTFOUND' | 'ENETUNREACH' | 'EAI_AGAIN'; +export declare class TimeoutError extends Error { + event: string; + code: ErrorCode; + constructor(threshold: number, event: string); +} +declare const _default: (request: ClientRequest, delays: Delays, options: TimedOutOptions) => () => void; +export default _default; +declare module 'http' { + interface ClientRequest { + [reentry]: boolean; + } +} diff --git a/setup-pandoc/node_modules/got/dist/source/core/utils/timed-out.js b/setup-pandoc/node_modules/got/dist/source/core/utils/timed-out.js new file mode 100644 index 000000000..887701631 --- /dev/null +++ b/setup-pandoc/node_modules/got/dist/source/core/utils/timed-out.js @@ -0,0 +1,121 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TimeoutError = void 0; +const net = require("net"); +const unhandle_1 = require("./unhandle"); +const reentry = Symbol('reentry'); +const noop = () => { }; +class TimeoutError extends Error { + constructor(threshold, event) { + super(`Timeout awaiting '${event}' for ${threshold}ms`); + this.event = event; + this.name = 'TimeoutError'; + this.code = 'ETIMEDOUT'; + } +} +exports.TimeoutError = TimeoutError; +exports.default = (request, delays, options) => { + if (reentry in request) { + return noop; + } + request[reentry] = true; + const cancelers = []; + const { once, unhandleAll } = unhandle_1.default(); + const addTimeout = (delay, callback, event) => { + var _a; + const timeout = setTimeout(callback, delay, delay, event); + (_a = timeout.unref) === null || _a === void 0 ? void 0 : _a.call(timeout); + const cancel = () => { + clearTimeout(timeout); + }; + cancelers.push(cancel); + return cancel; + }; + const { host, hostname } = options; + const timeoutHandler = (delay, event) => { + request.destroy(new TimeoutError(delay, event)); + }; + const cancelTimeouts = () => { + for (const cancel of cancelers) { + cancel(); + } + unhandleAll(); + }; + request.once('error', error => { + cancelTimeouts(); + // Save original behavior + /* istanbul ignore next */ + if (request.listenerCount('error') === 0) { + throw error; + } + }); + request.once('close', cancelTimeouts); + once(request, 'response', (response) => { + once(response, 'end', cancelTimeouts); + }); + if (typeof delays.request !== 'undefined') { + addTimeout(delays.request, timeoutHandler, 'request'); + } + if (typeof delays.socket !== 'undefined') { + const socketTimeoutHandler = () => { + timeoutHandler(delays.socket, 'socket'); + }; + request.setTimeout(delays.socket, socketTimeoutHandler); + // `request.setTimeout(0)` causes a memory leak. + // We can just remove the listener and forget about the timer - it's unreffed. + // See https://github.com/sindresorhus/got/issues/690 + cancelers.push(() => { + request.removeListener('timeout', socketTimeoutHandler); + }); + } + once(request, 'socket', (socket) => { + var _a; + const { socketPath } = request; + /* istanbul ignore next: hard to test */ + if (socket.connecting) { + const hasPath = Boolean(socketPath !== null && socketPath !== void 0 ? socketPath : net.isIP((_a = hostname !== null && hostname !== void 0 ? hostname : host) !== null && _a !== void 0 ? _a : '') !== 0); + if (typeof delays.lookup !== 'undefined' && !hasPath && typeof socket.address().address === 'undefined') { + const cancelTimeout = addTimeout(delays.lookup, timeoutHandler, 'lookup'); + once(socket, 'lookup', cancelTimeout); + } + if (typeof delays.connect !== 'undefined') { + const timeConnect = () => addTimeout(delays.connect, timeoutHandler, 'connect'); + if (hasPath) { + once(socket, 'connect', timeConnect()); + } + else { + once(socket, 'lookup', (error) => { + if (error === null) { + once(socket, 'connect', timeConnect()); + } + }); + } + } + if (typeof delays.secureConnect !== 'undefined' && options.protocol === 'https:') { + once(socket, 'connect', () => { + const cancelTimeout = addTimeout(delays.secureConnect, timeoutHandler, 'secureConnect'); + once(socket, 'secureConnect', cancelTimeout); + }); + } + } + if (typeof delays.send !== 'undefined') { + const timeRequest = () => addTimeout(delays.send, timeoutHandler, 'send'); + /* istanbul ignore next: hard to test */ + if (socket.connecting) { + once(socket, 'connect', () => { + once(request, 'upload-complete', timeRequest()); + }); + } + else { + once(request, 'upload-complete', timeRequest()); + } + } + }); + if (typeof delays.response !== 'undefined') { + once(request, 'upload-complete', () => { + const cancelTimeout = addTimeout(delays.response, timeoutHandler, 'response'); + once(request, 'response', cancelTimeout); + }); + } + return cancelTimeouts; +}; diff --git a/setup-pandoc/node_modules/got/dist/source/core/utils/unhandle.d.ts b/setup-pandoc/node_modules/got/dist/source/core/utils/unhandle.d.ts index c4945763a..f49b792e8 100644 --- a/setup-pandoc/node_modules/got/dist/source/core/utils/unhandle.d.ts +++ b/setup-pandoc/node_modules/got/dist/source/core/utils/unhandle.d.ts @@ -1,11 +1,11 @@ -/// -import type { EventEmitter } from 'node:events'; -type Origin = EventEmitter; -type Event = string | symbol; -type Fn = (...args: any[]) => void; -type Unhandler = { +/// +import { EventEmitter } from 'events'; +declare type Origin = EventEmitter; +declare type Event = string | symbol; +declare type Fn = (...args: any[]) => void; +interface Unhandler { once: (origin: Origin, event: Event, fn: Fn) => void; unhandleAll: () => void; -}; -export default function unhandle(): Unhandler; -export {}; +} +declare const _default: () => Unhandler; +export default _default; diff --git a/setup-pandoc/node_modules/got/dist/source/core/utils/unhandle.js b/setup-pandoc/node_modules/got/dist/source/core/utils/unhandle.js index 03127068e..e749697f8 100644 --- a/setup-pandoc/node_modules/got/dist/source/core/utils/unhandle.js +++ b/setup-pandoc/node_modules/got/dist/source/core/utils/unhandle.js @@ -1,8 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); // When attaching listeners, it's very easy to forget about them. // Especially if you do error handling and set timeouts. // So instead of checking if it's proper to throw an error on every timeout ever, // use this simple tool which will remove all listeners you have attached. -export default function unhandle() { +exports.default = () => { const handlers = []; return { once(origin, event, fn) { @@ -15,6 +17,6 @@ export default function unhandle() { origin.removeListener(event, fn); } handlers.length = 0; - }, + } }; -} +}; diff --git a/setup-pandoc/node_modules/got/dist/source/core/utils/url-to-options.d.ts b/setup-pandoc/node_modules/got/dist/source/core/utils/url-to-options.d.ts index 70a8feb0e..c977a0f4a 100644 --- a/setup-pandoc/node_modules/got/dist/source/core/utils/url-to-options.d.ts +++ b/setup-pandoc/node_modules/got/dist/source/core/utils/url-to-options.d.ts @@ -1,6 +1,5 @@ -/// -import type { UrlWithStringQuery } from 'node:url'; -export type LegacyUrlOptions = { +import { URL, UrlWithStringQuery } from 'url'; +export interface LegacyUrlOptions { protocol: string; hostname: string; host: string; @@ -11,5 +10,6 @@ export type LegacyUrlOptions = { path: string; port?: number; auth?: string; -}; -export default function urlToOptions(url: URL | UrlWithStringQuery): LegacyUrlOptions; +} +declare const _default: (url: URL | UrlWithStringQuery) => LegacyUrlOptions; +export default _default; diff --git a/setup-pandoc/node_modules/got/dist/source/core/utils/url-to-options.js b/setup-pandoc/node_modules/got/dist/source/core/utils/url-to-options.js index 959dd6983..19cc48752 100644 --- a/setup-pandoc/node_modules/got/dist/source/core/utils/url-to-options.js +++ b/setup-pandoc/node_modules/got/dist/source/core/utils/url-to-options.js @@ -1,22 +1,24 @@ -import is from '@sindresorhus/is'; -export default function urlToOptions(url) { +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const is_1 = require("@sindresorhus/is"); +exports.default = (url) => { // Cast to URL url = url; const options = { protocol: url.protocol, - hostname: is.string(url.hostname) && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname, + hostname: is_1.default.string(url.hostname) && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname, host: url.host, hash: url.hash, search: url.search, pathname: url.pathname, href: url.href, - path: `${url.pathname || ''}${url.search || ''}`, + path: `${url.pathname || ''}${url.search || ''}` }; - if (is.string(url.port) && url.port.length > 0) { + if (is_1.default.string(url.port) && url.port.length > 0) { options.port = Number(url.port); } if (url.username || url.password) { options.auth = `${url.username || ''}:${url.password || ''}`; } return options; -} +}; diff --git a/setup-pandoc/node_modules/got/dist/source/core/utils/weakable-map.js b/setup-pandoc/node_modules/got/dist/source/core/utils/weakable-map.js index 89f3c896e..5c5da7f01 100644 --- a/setup-pandoc/node_modules/got/dist/source/core/utils/weakable-map.js +++ b/setup-pandoc/node_modules/got/dist/source/core/utils/weakable-map.js @@ -1,6 +1,6 @@ -export default class WeakableMap { - weakMap; - map; +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +class WeakableMap { constructor() { this.weakMap = new WeakMap(); this.map = new Map(); @@ -26,3 +26,4 @@ export default class WeakableMap { return this.map.has(key); } } +exports.default = WeakableMap; diff --git a/setup-pandoc/node_modules/got/dist/source/create.d.ts b/setup-pandoc/node_modules/got/dist/source/create.d.ts index ce0f4b695..c8fd7aea4 100644 --- a/setup-pandoc/node_modules/got/dist/source/create.d.ts +++ b/setup-pandoc/node_modules/got/dist/source/create.d.ts @@ -1,3 +1,5 @@ -import type { Got, InstanceDefaults } from './types.js'; +import { Got, HandlerFunction, InstanceDefaults } from './types'; +export declare const defaultHandler: HandlerFunction; declare const create: (defaults: InstanceDefaults) => Got; export default create; +export * from './types'; diff --git a/setup-pandoc/node_modules/got/dist/source/create.js b/setup-pandoc/node_modules/got/dist/source/create.js index fb14e49f5..bf56db4c4 100644 --- a/setup-pandoc/node_modules/got/dist/source/create.js +++ b/setup-pandoc/node_modules/got/dist/source/create.js @@ -1,110 +1,170 @@ -import is, { assert } from '@sindresorhus/is'; -import asPromise from './as-promise/index.js'; -import Request from './core/index.js'; -import Options from './core/options.js'; +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defaultHandler = void 0; +const is_1 = require("@sindresorhus/is"); +const as_promise_1 = require("./as-promise"); +const create_rejection_1 = require("./as-promise/create-rejection"); +const core_1 = require("./core"); +const deep_freeze_1 = require("./utils/deep-freeze"); +const errors = { + RequestError: as_promise_1.RequestError, + CacheError: as_promise_1.CacheError, + ReadError: as_promise_1.ReadError, + HTTPError: as_promise_1.HTTPError, + MaxRedirectsError: as_promise_1.MaxRedirectsError, + TimeoutError: as_promise_1.TimeoutError, + ParseError: as_promise_1.ParseError, + CancelError: as_promise_1.CancelError, + UnsupportedProtocolError: as_promise_1.UnsupportedProtocolError, + UploadError: as_promise_1.UploadError +}; // The `delay` package weighs 10KB (!) const delay = async (ms) => new Promise(resolve => { setTimeout(resolve, ms); }); -const isGotInstance = (value) => is.function_(value); +const { normalizeArguments } = core_1.default; +const mergeOptions = (...sources) => { + let mergedOptions; + for (const source of sources) { + mergedOptions = normalizeArguments(undefined, source, mergedOptions); + } + return mergedOptions; +}; +const getPromiseOrStream = (options) => options.isStream ? new core_1.default(undefined, options) : as_promise_1.default(options); +const isGotInstance = (value) => ('defaults' in value && 'options' in value.defaults); const aliases = [ 'get', 'post', 'put', 'patch', 'head', - 'delete', + 'delete' ]; +exports.defaultHandler = (options, next) => next(options); +const callInitHooks = (hooks, options) => { + if (hooks) { + for (const hook of hooks) { + hook(options); + } + } +}; const create = (defaults) => { - defaults = { - options: new Options(undefined, undefined, defaults.options), - handlers: [...defaults.handlers], - mutableDefaults: defaults.mutableDefaults, - }; - Object.defineProperty(defaults, 'mutableDefaults', { - enumerable: true, - configurable: false, - writable: false, - }); + // Proxy properties from next handlers + defaults._rawHandlers = defaults.handlers; + defaults.handlers = defaults.handlers.map(fn => ((options, next) => { + // This will be assigned by assigning result + let root; + const result = fn(options, newOptions => { + root = next(newOptions); + return root; + }); + if (result !== root && !options.isStream && root) { + const typedResult = result; + const { then: promiseThen, catch: promiseCatch, finally: promiseFianlly } = typedResult; + Object.setPrototypeOf(typedResult, Object.getPrototypeOf(root)); + Object.defineProperties(typedResult, Object.getOwnPropertyDescriptors(root)); + // These should point to the new promise + // eslint-disable-next-line promise/prefer-await-to-then + typedResult.then = promiseThen; + typedResult.catch = promiseCatch; + typedResult.finally = promiseFianlly; + } + return result; + })); // Got interface - const got = ((url, options, defaultOptions = defaults.options) => { - const request = new Request(url, options, defaultOptions); - let promise; - const lastHandler = (normalized) => { - // Note: `options` is `undefined` when `new Options(...)` fails - request.options = normalized; - request._noPipe = !normalized.isStream; - void request.flush(); - if (normalized.isStream) { - return request; - } - if (!promise) { - promise = asPromise(request); - } - return promise; - }; + const got = ((url, options = {}, _defaults) => { + var _a, _b; let iteration = 0; const iterateHandlers = (newOptions) => { - const handler = defaults.handlers[iteration++] ?? lastHandler; - const result = handler(newOptions, iterateHandlers); - if (is.promise(result) && !request.options.isStream) { - if (!promise) { - promise = asPromise(request); - } - if (result !== promise) { - const descriptors = Object.getOwnPropertyDescriptors(promise); - for (const key in descriptors) { - if (key in result) { - // eslint-disable-next-line @typescript-eslint/no-dynamic-delete - delete descriptors[key]; - } - } - // eslint-disable-next-line @typescript-eslint/no-floating-promises - Object.defineProperties(result, descriptors); - result.cancel = promise.cancel; - } - } - return result; + return defaults.handlers[iteration++](newOptions, iteration === defaults.handlers.length ? getPromiseOrStream : iterateHandlers); }; - return iterateHandlers(request.options); + // TODO: Remove this in Got 12. + if (is_1.default.plainObject(url)) { + const mergedOptions = { + ...url, + ...options + }; + core_1.setNonEnumerableProperties([url, options], mergedOptions); + options = mergedOptions; + url = undefined; + } + try { + // Call `init` hooks + let initHookError; + try { + callInitHooks(defaults.options.hooks.init, options); + callInitHooks((_a = options.hooks) === null || _a === void 0 ? void 0 : _a.init, options); + } + catch (error) { + initHookError = error; + } + // Normalize options & call handlers + const normalizedOptions = normalizeArguments(url, options, _defaults !== null && _defaults !== void 0 ? _defaults : defaults.options); + normalizedOptions[core_1.kIsNormalizedAlready] = true; + if (initHookError) { + throw new as_promise_1.RequestError(initHookError.message, initHookError, normalizedOptions); + } + return iterateHandlers(normalizedOptions); + } + catch (error) { + if (options.isStream) { + throw error; + } + else { + return create_rejection_1.default(error, defaults.options.hooks.beforeError, (_b = options.hooks) === null || _b === void 0 ? void 0 : _b.beforeError); + } + } }); got.extend = (...instancesOrOptions) => { - const options = new Options(undefined, undefined, defaults.options); - const handlers = [...defaults.handlers]; - let mutableDefaults; + const optionsArray = [defaults.options]; + let handlers = [...defaults._rawHandlers]; + let isMutableDefaults; for (const value of instancesOrOptions) { if (isGotInstance(value)) { - options.merge(value.defaults.options); - handlers.push(...value.defaults.handlers); - mutableDefaults = value.defaults.mutableDefaults; + optionsArray.push(value.defaults.options); + handlers.push(...value.defaults._rawHandlers); + isMutableDefaults = value.defaults.mutableDefaults; } else { - options.merge(value); - if (value.handlers) { + optionsArray.push(value); + if ('handlers' in value) { handlers.push(...value.handlers); } - mutableDefaults = value.mutableDefaults; + isMutableDefaults = value.mutableDefaults; } } + handlers = handlers.filter(handler => handler !== exports.defaultHandler); + if (handlers.length === 0) { + handlers.push(exports.defaultHandler); + } return create({ - options, + options: mergeOptions(...optionsArray), handlers, - mutableDefaults: Boolean(mutableDefaults), + mutableDefaults: Boolean(isMutableDefaults) }); }; // Pagination const paginateEach = (async function* (url, options) { - let normalizedOptions = new Options(url, options, defaults.options); + // TODO: Remove this `@ts-expect-error` when upgrading to TypeScript 4. + // Error: Argument of type 'Merge> | undefined' is not assignable to parameter of type 'Options | undefined'. + // @ts-expect-error + let normalizedOptions = normalizeArguments(url, options, defaults.options); normalizedOptions.resolveBodyOnly = false; - const { pagination } = normalizedOptions; - assert.function_(pagination.transform); - assert.function_(pagination.shouldContinue); - assert.function_(pagination.filter); - assert.function_(pagination.paginate); - assert.number(pagination.countLimit); - assert.number(pagination.requestLimit); - assert.number(pagination.backoff); - const allItems = []; + const pagination = normalizedOptions.pagination; + if (!is_1.default.object(pagination)) { + throw new TypeError('`options.pagination` must be implemented'); + } + const all = []; let { countLimit } = pagination; let numberOfRequests = 0; while (numberOfRequests < pagination.requestLimit) { @@ -112,45 +172,37 @@ const create = (defaults) => { // eslint-disable-next-line no-await-in-loop await delay(pagination.backoff); } + // @ts-expect-error FIXME! + // TODO: Throw when result is not an instance of Response // eslint-disable-next-line no-await-in-loop - const response = (await got(undefined, undefined, normalizedOptions)); + const result = (await got(undefined, undefined, normalizedOptions)); // eslint-disable-next-line no-await-in-loop - const parsed = await pagination.transform(response); - const currentItems = []; - assert.array(parsed); + const parsed = await pagination.transform(result); + const current = []; for (const item of parsed) { - if (pagination.filter({ item, currentItems, allItems })) { - if (!pagination.shouldContinue({ item, currentItems, allItems })) { + if (pagination.filter(item, all, current)) { + if (!pagination.shouldContinue(item, all, current)) { return; } yield item; if (pagination.stackAllItems) { - allItems.push(item); + all.push(item); } - currentItems.push(item); + current.push(item); if (--countLimit <= 0) { return; } } } - const optionsToMerge = pagination.paginate({ - response, - currentItems, - allItems, - }); + const optionsToMerge = pagination.paginate(result, all, current); if (optionsToMerge === false) { return; } - if (optionsToMerge === response.request.options) { - normalizedOptions = response.request.options; + if (optionsToMerge === result.request.options) { + normalizedOptions = result.request.options; } - else { - normalizedOptions.merge(optionsToMerge); - assert.any([is.urlInstance, is.undefined], optionsToMerge.url); - if (optionsToMerge.url !== undefined) { - normalizedOptions.prefixUrl = ''; - normalizedOptions.url = optionsToMerge.url; - } + else if (optionsToMerge !== undefined) { + normalizedOptions = normalizeArguments(undefined, optionsToMerge, normalizedOptions); } numberOfRequests++; } @@ -170,18 +222,19 @@ const create = (defaults) => { // Shortcuts for (const method of aliases) { got[method] = ((url, options) => got(url, { ...options, method })); - got.stream[method] = ((url, options) => got(url, { ...options, method, isStream: true })); - } - if (!defaults.mutableDefaults) { - Object.freeze(defaults.handlers); - defaults.options.freeze(); + got.stream[method] = ((url, options) => { + return got(url, { ...options, method, isStream: true }); + }); } + Object.assign(got, errors); Object.defineProperty(got, 'defaults', { - value: defaults, - writable: false, - configurable: false, - enumerable: true, + value: defaults.mutableDefaults ? defaults : deep_freeze_1.default(defaults), + writable: defaults.mutableDefaults, + configurable: defaults.mutableDefaults, + enumerable: true }); + got.mergeOptions = mergeOptions; return got; }; -export default create; +exports.default = create; +__exportStar(require("./types"), exports); diff --git a/setup-pandoc/node_modules/got/dist/source/index.d.ts b/setup-pandoc/node_modules/got/dist/source/index.d.ts index 9447c9a7d..e65389567 100644 --- a/setup-pandoc/node_modules/got/dist/source/index.d.ts +++ b/setup-pandoc/node_modules/got/dist/source/index.d.ts @@ -1,15 +1,4 @@ -declare const got: import("./types.js").Got; +declare const got: import("./types").Got; export default got; -export { got }; -export { default as Options } from './core/options.js'; -export * from './core/options.js'; -export * from './core/response.js'; -export type { default as Request } from './core/index.js'; -export * from './core/index.js'; -export * from './core/errors.js'; -export type { Delays } from './core/timed-out.js'; -export { default as calculateRetryDelay } from './core/calculate-retry-delay.js'; -export * from './as-promise/types.js'; -export * from './types.js'; -export { default as create } from './create.js'; -export { default as parseLinkHeader } from './core/parse-link-header.js'; +export * from './create'; +export * from './as-promise'; diff --git a/setup-pandoc/node_modules/got/dist/source/index.js b/setup-pandoc/node_modules/got/dist/source/index.js index 025e2e2b7..106b1f2bf 100644 --- a/setup-pandoc/node_modules/got/dist/source/index.js +++ b/setup-pandoc/node_modules/got/dist/source/index.js @@ -1,21 +1,132 @@ -import create from './create.js'; -import Options from './core/options.js'; +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const url_1 = require("url"); +const create_1 = require("./create"); const defaults = { - options: new Options(), - handlers: [], - mutableDefaults: false, + options: { + method: 'GET', + retry: { + limit: 2, + methods: [ + 'GET', + 'PUT', + 'HEAD', + 'DELETE', + 'OPTIONS', + 'TRACE' + ], + statusCodes: [ + 408, + 413, + 429, + 500, + 502, + 503, + 504, + 521, + 522, + 524 + ], + errorCodes: [ + 'ETIMEDOUT', + 'ECONNRESET', + 'EADDRINUSE', + 'ECONNREFUSED', + 'EPIPE', + 'ENOTFOUND', + 'ENETUNREACH', + 'EAI_AGAIN' + ], + maxRetryAfter: undefined, + calculateDelay: ({ computedValue }) => computedValue + }, + timeout: {}, + headers: { + 'user-agent': 'got (https://github.com/sindresorhus/got)' + }, + hooks: { + init: [], + beforeRequest: [], + beforeRedirect: [], + beforeRetry: [], + beforeError: [], + afterResponse: [] + }, + cache: undefined, + dnsCache: undefined, + decompress: true, + throwHttpErrors: true, + followRedirect: true, + isStream: false, + responseType: 'text', + resolveBodyOnly: false, + maxRedirects: 10, + prefixUrl: '', + methodRewriting: true, + ignoreInvalidCookies: false, + context: {}, + // TODO: Set this to `true` when Got 12 gets released + http2: false, + allowGetBody: false, + https: undefined, + pagination: { + transform: (response) => { + if (response.request.options.responseType === 'json') { + return response.body; + } + return JSON.parse(response.body); + }, + paginate: response => { + if (!Reflect.has(response.headers, 'link')) { + return false; + } + const items = response.headers.link.split(','); + let next; + for (const item of items) { + const parsed = item.split(';'); + if (parsed[1].includes('next')) { + next = parsed[0].trimStart().trim(); + next = next.slice(1, -1); + break; + } + } + if (next) { + const options = { + url: new url_1.URL(next) + }; + return options; + } + return false; + }, + filter: () => true, + shouldContinue: () => true, + countLimit: Infinity, + backoff: 0, + requestLimit: 10000, + stackAllItems: true + }, + parseJson: (text) => JSON.parse(text), + stringifyJson: (object) => JSON.stringify(object), + cacheOptions: {} + }, + handlers: [create_1.defaultHandler], + mutableDefaults: false }; -const got = create(defaults); -export default got; -// TODO: Remove this in the next major version. -export { got }; -export { default as Options } from './core/options.js'; -export * from './core/options.js'; -export * from './core/response.js'; -export * from './core/index.js'; -export * from './core/errors.js'; -export { default as calculateRetryDelay } from './core/calculate-retry-delay.js'; -export * from './as-promise/types.js'; -export * from './types.js'; -export { default as create } from './create.js'; -export { default as parseLinkHeader } from './core/parse-link-header.js'; +const got = create_1.default(defaults); +exports.default = got; +// For CommonJS default export support +module.exports = got; +module.exports.default = got; +module.exports.__esModule = true; // Workaround for TS issue: https://github.com/sindresorhus/got/pull/1267 +__exportStar(require("./create"), exports); +__exportStar(require("./as-promise"), exports); diff --git a/setup-pandoc/node_modules/got/dist/source/types.d.ts b/setup-pandoc/node_modules/got/dist/source/types.d.ts index f07b9edf4..6c6b42819 100644 --- a/setup-pandoc/node_modules/got/dist/source/types.d.ts +++ b/setup-pandoc/node_modules/got/dist/source/types.d.ts @@ -1,20 +1,18 @@ -/// -import type { Buffer } from 'node:buffer'; -import type { CancelableRequest } from './as-promise/types.js'; -import type { Response } from './core/response.js'; -import type Options from './core/options.js'; -import { type PaginationOptions, type OptionsInit } from './core/options.js'; -import type Request from './core/index.js'; -type Except = Pick>; -type Merge = Except> & SecondType; +/// +import { URL } from 'url'; +import { CancelError } from 'p-cancelable'; +import { CancelableRequest, Response, Options, NormalizedOptions, Defaults as DefaultOptions, PaginationOptions, ParseError, RequestError, CacheError, ReadError, HTTPError, MaxRedirectsError, TimeoutError, UnsupportedProtocolError, UploadError } from './as-promise'; +import Request from './core'; +declare type Except = Pick>; +declare type Merge = Except> & SecondType; /** Defaults for each Got instance. */ -export type InstanceDefaults = { +export interface InstanceDefaults { /** - An object containing the default options of Got. + An object containing the default options of Got. */ - options: Options; + options: DefaultOptions; /** An array of functions. You execute them directly by calling `got()`. They are some sort of "global hooks" - these functions are called first. @@ -30,20 +28,21 @@ export type InstanceDefaults = { @default false */ mutableDefaults: boolean; -}; + _rawHandlers?: HandlerFunction[]; +} /** A Request object returned by calling Got, or any of the Got HTTP alias request functions. */ -export type GotReturn = Request | CancelableRequest; +export declare type GotReturn = Request | CancelableRequest; /** A function to handle options and returns a Request object. It acts sort of like a "global hook", and will be called before any actual request is made. */ -export type HandlerFunction = (options: Options, next: (options: Options) => T) => T | Promise; +export declare type HandlerFunction = (options: NormalizedOptions, next: (options: NormalizedOptions) => T) => T | Promise; /** The options available for `got.extend()`. */ -export type ExtendOptions = { +export interface ExtendOptions extends Options { /** An array of functions. You execute them directly by calling `got()`. They are some sort of "global hooks" - these functions are called first. @@ -59,40 +58,38 @@ export type ExtendOptions = { @default false */ mutableDefaults?: boolean; -} & OptionsInit; -export type OptionsOfTextResponseBody = Merge; -export type OptionsOfJSONResponseBody = Merge; -export type OptionsOfBufferResponseBody = Merge; -export type OptionsOfUnknownResponseBody = Merge; -export type StrictOptions = Except; -export type StreamOptions = Merge; +export declare type StreamOptions = Merge; -type ResponseBodyOnly = { +declare type ResponseBodyOnly = { resolveBodyOnly: true; }; -export type OptionsWithPagination = Merge; -}>; +export declare type OptionsWithPagination = Merge>; /** An instance of `got.paginate`. */ -export type GotPaginate = { +export interface GotPaginate { /** Same as `GotPaginate.each`. */ @@ -108,19 +105,19 @@ export type GotPaginate = { @example ``` - import got from 'got'; + (async () => { + const countLimit = 10; - const countLimit = 10; - - const pagination = got.paginate('https://api.github.com/repos/sindresorhus/got/commits', { - pagination: {countLimit} - }); + const pagination = got.paginate('https://api.github.com/repos/sindresorhus/got/commits', { + pagination: {countLimit} + }); - console.log(`Printing latest ${countLimit} Got commits (newest to oldest):`); + console.log(`Printing latest ${countLimit} Got commits (newest to oldest):`); - for await (const commitData of pagination) { - console.log(commitData.commit.message); - } + for await (const commitData of pagination) { + console.log(commitData.commit.message); + } + })(); ``` */ each: ((url: string | URL, options?: OptionsWithPagination) => AsyncIterableIterator) & ((options?: OptionsWithPagination) => AsyncIterableIterator); @@ -131,21 +128,21 @@ export type GotPaginate = { @example ``` - import got from 'got'; - - const countLimit = 10; + (async () => { + const countLimit = 10; - const results = await got.paginate.all('https://api.github.com/repos/sindresorhus/got/commits', { - pagination: {countLimit} - }); + const results = await got.paginate.all('https://api.github.com/repos/sindresorhus/got/commits', { + pagination: {countLimit} + }); - console.log(`Printing latest ${countLimit} Got commits (newest to oldest):`); - console.log(results); + console.log(`Printing latest ${countLimit} Got commits (newest to oldest):`); + console.log(results); + })(); ``` */ all: ((url: string | URL, options?: OptionsWithPagination) => Promise) & ((options?: OptionsWithPagination) => Promise); -}; -export type GotRequestFunction = { +} +export interface GotRequestFunction { (url: string | URL, options?: OptionsOfTextResponseBody): CancelableRequest>; (url: string | URL, options?: OptionsOfJSONResponseBody): CancelableRequest>; (url: string | URL, options?: OptionsOfBufferResponseBody): CancelableRequest>; @@ -160,33 +157,35 @@ export type GotRequestFunction = { (options: (Merge)): CancelableRequest; (options: (Merge)): CancelableRequest; (options: (Merge)): CancelableRequest; - (url: string | URL, options?: Merge): Request; - (options: Merge): Request; - (url: string | URL, options?: OptionsInit): CancelableRequest | Request; - (options: OptionsInit): CancelableRequest | Request; - (url: undefined, options: undefined, defaults: Options): CancelableRequest | Request; -}; + (url: string | URL, options?: Options): CancelableRequest | Request; + (options: Options): CancelableRequest | Request; +} /** All available HTTP request methods provided by Got. */ -export type HTTPAlias = 'get' | 'post' | 'put' | 'patch' | 'head' | 'delete'; -type GotStreamFunction = ((url?: string | URL, options?: Merge) => Request) & ((options?: Merge) => Request); +export declare type HTTPAlias = 'get' | 'post' | 'put' | 'patch' | 'head' | 'delete'; +interface GotStreamFunction { + (url: string | URL, options?: Merge): Request; + (options?: Merge): Request; +} /** An instance of `got.stream()`. */ -export type GotStream = GotStreamFunction & Record; +export declare type GotStream = GotStreamFunction & Record; /** An instance of `got`. */ -export type Got = { +export interface Got extends Record, GotRequestFunction { /** Sets `options.isStream` to `true`. @@ -206,19 +205,19 @@ export type Got = { @example ``` - import got from 'got'; + (async () => { + const countLimit = 10; - const countLimit = 10; + const pagination = got.paginate('https://api.github.com/repos/sindresorhus/got/commits', { + pagination: {countLimit} + }); - const pagination = got.paginate('https://api.github.com/repos/sindresorhus/got/commits', { - pagination: {countLimit} - }); - - console.log(`Printing latest ${countLimit} Got commits (newest to oldest):`); + console.log(`Printing latest ${countLimit} Got commits (newest to oldest):`); - for await (const commitData of pagination) { - console.log(commitData.commit.message); - } + for await (const commitData of pagination) { + console.log(commitData.commit.message); + } + })(); ``` */ paginate: GotPaginate; @@ -227,6 +226,54 @@ export type Got = { */ defaults: InstanceDefaults; /** + An error to be thrown when a cache method fails. For example, if the database goes down or there's a filesystem error. + Contains a `code` property with `ERR_CACHE_ACCESS` or a more specific failure code. + */ + CacheError: typeof CacheError; + /** + An error to be thrown when a request fails. Contains a `code` property with error class code, like `ECONNREFUSED`. + If there is no specific code supplied, `code` defaults to `ERR_GOT_REQUEST_ERROR`. + */ + RequestError: typeof RequestError; + /** + An error to be thrown when reading from response stream fails. Contains a `code` property with + `ERR_READING_RESPONSE_STREAM` or a more specific failure code. + */ + ReadError: typeof ReadError; + /** + An error to be thrown when server response code is 2xx, and parsing body fails. Includes a + `response` property. Contains a `code` property with `ERR_BODY_PARSE_FAILURE` or a more specific failure code. + */ + ParseError: typeof ParseError; + /** + An error to be thrown when the server response code is not 2xx nor 3xx if `options.followRedirect` is `true`, but always except for 304. + Includes a `response` property. Contains a `code` property with `ERR_NON_2XX_3XX_RESPONSE` or a more specific failure code. + */ + HTTPError: typeof HTTPError; + /** + An error to be thrown when the server redirects you more than ten times. + Includes a `response` property. Contains a `code` property with `ERR_TOO_MANY_REDIRECTS`. + */ + MaxRedirectsError: typeof MaxRedirectsError; + /** + An error to be thrown when given an unsupported protocol. Contains a `code` property with `ERR_UNSUPPORTED_PROTOCOL`. + */ + UnsupportedProtocolError: typeof UnsupportedProtocolError; + /** + An error to be thrown when the request is aborted due to a timeout. + Includes an `event` and `timings` property. Contains a `code` property with `ETIMEDOUT`. + */ + TimeoutError: typeof TimeoutError; + /** + An error to be thrown when the request body is a stream and an error occurs while reading from that stream. + Contains a `code` property with `ERR_UPLOAD` or a more specific failure code. + */ + UploadError: typeof UploadError; + /** + An error to be thrown when the request is aborted with `.cancel()`. Contains a `code` property with `ERR_CANCELED`. + */ + CancelError: typeof CancelError; + /** Configure a new `got` instance with default `options`. The `options` are merged with the parent instance's `defaults.options` using `got.mergeOptions`. You can access the resolved options with the `.defaults` property on the instance. @@ -238,9 +285,7 @@ export type Got = { - handlers are stored in an array (you can access them through `instance.defaults.handlers`). @example - ``` - import got from 'got'; - + ```js const client = got.extend({ prefixUrl: 'https://example.com', headers: { @@ -257,5 +302,43 @@ export type Got = { ``` */ extend: (...instancesOrOptions: Array) => Got; -} & Record & GotRequestFunction; + /** + Merges multiple `got` instances into the parent. + */ + mergeInstances: (parent: Got, ...instances: Got[]) => Got; + /** + Extends parent options. + Avoid using [object spread](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#Spread_in_object_literals) as it doesn't work recursively. + + Options are deeply merged to a new object. The value of each key is determined as follows: + + - If the new property is not defined, the old value is used. + - If the new property is explicitly set to `undefined`: + - If the parent property is a plain `object`, the parent value is deeply cloned. + - Otherwise, `undefined` is used. + - If the parent value is an instance of `URLSearchParams`: + - If the new value is a `string`, an `object` or an instance of `URLSearchParams`, a new `URLSearchParams` instance is created. + The values are merged using [`urlSearchParams.append(key, value)`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/append). + The keys defined in the new value override the keys defined in the parent value. + - Otherwise, the only available value is `undefined`. + - If the new property is a plain `object`: + - If the parent property is a plain `object` too, both values are merged recursively into a new `object`. + - Otherwise, only the new value is deeply cloned. + - If the new property is an `Array`, it overwrites the old one with a deep clone of the new property. + - Properties that are not enumerable, such as `context`, `body`, `json`, and `form`, will not be merged. + - Otherwise, the new value is assigned to the key. + + **Note:** Only Got options are merged! Custom user options should be defined via [`options.context`](#context). + + @example + ``` + const a = {headers: {cat: 'meow', wolf: ['bark', 'wrrr']}}; + const b = {headers: {cow: 'moo', wolf: ['auuu']}}; + + {...a, ...b} // => {headers: {cow: 'moo', wolf: ['auuu']}} + got.mergeOptions(a, b) // => {headers: {cat: 'meow', cow: 'moo', wolf: ['auuu']}} + ``` + */ + mergeOptions: (...sources: Options[]) => NormalizedOptions; +} export {}; diff --git a/setup-pandoc/node_modules/got/dist/source/types.js b/setup-pandoc/node_modules/got/dist/source/types.js index cb0ff5c3b..c8ad2e549 100644 --- a/setup-pandoc/node_modules/got/dist/source/types.js +++ b/setup-pandoc/node_modules/got/dist/source/types.js @@ -1 +1,2 @@ -export {}; +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/setup-pandoc/node_modules/got/dist/source/utils/deep-freeze.d.ts b/setup-pandoc/node_modules/got/dist/source/utils/deep-freeze.d.ts new file mode 100644 index 000000000..7c33e5c6c --- /dev/null +++ b/setup-pandoc/node_modules/got/dist/source/utils/deep-freeze.d.ts @@ -0,0 +1 @@ +export default function deepFreeze>(object: T): Readonly; diff --git a/setup-pandoc/node_modules/got/dist/source/utils/deep-freeze.js b/setup-pandoc/node_modules/got/dist/source/utils/deep-freeze.js new file mode 100644 index 000000000..a696d4efb --- /dev/null +++ b/setup-pandoc/node_modules/got/dist/source/utils/deep-freeze.js @@ -0,0 +1,12 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const is_1 = require("@sindresorhus/is"); +function deepFreeze(object) { + for (const value of Object.values(object)) { + if (is_1.default.plainObject(value) || is_1.default.array(value)) { + deepFreeze(value); + } + } + return Object.freeze(object); +} +exports.default = deepFreeze; diff --git a/setup-pandoc/node_modules/got/dist/source/utils/deprecation-warning.d.ts b/setup-pandoc/node_modules/got/dist/source/utils/deprecation-warning.d.ts new file mode 100644 index 000000000..1a08f9628 --- /dev/null +++ b/setup-pandoc/node_modules/got/dist/source/utils/deprecation-warning.d.ts @@ -0,0 +1,2 @@ +declare const _default: (message: string) => void; +export default _default; diff --git a/setup-pandoc/node_modules/got/dist/source/utils/deprecation-warning.js b/setup-pandoc/node_modules/got/dist/source/utils/deprecation-warning.js new file mode 100644 index 000000000..3cfb7b233 --- /dev/null +++ b/setup-pandoc/node_modules/got/dist/source/utils/deprecation-warning.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const alreadyWarned = new Set(); +exports.default = (message) => { + if (alreadyWarned.has(message)) { + return; + } + alreadyWarned.add(message); + // @ts-expect-error Missing types. + process.emitWarning(`Got: ${message}`, { + type: 'DeprecationWarning' + }); +}; diff --git a/setup-pandoc/node_modules/got/license b/setup-pandoc/node_modules/got/license index fa7ceba3e..e7af2f771 100644 --- a/setup-pandoc/node_modules/got/license +++ b/setup-pandoc/node_modules/got/license @@ -1,6 +1,6 @@ MIT License -Copyright (c) Sindre Sorhus (https://sindresorhus.com) +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: diff --git a/setup-pandoc/node_modules/got/node_modules/get-stream/license b/setup-pandoc/node_modules/got/node_modules/get-stream/license deleted file mode 100644 index fa7ceba3e..000000000 --- a/setup-pandoc/node_modules/got/node_modules/get-stream/license +++ /dev/null @@ -1,9 +0,0 @@ -MIT License - -Copyright (c) Sindre Sorhus (https://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. diff --git a/setup-pandoc/node_modules/got/node_modules/get-stream/package.json b/setup-pandoc/node_modules/got/node_modules/get-stream/package.json deleted file mode 100644 index bfd9a001d..000000000 --- a/setup-pandoc/node_modules/got/node_modules/get-stream/package.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "name": "get-stream", - "version": "8.0.1", - "description": "Get a stream as a string, Buffer, ArrayBuffer or array", - "license": "MIT", - "repository": "sindresorhus/get-stream", - "funding": "https://github.com/sponsors/sindresorhus", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "https://sindresorhus.com" - }, - "type": "module", - "exports": { - "types": "./source/index.d.ts", - "default": "./source/index.js" - }, - "engines": { - "node": ">=16" - }, - "scripts": { - "benchmark": "node benchmarks/index.js", - "test": "xo && ava && tsd --typings=source/index.d.ts --files=source/index.test-d.ts" - }, - "files": [ - "source", - "!*.test-d.ts" - ], - "keywords": [ - "get", - "stream", - "promise", - "concat", - "string", - "text", - "buffer", - "read", - "data", - "consume", - "readable", - "readablestream", - "object", - "concat" - ], - "devDependencies": { - "@types/node": "^20.5.0", - "ava": "^5.3.1", - "precise-now": "^2.0.0", - "stream-json": "^1.8.0", - "tsd": "^0.28.1", - "xo": "^0.56.0" - } -} diff --git a/setup-pandoc/node_modules/got/node_modules/get-stream/readme.md b/setup-pandoc/node_modules/got/node_modules/get-stream/readme.md deleted file mode 100644 index 7f04b9471..000000000 --- a/setup-pandoc/node_modules/got/node_modules/get-stream/readme.md +++ /dev/null @@ -1,291 +0,0 @@ -# get-stream - -> Get a stream as a string, Buffer, ArrayBuffer or array - -## Features - -- Works in any JavaScript environment ([Node.js](#nodejs-streams), [browsers](#web-streams), etc.). -- Supports [text streams](#getstreamstream-options), [binary streams](#getstreamasbufferstream-options) and [object streams](#getstreamasarraystream-options). -- Supports [async iterables](#async-iterables). -- Can set a [maximum stream size](#maxbuffer). -- Returns [partially read data](#errors) when the stream errors. -- [Fast](#benchmarks). - -## Install - -```sh -npm install get-stream -``` - -## Usage - -### Node.js streams - -```js -import fs from 'node:fs'; -import getStream from 'get-stream'; - -const stream = fs.createReadStream('unicorn.txt'); - -console.log(await getStream(stream)); -/* - ,,))))))));, - __)))))))))))))), -\|/ -\(((((''''((((((((. --*-==//////(('' . `)))))), -/|\ ))| o ;-. '((((( ,(, - ( `| / ) ;))))' ,_))^;(~ - | | | ,))((((_ _____------~~~-. %,;(;(>';'~ - o_); ; )))(((` ~---~ `:: \ %%~~)(v;(`('~ - ; ''''```` `: `:::|\,__,%% );`'; ~ - | _ ) / `:|`----' `-' - ______/\/~ | / / - /~;;.____/;;' / ___--,-( `;;;/ - / // _;______;'------~~~~~ /;;/\ / - // | | / ; \;;,\ - (<_ | ; /',/-----' _> - \_| ||_ //~;~~~~~~~~~ - `\_| (,~~ - \~\ - ~~ -*/ -``` - -### Web streams - -```js -import getStream from 'get-stream'; - -const {body: readableStream} = await fetch('https://example.com'); -console.log(await getStream(readableStream)); -``` - -### Async iterables - -```js -import {opendir} from 'node:fs/promises'; -import {getStreamAsArray} from 'get-stream'; - -const asyncIterable = await opendir(directory); -console.log(await getStreamAsArray(asyncIterable)); -``` - -## API - -The following methods read the stream's contents and return it as a promise. - -### getStream(stream, options?) - -`stream`: [`stream.Readable`](https://nodejs.org/api/stream.html#class-streamreadable), [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream), or [`AsyncIterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols)\ -`options`: [`Options`](#options) - -Get the given `stream` as a string. - -### getStreamAsBuffer(stream, options?) - -Get the given `stream` as a Node.js [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer). - -```js -import {getStreamAsBuffer} from 'get-stream'; - -const stream = fs.createReadStream('unicorn.png'); -console.log(await getStreamAsBuffer(stream)); -``` - -### getStreamAsArrayBuffer(stream, options?) - -Get the given `stream` as an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). - -```js -import {getStreamAsArrayBuffer} from 'get-stream'; - -const {body: readableStream} = await fetch('https://example.com'); -console.log(await getStreamAsArrayBuffer(readableStream)); -``` - -### getStreamAsArray(stream, options?) - -Get the given `stream` as an array. Unlike [other methods](#api), this supports [streams of objects](https://nodejs.org/api/stream.html#object-mode). - -```js -import {getStreamAsArray} from 'get-stream'; - -const {body: readableStream} = await fetch('https://example.com'); -console.log(await getStreamAsArray(readableStream)); -``` - -#### options - -Type: `object` - -##### maxBuffer - -Type: `number`\ -Default: `Infinity` - -Maximum length of the stream. If exceeded, the promise will be rejected with a `MaxBufferError`. - -Depending on the [method](#api), the length is measured with [`string.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length), [`buffer.length`](https://nodejs.org/api/buffer.html#buflength), [`arrayBuffer.byteLength`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/byteLength) or [`array.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length). - -## Errors - -If the stream errors, the returned promise will be rejected with the `error`. Any contents already read from the stream will be set to `error.bufferedData`, which is a `string`, a `Buffer`, an `ArrayBuffer` or an array depending on the [method used](#api). - -```js -import getStream from 'get-stream'; - -try { - await getStream(streamThatErrorsAtTheEnd('unicorn')); -} catch (error) { - console.log(error.bufferedData); - //=> 'unicorn' -} -``` - -## Tips - -### Alternatives - -If you do not need the [`maxBuffer`](#maxbuffer) option, [`error.bufferedData`](#errors), nor browser support, you can use the following methods instead of this package. - -#### [`streamConsumers.text()`](https://nodejs.org/api/webstreams.html#streamconsumerstextstream) - -```js -import fs from 'node:fs'; -import {text} from 'node:stream/consumers'; - -const stream = fs.createReadStream('unicorn.txt', {encoding: 'utf8'}); -console.log(await text(stream)) -``` - -#### [`streamConsumers.buffer()`](https://nodejs.org/api/webstreams.html#streamconsumersbufferstream) - -```js -import {buffer} from 'node:stream/consumers'; - -console.log(await buffer(stream)) -``` - -#### [`streamConsumers.arrayBuffer()`](https://nodejs.org/api/webstreams.html#streamconsumersarraybufferstream) - -```js -import {arrayBuffer} from 'node:stream/consumers'; - -console.log(await arrayBuffer(stream)) -``` - -#### [`readable.toArray()`](https://nodejs.org/api/stream.html#readabletoarrayoptions) - -```js -console.log(await stream.toArray()) -``` - -#### [`Array.fromAsync()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fromAsync) - -If your [environment supports it](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fromAsync#browser_compatibility): - -```js -console.log(await Array.fromAsync(stream)) -``` - -### Non-UTF-8 encoding - -When all of the following conditions apply: - - [`getStream()`](#getstreamstream-options) is used (as opposed to [`getStreamAsBuffer()`](#getstreamasbufferstream-options) or [`getStreamAsArrayBuffer()`](#getstreamasarraybufferstream-options)) - - The stream is binary (not text) - - The stream's encoding is not UTF-8 (for example, it is UTF-16, hexadecimal, or Base64) - -Then the stream must be decoded using a transform stream like [`TextDecoderStream`](https://developer.mozilla.org/en-US/docs/Web/API/TextDecoderStream) or [`b64`](https://github.com/hapijs/b64). - -```js -import getStream from 'get-stream'; - -const textDecoderStream = new TextDecoderStream('utf-16le'); -const {body: readableStream} = await fetch('https://example.com'); -console.log(await getStream(readableStream.pipeThrough(textDecoderStream))); -``` - -### Blobs - -[`getStreamAsArrayBuffer()`](#getstreamasarraybufferstream-options) can be used to create [Blobs](https://developer.mozilla.org/en-US/docs/Web/API/Blob). - -```js -import {getStreamAsArrayBuffer} from 'get-stream'; - -const stream = fs.createReadStream('unicorn.txt'); -console.log(new Blob([await getStreamAsArrayBuffer(stream)])); -``` - -### JSON streaming - -[`getStreamAsArray()`](#getstreamasarraystream-options) can be combined with JSON streaming utilities to parse JSON incrementally. - -```js -import fs from 'node:fs'; -import {compose as composeStreams} from 'node:stream'; -import {getStreamAsArray} from 'get-stream'; -import streamJson from 'stream-json'; -import streamJsonArray from 'stream-json/streamers/StreamArray.js'; - -const stream = fs.createReadStream('big-array-of-objects.json'); -console.log(await getStreamAsArray( - composeStreams(stream, streamJson.parser(), streamJsonArray.streamArray()), -)); -``` - -## Benchmarks - -### Node.js stream (100 MB, binary) - -- `getStream()`: 142ms -- `text()`: 139ms -- `getStreamAsBuffer()`: 106ms -- `buffer()`: 83ms -- `getStreamAsArrayBuffer()`: 105ms -- `arrayBuffer()`: 81ms -- `getStreamAsArray()`: 24ms -- `stream.toArray()`: 21ms - -### Node.js stream (100 MB, text) - -- `getStream()`: 90ms -- `text()`: 89ms -- `getStreamAsBuffer()`: 127ms -- `buffer()`: 192ms -- `getStreamAsArrayBuffer()`: 129ms -- `arrayBuffer()`: 195ms -- `getStreamAsArray()`: 89ms -- `stream.toArray()`: 90ms - -### Web ReadableStream (100 MB, binary) - -- `getStream()`: 223ms -- `text()`: 221ms -- `getStreamAsBuffer()`: 182ms -- `buffer()`: 153ms -- `getStreamAsArrayBuffer()`: 171ms -- `arrayBuffer()`: 155ms -- `getStreamAsArray()`: 83ms - -### Web ReadableStream (100 MB, text) - -- `getStream()`: 141ms -- `text()`: 139ms -- `getStreamAsBuffer()`: 91ms -- `buffer()`: 80ms -- `getStreamAsArrayBuffer()`: 89ms -- `arrayBuffer()`: 81ms -- `getStreamAsArray()`: 21ms - -[Benchmarks' source file](benchmarks/index.js). - -## FAQ - -### How is this different from [`concat-stream`](https://github.com/maxogden/concat-stream)? - -This module accepts a stream instead of being one and returns a promise instead of using a callback. The API is simpler and it only supports returning a string, `Buffer`, an `ArrayBuffer` or an array. It doesn't have a fragile type inference. You explicitly choose what you want. And it doesn't depend on the huge `readable-stream` package. - -## Related - -- [get-stdin](https://github.com/sindresorhus/get-stdin) - Get stdin as a string or buffer -- [into-stream](https://github.com/sindresorhus/into-stream) - The opposite of this package diff --git a/setup-pandoc/node_modules/got/node_modules/get-stream/source/array-buffer.js b/setup-pandoc/node_modules/got/node_modules/get-stream/source/array-buffer.js deleted file mode 100644 index a547405e0..000000000 --- a/setup-pandoc/node_modules/got/node_modules/get-stream/source/array-buffer.js +++ /dev/null @@ -1,84 +0,0 @@ -import {getStreamContents} from './contents.js'; -import {noop, throwObjectStream, getLengthProp} from './utils.js'; - -export async function getStreamAsArrayBuffer(stream, options) { - return getStreamContents(stream, arrayBufferMethods, options); -} - -const initArrayBuffer = () => ({contents: new ArrayBuffer(0)}); - -const useTextEncoder = chunk => textEncoder.encode(chunk); -const textEncoder = new TextEncoder(); - -const useUint8Array = chunk => new Uint8Array(chunk); - -const useUint8ArrayWithOffset = chunk => new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength); - -const truncateArrayBufferChunk = (convertedChunk, chunkSize) => convertedChunk.slice(0, chunkSize); - -// `contents` is an increasingly growing `Uint8Array`. -const addArrayBufferChunk = (convertedChunk, {contents, length: previousLength}, length) => { - const newContents = hasArrayBufferResize() ? resizeArrayBuffer(contents, length) : resizeArrayBufferSlow(contents, length); - new Uint8Array(newContents).set(convertedChunk, previousLength); - return newContents; -}; - -// Without `ArrayBuffer.resize()`, `contents` size is always a power of 2. -// This means its last bytes are zeroes (not stream data), which need to be -// trimmed at the end with `ArrayBuffer.slice()`. -const resizeArrayBufferSlow = (contents, length) => { - if (length <= contents.byteLength) { - return contents; - } - - const arrayBuffer = new ArrayBuffer(getNewContentsLength(length)); - new Uint8Array(arrayBuffer).set(new Uint8Array(contents), 0); - return arrayBuffer; -}; - -// With `ArrayBuffer.resize()`, `contents` size matches exactly the size of -// the stream data. It does not include extraneous zeroes to trim at the end. -// The underlying `ArrayBuffer` does allocate a number of bytes that is a power -// of 2, but those bytes are only visible after calling `ArrayBuffer.resize()`. -const resizeArrayBuffer = (contents, length) => { - if (length <= contents.maxByteLength) { - contents.resize(length); - return contents; - } - - const arrayBuffer = new ArrayBuffer(length, {maxByteLength: getNewContentsLength(length)}); - new Uint8Array(arrayBuffer).set(new Uint8Array(contents), 0); - return arrayBuffer; -}; - -// Retrieve the closest `length` that is both >= and a power of 2 -const getNewContentsLength = length => SCALE_FACTOR ** Math.ceil(Math.log(length) / Math.log(SCALE_FACTOR)); - -const SCALE_FACTOR = 2; - -const finalizeArrayBuffer = ({contents, length}) => hasArrayBufferResize() ? contents : contents.slice(0, length); - -// `ArrayBuffer.slice()` is slow. When `ArrayBuffer.resize()` is available -// (Node >=20.0.0, Safari >=16.4 and Chrome), we can use it instead. -// eslint-disable-next-line no-warning-comments -// TODO: remove after dropping support for Node 20. -// eslint-disable-next-line no-warning-comments -// TODO: use `ArrayBuffer.transferToFixedLength()` instead once it is available -const hasArrayBufferResize = () => 'resize' in ArrayBuffer.prototype; - -const arrayBufferMethods = { - init: initArrayBuffer, - convertChunk: { - string: useTextEncoder, - buffer: useUint8Array, - arrayBuffer: useUint8Array, - dataView: useUint8ArrayWithOffset, - typedArray: useUint8ArrayWithOffset, - others: throwObjectStream, - }, - getSize: getLengthProp, - truncateChunk: truncateArrayBufferChunk, - addChunk: addArrayBufferChunk, - getFinalChunk: noop, - finalize: finalizeArrayBuffer, -}; diff --git a/setup-pandoc/node_modules/got/node_modules/get-stream/source/array.js b/setup-pandoc/node_modules/got/node_modules/get-stream/source/array.js deleted file mode 100644 index 468bad119..000000000 --- a/setup-pandoc/node_modules/got/node_modules/get-stream/source/array.js +++ /dev/null @@ -1,32 +0,0 @@ -import {getStreamContents} from './contents.js'; -import {identity, noop, getContentsProp} from './utils.js'; - -export async function getStreamAsArray(stream, options) { - return getStreamContents(stream, arrayMethods, options); -} - -const initArray = () => ({contents: []}); - -const increment = () => 1; - -const addArrayChunk = (convertedChunk, {contents}) => { - contents.push(convertedChunk); - return contents; -}; - -const arrayMethods = { - init: initArray, - convertChunk: { - string: identity, - buffer: identity, - arrayBuffer: identity, - dataView: identity, - typedArray: identity, - others: identity, - }, - getSize: increment, - truncateChunk: noop, - addChunk: addArrayChunk, - getFinalChunk: noop, - finalize: getContentsProp, -}; diff --git a/setup-pandoc/node_modules/got/node_modules/get-stream/source/buffer.js b/setup-pandoc/node_modules/got/node_modules/get-stream/source/buffer.js deleted file mode 100644 index 7d22d78db..000000000 --- a/setup-pandoc/node_modules/got/node_modules/get-stream/source/buffer.js +++ /dev/null @@ -1,20 +0,0 @@ -import {getStreamAsArrayBuffer} from './array-buffer.js'; - -export async function getStreamAsBuffer(stream, options) { - if (!('Buffer' in globalThis)) { - throw new Error('getStreamAsBuffer() is only supported in Node.js'); - } - - try { - return arrayBufferToNodeBuffer(await getStreamAsArrayBuffer(stream, options)); - } catch (error) { - if (error.bufferedData !== undefined) { - error.bufferedData = arrayBufferToNodeBuffer(error.bufferedData); - } - - throw error; - } -} - -// eslint-disable-next-line n/prefer-global/buffer -const arrayBufferToNodeBuffer = arrayBuffer => globalThis.Buffer.from(arrayBuffer); diff --git a/setup-pandoc/node_modules/got/node_modules/get-stream/source/contents.js b/setup-pandoc/node_modules/got/node_modules/get-stream/source/contents.js deleted file mode 100644 index 2ca36f2e1..000000000 --- a/setup-pandoc/node_modules/got/node_modules/get-stream/source/contents.js +++ /dev/null @@ -1,101 +0,0 @@ -export const getStreamContents = async (stream, {init, convertChunk, getSize, truncateChunk, addChunk, getFinalChunk, finalize}, {maxBuffer = Number.POSITIVE_INFINITY} = {}) => { - if (!isAsyncIterable(stream)) { - throw new Error('The first argument must be a Readable, a ReadableStream, or an async iterable.'); - } - - const state = init(); - state.length = 0; - - try { - for await (const chunk of stream) { - const chunkType = getChunkType(chunk); - const convertedChunk = convertChunk[chunkType](chunk, state); - appendChunk({convertedChunk, state, getSize, truncateChunk, addChunk, maxBuffer}); - } - - appendFinalChunk({state, convertChunk, getSize, truncateChunk, addChunk, getFinalChunk, maxBuffer}); - return finalize(state); - } catch (error) { - error.bufferedData = finalize(state); - throw error; - } -}; - -const appendFinalChunk = ({state, getSize, truncateChunk, addChunk, getFinalChunk, maxBuffer}) => { - const convertedChunk = getFinalChunk(state); - if (convertedChunk !== undefined) { - appendChunk({convertedChunk, state, getSize, truncateChunk, addChunk, maxBuffer}); - } -}; - -const appendChunk = ({convertedChunk, state, getSize, truncateChunk, addChunk, maxBuffer}) => { - const chunkSize = getSize(convertedChunk); - const newLength = state.length + chunkSize; - - if (newLength <= maxBuffer) { - addNewChunk(convertedChunk, state, addChunk, newLength); - return; - } - - const truncatedChunk = truncateChunk(convertedChunk, maxBuffer - state.length); - - if (truncatedChunk !== undefined) { - addNewChunk(truncatedChunk, state, addChunk, maxBuffer); - } - - throw new MaxBufferError(); -}; - -const addNewChunk = (convertedChunk, state, addChunk, newLength) => { - state.contents = addChunk(convertedChunk, state, newLength); - state.length = newLength; -}; - -const isAsyncIterable = stream => typeof stream === 'object' && stream !== null && typeof stream[Symbol.asyncIterator] === 'function'; - -const getChunkType = chunk => { - const typeOfChunk = typeof chunk; - - if (typeOfChunk === 'string') { - return 'string'; - } - - if (typeOfChunk !== 'object' || chunk === null) { - return 'others'; - } - - // eslint-disable-next-line n/prefer-global/buffer - if (globalThis.Buffer?.isBuffer(chunk)) { - return 'buffer'; - } - - const prototypeName = objectToString.call(chunk); - - if (prototypeName === '[object ArrayBuffer]') { - return 'arrayBuffer'; - } - - if (prototypeName === '[object DataView]') { - return 'dataView'; - } - - if ( - Number.isInteger(chunk.byteLength) - && Number.isInteger(chunk.byteOffset) - && objectToString.call(chunk.buffer) === '[object ArrayBuffer]' - ) { - return 'typedArray'; - } - - return 'others'; -}; - -const {toString: objectToString} = Object.prototype; - -export class MaxBufferError extends Error { - name = 'MaxBufferError'; - - constructor() { - super('maxBuffer exceeded'); - } -} diff --git a/setup-pandoc/node_modules/got/node_modules/get-stream/source/index.d.ts b/setup-pandoc/node_modules/got/node_modules/get-stream/source/index.d.ts deleted file mode 100644 index 0a456ca16..000000000 --- a/setup-pandoc/node_modules/got/node_modules/get-stream/source/index.d.ts +++ /dev/null @@ -1,119 +0,0 @@ -import {type Readable} from 'node:stream'; -import {type Buffer} from 'node:buffer'; - -export class MaxBufferError extends Error { - readonly name: 'MaxBufferError'; - constructor(); -} - -type TextStreamItem = string | Buffer | ArrayBuffer | ArrayBufferView; -export type AnyStream = Readable | ReadableStream | AsyncIterable; - -export type Options = { - /** - Maximum length of the stream. If exceeded, the promise will be rejected with a `MaxBufferError`. - - Depending on the [method](#api), the length is measured with [`string.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length), [`buffer.length`](https://nodejs.org/api/buffer.html#buflength), [`arrayBuffer.byteLength`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/byteLength) or [`array.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length). - - @default Infinity - */ - readonly maxBuffer?: number; -}; - -/** -Get the given `stream` as a string. - -@returns The stream's contents as a promise. - -@example -``` -import fs from 'node:fs'; -import getStream from 'get-stream'; - -const stream = fs.createReadStream('unicorn.txt'); - -console.log(await getStream(stream)); -// ,,))))))));, -// __)))))))))))))), -// \|/ -\(((((''''((((((((. -// -*-==//////(('' . `)))))), -// /|\ ))| o ;-. '((((( ,(, -// ( `| / ) ;))))' ,_))^;(~ -// | | | ,))((((_ _____------~~~-. %,;(;(>';'~ -// o_); ; )))(((` ~---~ `:: \ %%~~)(v;(`('~ -// ; ''''```` `: `:::|\,__,%% );`'; ~ -// | _ ) / `:|`----' `-' -// ______/\/~ | / / -// /~;;.____/;;' / ___--,-( `;;;/ -// / // _;______;'------~~~~~ /;;/\ / -// // | | / ; \;;,\ -// (<_ | ; /',/-----' _> -// \_| ||_ //~;~~~~~~~~~ -// `\_| (,~~ -// \~\ -// ~~ -``` - -@example -``` -import getStream from 'get-stream'; - -const {body: readableStream} = await fetch('https://example.com'); -console.log(await getStream(readableStream)); -``` - -@example -``` -import {opendir} from 'node:fs/promises'; -import {getStreamAsArray} from 'get-stream'; - -const asyncIterable = await opendir(directory); -console.log(await getStreamAsArray(asyncIterable)); -``` -*/ -export default function getStream(stream: AnyStream, options?: Options): Promise; - -/** -Get the given `stream` as a Node.js [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer). - -@returns The stream's contents as a promise. - -@example -``` -import {getStreamAsBuffer} from 'get-stream'; - -const stream = fs.createReadStream('unicorn.png'); -console.log(await getStreamAsBuffer(stream)); -``` -*/ -export function getStreamAsBuffer(stream: AnyStream, options?: Options): Promise; - -/** -Get the given `stream` as an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). - -@returns The stream's contents as a promise. - -@example -``` -import {getStreamAsArrayBuffer} from 'get-stream'; - -const {body: readableStream} = await fetch('https://example.com'); -console.log(await getStreamAsArrayBuffer(readableStream)); -``` -*/ -export function getStreamAsArrayBuffer(stream: AnyStream, options?: Options): Promise; - -/** -Get the given `stream` as an array. Unlike [other methods](#api), this supports [streams of objects](https://nodejs.org/api/stream.html#object-mode). - -@returns The stream's contents as a promise. - -@example -``` -import {getStreamAsArray} from 'get-stream'; - -const {body: readableStream} = await fetch('https://example.com'); -console.log(await getStreamAsArray(readableStream)); -``` -*/ -export function getStreamAsArray(stream: AnyStream, options?: Options): Promise; diff --git a/setup-pandoc/node_modules/got/node_modules/get-stream/source/index.js b/setup-pandoc/node_modules/got/node_modules/get-stream/source/index.js deleted file mode 100644 index 43c2dd4ba..000000000 --- a/setup-pandoc/node_modules/got/node_modules/get-stream/source/index.js +++ /dev/null @@ -1,5 +0,0 @@ -export {getStreamAsArray} from './array.js'; -export {getStreamAsArrayBuffer} from './array-buffer.js'; -export {getStreamAsBuffer} from './buffer.js'; -export {getStreamAsString as default} from './string.js'; -export {MaxBufferError} from './contents.js'; diff --git a/setup-pandoc/node_modules/got/node_modules/get-stream/source/string.js b/setup-pandoc/node_modules/got/node_modules/get-stream/source/string.js deleted file mode 100644 index 90f94b96a..000000000 --- a/setup-pandoc/node_modules/got/node_modules/get-stream/source/string.js +++ /dev/null @@ -1,36 +0,0 @@ -import {getStreamContents} from './contents.js'; -import {identity, getContentsProp, throwObjectStream, getLengthProp} from './utils.js'; - -export async function getStreamAsString(stream, options) { - return getStreamContents(stream, stringMethods, options); -} - -const initString = () => ({contents: '', textDecoder: new TextDecoder()}); - -const useTextDecoder = (chunk, {textDecoder}) => textDecoder.decode(chunk, {stream: true}); - -const addStringChunk = (convertedChunk, {contents}) => contents + convertedChunk; - -const truncateStringChunk = (convertedChunk, chunkSize) => convertedChunk.slice(0, chunkSize); - -const getFinalStringChunk = ({textDecoder}) => { - const finalChunk = textDecoder.decode(); - return finalChunk === '' ? undefined : finalChunk; -}; - -const stringMethods = { - init: initString, - convertChunk: { - string: identity, - buffer: useTextDecoder, - arrayBuffer: useTextDecoder, - dataView: useTextDecoder, - typedArray: useTextDecoder, - others: throwObjectStream, - }, - getSize: getLengthProp, - truncateChunk: truncateStringChunk, - addChunk: addStringChunk, - getFinalChunk: getFinalStringChunk, - finalize: getContentsProp, -}; diff --git a/setup-pandoc/node_modules/got/node_modules/get-stream/source/utils.js b/setup-pandoc/node_modules/got/node_modules/get-stream/source/utils.js deleted file mode 100644 index af8d5e297..000000000 --- a/setup-pandoc/node_modules/got/node_modules/get-stream/source/utils.js +++ /dev/null @@ -1,11 +0,0 @@ -export const identity = value => value; - -export const noop = () => undefined; - -export const getContentsProp = ({contents}) => contents; - -export const throwObjectStream = chunk => { - throw new Error(`Streams in object mode are not supported: ${String(chunk)}`); -}; - -export const getLengthProp = convertedChunk => convertedChunk.length; diff --git a/setup-pandoc/node_modules/got/package.json b/setup-pandoc/node_modules/got/package.json index 901cd3b83..c1b8f4cfa 100644 --- a/setup-pandoc/node_modules/got/package.json +++ b/setup-pandoc/node_modules/got/package.json @@ -1,21 +1,16 @@ { "name": "got", - "version": "14.2.0", + "version": "11.8.6", "description": "Human-friendly and powerful HTTP request library for Node.js", "license": "MIT", "repository": "sindresorhus/got", "funding": "https://github.com/sindresorhus/got?sponsor=1", - "type": "module", - "exports": { - "types": "./dist/source/index.d.ts", - "default": "./dist/source/index.js" - }, - "sideEffects": false, + "main": "dist/source", "engines": { - "node": ">=20" + "node": ">=10.19.0" }, "scripts": { - "test": "xo && tsc --noEmit && NODE_OPTIONS='--import=tsx/esm' ava", + "test": "xo && npm run build && nyc --reporter=html --reporter=text ava", "release": "np", "build": "del-cli dist && tsc", "prepare": "npm run build" @@ -48,77 +43,71 @@ "ky" ], "dependencies": { - "@sindresorhus/is": "^6.1.0", - "@szmarczak/http-timer": "^5.0.1", - "cacheable-lookup": "^7.0.0", - "cacheable-request": "^10.2.14", + "@sindresorhus/is": "^4.0.0", + "@szmarczak/http-timer": "^4.0.5", + "@types/cacheable-request": "^6.0.1", + "@types/responselike": "^1.0.0", + "cacheable-lookup": "^5.0.3", + "cacheable-request": "^7.0.2", "decompress-response": "^6.0.0", - "form-data-encoder": "^4.0.2", - "get-stream": "^8.0.1", - "http2-wrapper": "^2.2.1", - "lowercase-keys": "^3.0.0", - "p-cancelable": "^4.0.1", - "responselike": "^3.0.0" + "http2-wrapper": "^1.0.0-beta.5.2", + "lowercase-keys": "^2.0.0", + "p-cancelable": "^2.0.0", + "responselike": "^2.0.0" }, "devDependencies": { - "@hapi/bourne": "^3.0.0", - "@sindresorhus/tsconfig": "^5.0.0", - "@sinonjs/fake-timers": "^11.2.2", - "@types/benchmark": "^2.1.5", - "@types/express": "^4.17.21", - "@types/node": "^20.10.0", - "@types/pem": "^1.14.4", - "@types/readable-stream": "^4.0.9", - "@types/request": "^2.48.12", - "@types/sinon": "^17.0.2", - "@types/sinonjs__fake-timers": "^8.1.5", - "ava": "^5.3.1", - "axios": "^1.6.2", + "@ava/typescript": "^1.1.1", + "@sindresorhus/tsconfig": "^0.7.0", + "@sinonjs/fake-timers": "^6.0.1", + "@types/benchmark": "^1.0.33", + "@types/express": "^4.17.7", + "@types/express-serve-static-core": "4.17.18 - 4.17.30", + "@types/node": "^14.14.0", + "@types/node-fetch": "^2.5.7", + "@types/pem": "^1.9.5", + "@types/pify": "^3.0.2", + "@types/request": "^2.48.5", + "@types/sinon": "^9.0.5", + "@types/tough-cookie": "^4.0.0", + "ava": "^3.11.1", + "axios": "^0.20.0", "benchmark": "^2.1.4", - "bluebird": "^3.7.2", - "body-parser": "^1.20.2", - "create-cert": "^1.0.6", + "coveralls": "^3.1.0", "create-test-server": "^3.0.1", - "del-cli": "^5.1.0", - "delay": "^6.0.0", - "express": "^4.18.2", - "form-data": "^4.0.0", - "formdata-node": "^6.0.3", - "nock": "^13.4.0", - "node-fetch": "^3.3.2", - "np": "^9.0.0", + "del-cli": "^3.0.1", + "delay": "^4.4.0", + "express": "^4.17.1", + "form-data": "^3.0.0", + "get-stream": "^6.0.0", + "nock": "^13.0.4", + "node-fetch": "^2.6.0", + "np": "^6.4.0", "nyc": "^15.1.0", - "p-event": "^6.0.0", - "pem": "^1.14.8", - "pify": "^6.1.0", - "readable-stream": "^4.4.2", - "request": "^2.88.2", - "sinon": "^17.0.1", + "p-event": "^4.2.0", + "pem": "^1.14.4", + "pify": "^5.0.0", + "sinon": "^9.0.3", "slow-stream": "0.0.4", - "tempy": "^3.1.0", - "then-busboy": "^5.2.1", - "tough-cookie": "^4.1.3", - "tsx": "^4.6.0", - "type-fest": "^4.8.2", - "typescript": "^5.3.2", - "xo": "^0.56.0" + "tempy": "^1.0.0", + "to-readable-stream": "^2.1.0", + "tough-cookie": "^4.0.0", + "typescript": "4.0.3", + "xo": "^0.34.1" }, + "types": "dist/source", + "sideEffects": false, "ava": { "files": [ "test/*" ], "timeout": "1m", - "extensions": { - "ts": "module" - }, - "workerThreads": false + "typescript": { + "rewritePaths": { + "test/": "dist/test/" + } + } }, "nyc": { - "reporter": [ - "text", - "html", - "lcov" - ], "extension": [ ".ts" ], @@ -132,20 +121,10 @@ ], "rules": { "@typescript-eslint/no-empty-function": "off", - "n/no-deprecated-api": "off", - "@typescript-eslint/no-implicit-any-catch": "off", - "ava/assertion-arguments": "off", - "@typescript-eslint/no-unsafe-member-access": "off", - "@typescript-eslint/no-unsafe-return": "off", - "@typescript-eslint/no-unsafe-assignment": "off", - "@typescript-eslint/no-unsafe-call": "off", - "@typescript-eslint/await-thenable": "off", - "@typescript-eslint/no-redundant-type-constituents": "off", - "@typescript-eslint/no-unsafe-argument": "off", - "@typescript-eslint/promise-function-async": "off", - "no-lone-blocks": "off", - "unicorn/no-await-expression-member": "off", - "unicorn/prefer-event-target": "off" + "node/prefer-global/url": "off", + "node/prefer-global/url-search-params": "off", + "import/no-anonymous-default-export": "off", + "@typescript-eslint/no-implicit-any-catch": "off" } }, "runkitExampleFilename": "./documentation/examples/runkit-example.js" diff --git a/setup-pandoc/node_modules/got/readme.md b/setup-pandoc/node_modules/got/readme.md index 02b53f695..858c536ad 100644 --- a/setup-pandoc/node_modules/got/readme.md +++ b/setup-pandoc/node_modules/got/readme.md @@ -5,349 +5,2346 @@


-

-

- - Sindre's open source work is supported by the community.
Special thanks to: -
-

-
- - - -
-
- -
- Strapi -
- Strapi is the leading open-source headless CMS. -
- It’s 100% JavaScript, fully customizable, and developer-first. -
-
-
-
-
- -
- SerpApi -
- API to get search engine results with ease. -
- -
- SerpApi -
- API to get search engine results with ease. -
-
-
-
-
- -
- DutchIS -
-
- VPS hosting with taste 😛 -
- -
- DutchIS -
-
- VPS hosting with taste 😛 -
-
-
-
-
-
-
+

Huge thanks to for sponsoring Sindre Sorhus!

+

(they love Got too!)



> Human-friendly and powerful HTTP request library for Node.js - +[![Build Status: Linux](https://travis-ci.com/sindresorhus/got.svg?branch=master)](https://travis-ci.com/github/sindresorhus/got) +[![Coverage Status](https://coveralls.io/repos/github/sindresorhus/got/badge.svg?branch=master)](https://coveralls.io/github/sindresorhus/got?branch=master) [![Downloads](https://img.shields.io/npm/dm/got.svg)](https://npmjs.com/got) -[![Install size](https://packagephobia.com/badge?p=got)](https://packagephobia.com/result?p=got) +[![Install size](https://packagephobia.now.sh/badge?p=got)](https://packagephobia.now.sh/result?p=got) + +[Moving from Request?](documentation/migration-guides.md) [*(Note that Request is unmaintained)*](https://github.com/request/request/issues/3142) [See how Got compares to other HTTP libraries](#comparison) ---- +For browser usage, we recommend [Ky](https://github.com/sindresorhus/ky) by the same people. + +## Highlights + +- [Promise API](#api) +- [Stream API](#streams) +- [Pagination API](#pagination) +- [HTTP2 support](#http2) +- [Request cancelation](#aborting-the-request) +- [RFC compliant caching](#cache-adapters) +- [Follows redirects](#followredirect) +- [Retries on failure](#retry) +- [Progress events](#onuploadprogress-progress) +- [Handles gzip/deflate/brotli](#decompress) +- [Timeout handling](#timeout) +- [Errors with metadata](#errors) +- [JSON mode](#json-mode) +- [WHATWG URL support](#url) +- [HTTPS API](#advanced-https-api) +- [Hooks](#hooks) +- [Instances with custom defaults](#instances) +- [Types](#types) +- [Composable](documentation/advanced-creation.md#merging-instances) +- [Plugins](documentation/lets-make-a-plugin.md) +- [Used by 4K+ packages and 1.8M+ repos](https://github.com/sindresorhus/got/network/dependents) +- [Actively maintained](https://github.com/sindresorhus/got/graphs/contributors) +- [Trusted by many companies](#widely-used) + +## Install + +``` +$ npm install got +``` + +## Usage + +###### Promise + +```js +const got = require('got'); + +(async () => { + try { + const response = await got('https://sindresorhus.com'); + console.log(response.body); + //=> ' ...' + } catch (error) { + console.log(error.response.body); + //=> 'Internal server error ...' + } +})(); +``` + +###### JSON + +```js +const got = require('got'); + +(async () => { + const {body} = await got.post('https://httpbin.org/anything', { + json: { + hello: 'world' + }, + responseType: 'json' + }); + + console.log(body.data); + //=> {hello: 'world'} +})(); +``` + +See [JSON mode](#json-mode) for more details. + +###### Streams + +```js +const stream = require('stream'); +const {promisify} = require('util'); +const fs = require('fs'); +const got = require('got'); + +const pipeline = promisify(stream.pipeline); + +(async () => { + await pipeline( + got.stream('https://sindresorhus.com'), + fs.createWriteStream('index.html') + ); + + // For POST, PUT, PATCH, and DELETE methods, `got.stream` returns a `stream.Writable`. + await pipeline( + fs.createReadStream('index.html'), + got.stream.post('https://sindresorhus.com') + ); +})(); +``` + +**Tip:** `from.pipe(to)` doesn't forward errors. Instead, use [`stream.pipeline(from, ..., to, callback)`](https://nodejs.org/api/stream.html#stream_stream_pipeline_streams_callback). + +**Note:** While `got.post('https://example.com')` resolves, `got.stream.post('https://example.com')` will hang indefinitely until a body is provided. If there's no body on purpose, remember to `.end()` the stream or set the [`body`](#body) option to an empty string. + +### API + +It's a `GET` request by default, but can be changed by using different methods or via [`options.method`](#method). + +**By default, Got will retry on failure. To disable this option, set [`options.retry`](#retry) to `0`.** + +#### got(url?, options?) + +Returns a Promise giving a [Response object](#response) or a [Got Stream](#streams-1) if `options.isStream` is set to true. + +##### url + +Type: `string | object` + +The URL to request, as a string, a [`https.request` options object](https://nodejs.org/api/https.html#https_https_request_options_callback), or a [WHATWG `URL`](https://nodejs.org/api/url.html#url_class_url). + +Properties from `options` will override properties in the parsed `url`. + +If no protocol is specified, it will throw a `TypeError`. + +**Note:** The query string is **not** parsed as search params. Example: + +```js +got('https://example.com/?query=a b'); //=> https://example.com/?query=a%20b +got('https://example.com/', {searchParams: {query: 'a b'}}); //=> https://example.com/?query=a+b + +// The query string is overridden by `searchParams` +got('https://example.com/?query=a b', {searchParams: {query: 'a b'}}); //=> https://example.com/?query=a+b +``` + +##### options + +Type: `object` + +Any of the [`https.request`](https://nodejs.org/api/https.html#https_https_request_options_callback) options. + +**Note:** Legacy URL support is disabled. `options.path` is supported only for backwards compatibility. Use `options.pathname` and `options.searchParams` instead. `options.auth` has been replaced with `options.username` & `options.password`. + +###### method + +Type: `string`\ +Default: `GET` + +The HTTP method used to make the request. + +###### prefixUrl + +Type: `string | URL` + +When specified, `prefixUrl` will be prepended to `url`. The prefix can be any valid URL, either relative or absolute.\ +A trailing slash `/` is optional - one will be added automatically. + +**Note:** `prefixUrl` will be ignored if the `url` argument is a URL instance. + +**Note:** Leading slashes in `input` are disallowed when using this option to enforce consistency and avoid confusion. For example, when the prefix URL is `https://example.com/foo` and the input is `/bar`, there's ambiguity whether the resulting URL would become `https://example.com/foo/bar` or `https://example.com/bar`. The latter is used by browsers. + +**Tip:** Useful when used with [`got.extend()`](#custom-endpoints) to create niche-specific Got instances. + +**Tip:** You can change `prefixUrl` using hooks as long as the URL still includes the `prefixUrl`. If the URL doesn't include it anymore, it will throw. + +```js +const got = require('got'); + +(async () => { + await got('unicorn', {prefixUrl: 'https://cats.com'}); + //=> 'https://cats.com/unicorn' + + const instance = got.extend({ + prefixUrl: 'https://google.com' + }); + + await instance('unicorn', { + hooks: { + beforeRequest: [ + options => { + options.prefixUrl = 'https://cats.com'; + } + ] + } + }); + //=> 'https://cats.com/unicorn' +})(); +``` + +###### headers + +Type: `object`\ +Default: `{}` + +Request headers. + +Existing headers will be overwritten. Headers set to `undefined` will be omitted. + +###### isStream + +Type: `boolean`\ +Default: `false` + +Returns a `Stream` instead of a `Promise`. This is equivalent to calling `got.stream(url, options?)`. + +###### body + +Type: `string | Buffer | stream.Readable` or [`form-data` instance](https://github.com/form-data/form-data) + +**Note #1:** The `body` option cannot be used with the `json` or `form` option. + +**Note #2:** If you provide this option, `got.stream()` will be read-only. + +**Note #3:** If you provide a payload with the `GET` or `HEAD` method, it will throw a `TypeError` unless the method is `GET` and the `allowGetBody` option is set to `true`. + +**Note #4:** This option is not enumerable and will not be merged with the instance defaults. + +The `content-length` header will be automatically set if `body` is a `string` / `Buffer` / `fs.createReadStream` instance / [`form-data` instance](https://github.com/form-data/form-data), and `content-length` and `transfer-encoding` are not manually set in `options.headers`. + +###### json + +Type: `object | Array | number | string | boolean | null` *(JSON-serializable values)* + +**Note #1:** If you provide this option, `got.stream()` will be read-only.\ +**Note #2:** This option is not enumerable and will not be merged with the instance defaults. + +JSON body. If the `Content-Type` header is not set, it will be set to `application/json`. + +###### context + +Type: `object` + +User data. In contrast to other options, `context` is not enumerable. + +**Note:** The object is never merged, it's just passed through. Got will not modify the object in any way. + +It's very useful for storing auth tokens: + +```js +const got = require('got'); + +const instance = got.extend({ + hooks: { + beforeRequest: [ + options => { + if (!options.context || !options.context.token) { + throw new Error('Token required'); + } + + options.headers.token = options.context.token; + } + ] + } +}); + +(async () => { + const context = { + token: 'secret' + }; + + const response = await instance('https://httpbin.org/headers', {context}); + + // Let's see the headers + console.log(response.body); +})(); +``` + +###### responseType + +Type: `string`\ +Default: `'text'` + +**Note:** When using streams, this option is ignored. + +The parsing method. Can be `'text'`, `'json'` or `'buffer'`. + +The promise also has `.text()`, `.json()` and `.buffer()` methods which return another Got promise for the parsed body.\ +It's like setting the options to `{responseType: 'json', resolveBodyOnly: true}` but without affecting the main Got promise. + +Example: + +```js +(async () => { + const responsePromise = got(url); + const bufferPromise = responsePromise.buffer(); + const jsonPromise = responsePromise.json(); + + const [response, buffer, json] = await Promise.all([responsePromise, bufferPromise, jsonPromise]); + // `response` is an instance of Got Response + // `buffer` is an instance of Buffer + // `json` is an object +})(); +``` + +```js +// This +const body = await got(url).json(); + +// is semantically the same as this +const body = await got(url, {responseType: 'json', resolveBodyOnly: true}); +``` + +**Note:** `buffer` will return the raw body buffer. Modifying it will also alter the result of `promise.text()` and `promise.json()`. Before overwritting the buffer, please copy it first via `Buffer.from(buffer)`. See https://github.com/nodejs/node/issues/27080 + +###### parseJson + +Type: `(text: string) => unknown`\ +Default: `(text: string) => JSON.parse(text)` + +A function used to parse JSON responses. + +
+Example + +Using [`bourne`](https://github.com/hapijs/bourne) to prevent prototype pollution: + +```js +const got = require('got'); +const Bourne = require('@hapi/bourne'); + +(async () => { + const parsed = await got('https://example.com', { + parseJson: text => Bourne.parse(text) + }).json(); + + console.log(parsed); +})(); +``` +
+ +###### stringifyJson + +Type: `(object: unknown) => string`\ +Default: `(object: unknown) => JSON.stringify(object)` + +A function used to stringify the body of JSON requests. + +
+Examples + +Ignore properties starting with `_`: + +```js +const got = require('got'); + +(async () => { + await got.post('https://example.com', { + stringifyJson: object => JSON.stringify(object, (key, value) => { + if (key.startsWith('_')) { + return; + } + + return value; + }), + json: { + some: 'payload', + _ignoreMe: 1234 + } + }); +})(); +``` + +All numbers as strings: + +```js +const got = require('got'); + +(async () => { + await got.post('https://example.com', { + stringifyJson: object => JSON.stringify(object, (key, value) => { + if (typeof value === 'number') { + return value.toString(); + } + + return value; + }), + json: { + some: 'payload', + number: 1 + } + }); +})(); +``` +
+ +###### resolveBodyOnly + +Type: `boolean`\ +Default: `false` + +When set to `true` the promise will return the [Response body](#body-1) instead of the [Response](#response) object. + +###### cookieJar + +Type: `object` | [`tough.CookieJar` instance](https://github.com/salesforce/tough-cookie#cookiejar) + +**Note:** If you provide this option, `options.headers.cookie` will be overridden. + +Cookie support. You don't have to care about parsing or how to store them. [Example](#cookies). + +###### cookieJar.setCookie + +Type: `Function` + +The function takes two arguments: `rawCookie` (`string`) and `url` (`string`). + +###### cookieJar.getCookieString + +Type: `Function` + +The function takes one argument: `url` (`string`). + +###### ignoreInvalidCookies + +Type: `boolean`\ +Default: `false` + +Ignore invalid cookies instead of throwing an error. Only useful when the `cookieJar` option has been set. Not recommended. + +###### encoding + +Type: `string`\ +Default: `'utf8'` + +[Encoding](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings) to be used on `setEncoding` of the response data. + +To get a [`Buffer`](https://nodejs.org/api/buffer.html), you need to set [`responseType`](#responseType) to `buffer` instead. Don't set this option to `null`. + +**Note:** This doesn't affect streams! Instead, you need to do `got.stream(...).setEncoding(encoding)`. + +###### form + +Type: `object` + +**Note #1:** If you provide this option, `got.stream()` will be read-only.\ +**Note #2:** This option is not enumerable and will not be merged with the instance defaults. + +The form body is converted to a query string using [`(new URLSearchParams(object)).toString()`](https://nodejs.org/api/url.html#url_constructor_new_urlsearchparams_obj). + +If the `Content-Type` header is not present, it will be set to `application/x-www-form-urlencoded`. + +###### searchParams + +Type: `string | object | URLSearchParams` + +Query string that will be added to the request URL. This will override the query string in `url`. + +If you need to pass in an array, you can do it using a `URLSearchParams` instance: + +```js +const got = require('got'); + +const searchParams = new URLSearchParams([['key', 'a'], ['key', 'b']]); + +got('https://example.com', {searchParams}); + +console.log(searchParams.toString()); +//=> 'key=a&key=b' +``` + +There are some exceptions in regards to `URLSearchParams` behavior: + +**Note #1:** `null` values are not stringified, an empty string is used instead. + +**Note #2:** `undefined` values are not stringified, the entry is skipped instead. + +###### timeout + +Type: `number | object` + +Milliseconds to wait for the server to end the response before aborting the request with [`got.TimeoutError`](#gottimeouterror) error (a.k.a. `request` property). By default, there's no timeout. + +This also accepts an `object` with the following fields to constrain the duration of each phase of the request lifecycle: + +- `lookup` starts when a socket is assigned and ends when the hostname has been resolved. Does not apply when using a Unix domain socket. +- `connect` starts when `lookup` completes (or when the socket is assigned if lookup does not apply to the request) and ends when the socket is connected. +- `secureConnect` starts when `connect` completes and ends when the handshaking process completes (HTTPS only). +- `socket` starts when the socket is connected. See [request.setTimeout](https://nodejs.org/api/http.html#http_request_settimeout_timeout_callback). +- `response` starts when the request has been written to the socket and ends when the response headers are received. +- `send` starts when the socket is connected and ends with the request has been written to the socket. +- `request` starts when the request is initiated and ends when the response's end event fires. + +###### retry + +Type: `number | object`\ +Default: +- limit: `2` +- calculateDelay: `({attemptCount, retryOptions, error, computedValue}) => computedValue | Promise` +- methods: `GET` `PUT` `HEAD` `DELETE` `OPTIONS` `TRACE` +- statusCodes: [`408`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/408) [`413`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/413) [`429`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429) [`500`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500) [`502`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/502) [`503`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/503) [`504`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504) [`521`](https://support.cloudflare.com/hc/en-us/articles/115003011431#521error) [`522`](https://support.cloudflare.com/hc/en-us/articles/115003011431#522error) [`524`](https://support.cloudflare.com/hc/en-us/articles/115003011431#524error) +- maxRetryAfter: `undefined` +- errorCodes: `ETIMEDOUT` `ECONNRESET` `EADDRINUSE` `ECONNREFUSED` `EPIPE` `ENOTFOUND` `ENETUNREACH` `EAI_AGAIN` + +An object representing `limit`, `calculateDelay`, `methods`, `statusCodes`, `maxRetryAfter` and `errorCodes` fields for maximum retry count, retry handler, allowed methods, allowed status codes, maximum [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time and allowed error codes. + +If `maxRetryAfter` is set to `undefined`, it will use `options.timeout`.\ +If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will cancel the request. + +Delays between retries counts with function `1000 * Math.pow(2, retry - 1) + Math.random() * 100`, where `retry` is attempt number (starts from 1). + +The `calculateDelay` property is a `function` that receives an object with `attemptCount`, `retryOptions`, `error` and `computedValue` properties for current retry count, the retry options, error and default computed value. The function must return a delay in milliseconds (or a Promise resolving with it) (`0` return value cancels retry). + +**Note:** The `calculateDelay` function is responsible for the entire cache mechanism, including the `limit` property. To support it, you need to check whether `computedValue` is different than `0`. + +By default, it retries *only* on the specified methods, status codes, and on these network errors: +- `ETIMEDOUT`: One of the [timeout](#timeout) limits were reached. +- `ECONNRESET`: Connection was forcibly closed by a peer. +- `EADDRINUSE`: Could not bind to any free port. +- `ECONNREFUSED`: Connection was refused by the server. +- `EPIPE`: The remote side of the stream being written has been closed. +- `ENOTFOUND`: Couldn't resolve the hostname to an IP address. +- `ENETUNREACH`: No internet connection. +- `EAI_AGAIN`: DNS lookup timed out. + + + +You can retry Got streams too. The implementation looks like this: + +```js +const got = require('got'); +const fs = require('fs'); + +let writeStream; + +const fn = (retryCount = 0) => { + const stream = got.stream('https://example.com'); + stream.retryCount = retryCount; + + if (writeStream) { + writeStream.destroy(); + } + + writeStream = fs.createWriteStream('example.com'); + + stream.pipe(writeStream); + + // If you don't attach the listener, it will NOT make a retry. + // It automatically checks the listener count so it knows whether to retry or not :) + stream.once('retry', fn); +}; + +fn(); +``` + +###### followRedirect + +Type: `boolean`\ +Default: `true` + +Defines if redirect responses should be followed automatically. + +Note that if a `303` is sent by the server in response to any request type (`POST`, `DELETE`, etc.), Got will automatically request the resource pointed to in the location header via `GET`. This is in accordance with [the spec](https://tools.ietf.org/html/rfc7231#section-6.4.4). + +###### methodRewriting + +Type: `boolean`\ +Default: `true` + +By default, redirects will use [method rewriting](https://tools.ietf.org/html/rfc7231#section-6.4). For example, when sending a POST request and receiving a `302`, it will resend the body to the new location using the same HTTP method (`POST` in this case). + +###### allowGetBody + +Type: `boolean`\ +Default: `false` + +**Note:** The [RFC 7321](https://tools.ietf.org/html/rfc7231#section-4.3.1) doesn't specify any particular behavior for the GET method having a payload, therefore **it's considered an [anti-pattern](https://en.wikipedia.org/wiki/Anti-pattern)**. + +Set this to `true` to allow sending body for the `GET` method. However, the [HTTP/2 specification](https://tools.ietf.org/html/rfc7540#section-8.1.3) says that `An HTTP GET request includes request header fields and no payload body`, therefore when using the HTTP/2 protocol this option will have no effect. This option is only meant to interact with non-compliant servers when you have no other choice. + +###### maxRedirects + +Type: `number`\ +Default: `10` + +If exceeded, the request will be aborted and a `MaxRedirectsError` will be thrown. + +###### decompress + +Type: `boolean`\ +Default: `true` + +Decompress the response automatically. This will set the `accept-encoding` header to `gzip, deflate, br` on Node.js 11.7.0+ or `gzip, deflate` for older Node.js versions, unless you set it yourself. + +Brotli (`br`) support requires Node.js 11.7.0 or later. + +If this is disabled, a compressed response is returned as a `Buffer`. This may be useful if you want to handle decompression yourself or stream the raw compressed data. + +###### cache + +Type: `object | false`\ +Default: `false` + +[Cache adapter instance](#cache-adapters) for storing cached response data. + +###### cacheOptions + +Type: `object | undefined`\ +Default: `{}` + +[Cache options](https://github.com/kornelski/http-cache-semantics#constructor-options) used for the specified request. + +###### dnsCache + +Type: `CacheableLookup | false`\ +Default: `false` + +An instance of [`CacheableLookup`](https://github.com/szmarczak/cacheable-lookup) used for making DNS lookups. Useful when making lots of requests to different *public* hostnames. + +**Note:** This should stay disabled when making requests to internal hostnames such as `localhost`, `database.local` etc.\ +`CacheableLookup` uses `dns.resolver4(..)` and `dns.resolver6(...)` under the hood and fall backs to `dns.lookup(...)` when the first two fail, which may lead to additional delay. + +###### dnsLookupIpVersion + +Type: `'auto' | 'ipv4' | 'ipv6'`\ +Default: `'auto'` + +Indicates which DNS record family to use.\ +Values: + - `auto`: IPv4 (if present) or IPv6 + - `ipv4`: Only IPv4 + - `ipv6`: Only IPv6 + +Note: If you are using the undocumented option `family`, `dnsLookupIpVersion` will override it. + +```js +// `api6.ipify.org` will be resolved as IPv4 and the request will be over IPv4 (the website will respond with your public IPv4) +await got('https://api6.ipify.org', { + dnsLookupIpVersion: 'ipv4' +}); + +// `api6.ipify.org` will be resolved as IPv6 and the request will be over IPv6 (the website will respond with your public IPv6) +await got('https://api6.ipify.org', { + dnsLookupIpVersion: 'ipv6' +}); +``` + +###### lookup + +Type: `Function`\ +Default: [`dns.lookup`](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback) + +Custom DNS resolution logic. + +The function signature is the same as [`dns.lookup`](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback). + +###### request + +Type: `Function`\ +Default: `http.request | https.request` *(Depending on the protocol)* + +Custom request function. The main purpose of this is to [support HTTP2 using a wrapper](https://github.com/szmarczak/http2-wrapper). + +###### http2 + +Type: `boolean`\ +Default: `false` + +If set to `true`, Got will additionally accept HTTP2 requests.\ +It will choose either HTTP/1.1 or HTTP/2 depending on the ALPN protocol. + +**Note:** Overriding `options.request` will disable HTTP2 support. + +**Note:** This option will default to `true` in the next upcoming major release. + +```js +const got = require('got'); + +(async () => { + const {headers} = await got('https://nghttp2.org/httpbin/anything', {http2: true}); + console.log(headers.via); + //=> '2 nghttpx' +})(); +``` + +###### throwHttpErrors + +Type: `boolean`\ +Default: `true` + +Determines if a [`got.HTTPError`](#gothttperror) is thrown for unsuccessful responses. + +If this is disabled, requests that encounter an error status code will be resolved with the `response` instead of throwing. This may be useful if you are checking for resource availability and are expecting error responses. + +###### agent + +Type: `object` + +An object representing `http`, `https` and `http2` keys for [`http.Agent`](https://nodejs.org/api/http.html#http_class_http_agent), [`https.Agent`](https://nodejs.org/api/https.html#https_class_https_agent) and [`http2wrapper.Agent`](https://github.com/szmarczak/http2-wrapper#new-http2agentoptions) instance. This is necessary because a request to one protocol might redirect to another. In such a scenario, Got will switch over to the right protocol agent for you. + +If a key is not present, it will default to a global agent. + +```js +const got = require('got'); +const HttpAgent = require('agentkeepalive'); +const {HttpsAgent} = HttpAgent; + +got('https://sindresorhus.com', { + agent: { + http: new HttpAgent(), + https: new HttpsAgent() + } +}); +``` + +###### hooks + +Type: `object` + +Hooks allow modifications during the request lifecycle. Hook functions may be async and are run serially. + +###### hooks.init + +Type: `Function[]`\ +Default: `[]` + +Called with plain [request options](#options), right before their normalization. This is especially useful in conjunction with [`got.extend()`](#instances) when the input needs custom handling. + +See the [Request migration guide](documentation/migration-guides.md#breaking-changes) for an example. + +**Note #1:** This hook must be synchronous!\ +**Note #2:** Errors in this hook will be converted into an instances of [`RequestError`](#gotrequesterror).\ +**Note #3:** The options object may not have a `url` property. To modify it, use a `beforeRequest` hook instead. + +###### hooks.beforeRequest + +Type: `Function[]`\ +Default: `[]` + +Called with [normalized](source/core/index.ts) [request options](#options). Got will make no further changes to the request before it is sent. This is especially useful in conjunction with [`got.extend()`](#instances) when you want to create an API client that, for example, uses HMAC-signing. + +**Note:** Changing `options.json` or `options.form` has no effect on the request, you should change `options.body` instead. If needed, update the `options.headers` accordingly. Example: + +```js +const got = require('got'); + +got.post({ + json: {payload: 'old'}, + hooks: { + beforeRequest: [ + options => { + options.body = JSON.stringify({payload: 'new'}); + options.headers['content-length'] = options.body.length.toString(); + } + ] + } +}); +``` + +**Tip:** You can override the `request` function by returning a [`ClientRequest`-like](https://nodejs.org/api/http.html#http_class_http_clientrequest) instance or a [`IncomingMessage`-like](https://nodejs.org/api/http.html#http_class_http_incomingmessage) instance. This is very useful when creating a custom cache mechanism. + +###### hooks.beforeRedirect + +Type: `Function[]`\ +Default: `[]` + +Called with [normalized](source/core/index.ts) [request options](#options) and the redirect [response](#response). Got will make no further changes to the request. This is especially useful when you want to avoid dead sites. Example: + +```js +const got = require('got'); + +got('https://example.com', { + hooks: { + beforeRedirect: [ + (options, response) => { + if (options.hostname === 'deadSite') { + options.hostname = 'fallbackSite'; + } + } + ] + } +}); +``` + +###### hooks.beforeRetry + +Type: `Function[]`\ +Default: `[]` + +**Note:** When using streams, this hook is ignored. + +Called with [normalized](source/normalize-arguments.ts) [request options](#options), the error and the retry count. Got will make no further changes to the request. This is especially useful when some extra work is required before the next try. Example: + +```js +const got = require('got'); + +got.post('https://example.com', { + hooks: { + beforeRetry: [ + (options, error, retryCount) => { + if (error.response.statusCode === 413) { // Payload too large + options.body = getNewBody(); + } + } + ] + } +}); +``` + +**Note:** When retrying in a `afterResponse` hook, all remaining `beforeRetry` hooks will be called without the `error` and `retryCount` arguments. + +###### hooks.afterResponse + +Type: `Function[]`\ +Default: `[]` + +**Note:** When using streams, this hook is ignored. + +Called with [response object](#response) and a retry function. Calling the retry function will trigger `beforeRetry` hooks. + +Each function should return the response. This is especially useful when you want to refresh an access token. Example: + +```js +const got = require('got'); + +const instance = got.extend({ + hooks: { + afterResponse: [ + (response, retryWithMergedOptions) => { + if (response.statusCode === 401) { // Unauthorized + const updatedOptions = { + headers: { + token: getNewToken() // Refresh the access token + } + }; + + // Save for further requests + instance.defaults.options = got.mergeOptions(instance.defaults.options, updatedOptions); + + // Make a new retry + return retryWithMergedOptions(updatedOptions); + } + + // No changes otherwise + return response; + } + ], + beforeRetry: [ + (options, error, retryCount) => { + // This will be called on `retryWithMergedOptions(...)` + } + ] + }, + mutableDefaults: true +}); +``` + +###### hooks.beforeError + +Type: `Function[]`\ +Default: `[]` + +Called with an `Error` instance. The error is passed to the hook right before it's thrown. This is especially useful when you want to have more detailed errors. + +**Note:** Errors thrown while normalizing input options are thrown directly and not part of this hook. + +```js +const got = require('got'); + +got('https://api.github.com/some-endpoint', { + hooks: { + beforeError: [ + error => { + const {response} = error; + if (response && response.body) { + error.name = 'GitHubError'; + error.message = `${response.body.message} (${response.statusCode})`; + } + + return error; + } + ] + } +}); +``` + +##### pagination + +Type: `object` + +**Note:** We're [looking for feedback](https://github.com/sindresorhus/got/issues/1052), any ideas on how to improve the API are welcome. + +###### pagination.transform + +Type: `Function`\ +Default: `response => JSON.parse(response.body)` + +A function that transform [`Response`](#response) into an array of items. This is where you should do the parsing. + +###### pagination.paginate + +Type: `Function`\ +Default: [`Link` header logic](source/index.ts) + +The function takes three arguments: +- `response` - The current response object. +- `allItems` - An array of the emitted items. +- `currentItems` - Items from the current response. + +It should return an object representing Got options pointing to the next page. The options are merged automatically with the previous request, therefore the options returned `pagination.paginate(...)` must reflect changes only. If there are no more pages, `false` should be returned. + +For example, if you want to stop when the response contains less items than expected, you can use something like this: + +```js +const got = require('got'); + +(async () => { + const limit = 10; + + const items = got.paginate('https://example.com/items', { + searchParams: { + limit, + offset: 0 + }, + pagination: { + paginate: (response, allItems, currentItems) => { + const previousSearchParams = response.request.options.searchParams; + const previousOffset = previousSearchParams.get('offset'); + + if (currentItems.length < limit) { + return false; + } + + return { + searchParams: { + ...previousSearchParams, + offset: Number(previousOffset) + limit, + } + }; + } + } + }); + + console.log('Items from all pages:', items); +})(); +``` + +###### pagination.filter + +Type: `Function`\ +Default: `(item, allItems, currentItems) => true` + +Checks whether the item should be emitted or not. + +###### pagination.shouldContinue + +Type: `Function`\ +Default: `(item, allItems, currentItems) => true` + +Checks whether the pagination should continue. + +For example, if you need to stop **before** emitting an entry with some flag, you should use `(item, allItems, currentItems) => !item.flag`. If you want to stop **after** emitting the entry, you should use `(item, allItems, currentItems) => allItems.some(entry => entry.flag)` instead. + +###### pagination.countLimit + +Type: `number`\ +Default: `Infinity` + +The maximum amount of items that should be emitted. + +###### pagination.backoff + +Type: `number`\ +Default: `0` + +Milliseconds to wait before the next request is triggered. + +###### pagination.requestLimit + +Type: `number`\ +Default: `10000` + +The maximum amount of request that should be triggered. [Retries on failure](#retry) are not counted towards this limit. + +For example, it can be helpful during development to avoid an infinite number of requests. + +###### pagination.stackAllItems + +Type: `boolean`\ +Default: `true` + +Defines how the parameter `allItems` in [pagination.paginate](#pagination.paginate), [pagination.filter](#pagination.filter) and [pagination.shouldContinue](#pagination.shouldContinue) is managed. When set to `false`, the parameter `allItems` is always an empty array. + +This option can be helpful to save on memory usage when working with a large dataset. + +##### localAddress + +Type: `string` + +The IP address used to send the request from. + +### Advanced HTTPS API + +Note: If the request is not HTTPS, these options will be ignored. + +##### https.certificateAuthority + +Type: `string | Buffer | Array` + +Override the default Certificate Authorities ([from Mozilla](https://ccadb-public.secure.force.com/mozilla/IncludedCACertificateReport)) + +```js +// Single Certificate Authority +got('https://example.com', { + https: { + certificateAuthority: fs.readFileSync('./my_ca.pem') + } +}); +``` + +##### https.key + +Type: `string | Buffer | Array | object[]` + +Private keys in [PEM](https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail) format.\ +[PEM](https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail) allows the option of private keys being encrypted. Encrypted keys will be decrypted with `options.https.passphrase`.\ +Multiple keys with different passphrases can be provided as an array of `{pem: , passphrase: }` + +##### https.certificate + +Type: `string | Buffer | (string | Buffer)[]` + +[Certificate chains](https://en.wikipedia.org/wiki/X.509#Certificate_chains_and_cross-certification) in [PEM](https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail) format.\ +One cert chain should be provided per private key (`options.https.key`).\ +When providing multiple cert chains, they do not have to be in the same order as their private keys in `options.https.key`.\ +If the intermediate certificates are not provided, the peer will not be able to validate the certificate, and the handshake will fail. + +##### https.passphrase + +Type: `string` + +The passphrase to decrypt the `options.https.key` (if different keys have different passphrases refer to `options.https.key` documentation). + +##### https.pfx + +Type: `string | Buffer | Array` + +[PFX or PKCS12](https://en.wikipedia.org/wiki/PKCS_12) encoded private key and certificate chain. Using `options.https.pfx` is an alternative to providing `options.https.key` and `options.https.certificate` individually. A PFX is usually encrypted, and if it is, `options.https.passphrase` will be used to decrypt it. + +Multiple PFX's can be be provided as an array of unencrypted buffers or an array of objects like: + +```ts +{ + buffer: string | Buffer, + passphrase?: string +} +``` + +This object form can only occur in an array. If the provided buffers are encrypted, `object.passphrase` can be used to decrypt them. If `object.passphrase` is not provided, `options.https.passphrase` will be used for decryption. + +##### Examples for `https.key`, `https.certificate`, `https.passphrase`, and `https.pfx` + +```js +// Single key with certificate +got('https://example.com', { + https: { + key: fs.readFileSync('./client_key.pem'), + certificate: fs.readFileSync('./client_cert.pem') + } +}); + +// Multiple keys with certificates (out of order) +got('https://example.com', { + https: { + key: [ + fs.readFileSync('./client_key1.pem'), + fs.readFileSync('./client_key2.pem') + ], + certificate: [ + fs.readFileSync('./client_cert2.pem'), + fs.readFileSync('./client_cert1.pem') + ] + } +}); + +// Single key with passphrase +got('https://example.com', { + https: { + key: fs.readFileSync('./client_key.pem'), + certificate: fs.readFileSync('./client_cert.pem'), + passphrase: 'client_key_passphrase' + } +}); + +// Multiple keys with different passphrases +got('https://example.com', { + https: { + key: [ + {pem: fs.readFileSync('./client_key1.pem'), passphrase: 'passphrase1'}, + {pem: fs.readFileSync('./client_key2.pem'), passphrase: 'passphrase2'}, + ], + certificate: [ + fs.readFileSync('./client_cert1.pem'), + fs.readFileSync('./client_cert2.pem') + ] + } +}); + +// Single encrypted PFX with passphrase +got('https://example.com', { + https: { + pfx: fs.readFileSync('./fake.pfx'), + passphrase: 'passphrase' + } +}); + +// Multiple encrypted PFX's with different passphrases +got('https://example.com', { + https: { + pfx: [ + { + buffer: fs.readFileSync('./key1.pfx'), + passphrase: 'passphrase1' + }, + { + buffer: fs.readFileSync('./key2.pfx'), + passphrase: 'passphrase2' + } + ] + } +}); + +// Multiple encrypted PFX's with single passphrase +got('https://example.com', { + https: { + passphrase: 'passphrase', + pfx: [ + { + buffer: fs.readFileSync('./key1.pfx') + }, + { + buffer: fs.readFileSync('./key2.pfx') + } + ] + } +}); +``` + +##### https.rejectUnauthorized + +Type: `boolean`\ +Default: `true` + +If set to `false`, all invalid SSL certificates will be ignored and no error will be thrown.\ +If set to `true`, it will throw an error whenever an invalid SSL certificate is detected. + +We strongly recommend to have this set to `true` for security reasons. + +```js +const got = require('got'); + +(async () => { + // Correct: + await got('https://example.com', { + https: { + rejectUnauthorized: true + } + }); + + // You can disable it when developing an HTTPS app: + await got('https://localhost', { + https: { + rejectUnauthorized: false + } + }); + + // Never do this: + await got('https://example.com', { + https: { + rejectUnauthorized: false + } + }); +``` + +##### https.checkServerIdentity + +Type: `Function`\ +Signature: `(hostname: string, certificate: DetailedPeerCertificate) => Error | undefined`\ +Default: `tls.checkServerIdentity` (from the `tls` module) + +This function enable a custom check of the certificate.\ +Note: In order to have the function called the certificate must not be `expired`, `self-signed` or with an `untrusted-root`.\ +The function parameters are: +- `hostname`: The server hostname (used when connecting) +- `certificate`: The server certificate + +The function must return `undefined` if the check succeeded or an `Error` if it failed. + +```js +await got('https://example.com', { + https: { + checkServerIdentity: (hostname, certificate) => { + if (hostname === 'example.com') { + return; // Certificate OK + } + + return new Error('Invalid Hostname'); // Certificate NOT OK + } + } +}); +``` + +#### Response + +The response object will typically be a [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage), however, if returned from the cache it will be a [response-like object](https://github.com/lukechilds/responselike) which behaves in the same way. + +##### request + +Type: `object` + +**Note:** This is not a [http.ClientRequest](https://nodejs.org/api/http.html#http_class_http_clientrequest). + +- `options` - The Got options that were set on this request. + +##### body + +Type: `string | object | Buffer` *(Depending on `options.responseType`)* + +The result of the request. + +##### rawBody + +Type: `Buffer` + +The raw result of the request. + +##### url + +Type: `string` + +The request URL or the final URL after redirects. + +##### ip + +Type: `string` + +The remote IP address. + +**Note:** Not available when the response is cached. This is hopefully a temporary limitation, see [lukechilds/cacheable-request#86](https://github.com/lukechilds/cacheable-request/issues/86). + +##### requestUrl + +Type: `string` + +The original request URL. + +##### timings + +Type: `object` + +The object contains the following properties: + +- `start` - Time when the request started. +- `socket` - Time when a socket was assigned to the request. +- `lookup` - Time when the DNS lookup finished. +- `connect` - Time when the socket successfully connected. +- `secureConnect` - Time when the socket securely connected. +- `upload` - Time when the request finished uploading. +- `response` - Time when the request fired `response` event. +- `end` - Time when the response fired `end` event. +- `error` - Time when the request fired `error` event. +- `abort` - Time when the request fired `abort` event. +- `phases` + - `wait` - `timings.socket - timings.start` + - `dns` - `timings.lookup - timings.socket` + - `tcp` - `timings.connect - timings.lookup` + - `tls` - `timings.secureConnect - timings.connect` + - `request` - `timings.upload - (timings.secureConnect || timings.connect)` + - `firstByte` - `timings.response - timings.upload` + - `download` - `timings.end - timings.response` + - `total` - `(timings.end || timings.error || timings.abort) - timings.start` + +If something has not been measured yet, it will be `undefined`. + +**Note:** The time is a `number` representing the milliseconds elapsed since the UNIX epoch. + +##### isFromCache + +Type: `boolean` + +Whether the response was retrieved from the cache. + +##### redirectUrls + +Type: `string[]` + +The redirect URLs. + +##### retryCount + +Type: `number` + +The number of times the request was retried. + +#### Streams + +**Note:** Progress events, redirect events and request/response events can also be used with promises. + +**Note:** To access `response.isFromCache` you need to use `got.stream(url, options).isFromCache`. The value will be undefined until the `response` event. + +#### got.stream(url, options?) + +Sets `options.isStream` to `true`. + +Returns a [duplex stream](https://nodejs.org/api/stream.html#stream_class_stream_duplex) with additional events: + +##### .on('request', request) + +`request` event to get the request object of the request. + +**Tip:** You can use `request` event to abort request: + +```js +got.stream('https://github.com') + .on('request', request => setTimeout(() => request.destroy(), 50)); +``` + +##### .on('response', response) + +The `response` event to get the response object of the final request. + +##### .on('redirect', response, nextOptions) + +The `redirect` event to get the response object of a redirect. The second argument is options for the next request to the redirect location. + +##### .on('uploadProgress', progress) +##### .uploadProgress +##### .on('downloadProgress', progress) +##### .downloadProgress -**You probably want [Ky](https://github.com/sindresorhus/ky) instead, by the same people. It's smaller, works in the browser too, and is more stable since it's built upon [`Fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).** +Progress events for uploading (sending a request) and downloading (receiving a response). The `progress` argument is an object like: ---- +```js +{ + percent: 0.1, + transferred: 1024, + total: 10240 +} +``` -**Support questions should be asked [here](https://github.com/sindresorhus/got/discussions).** +If the `content-length` header is missing, `total` will be `undefined`. -## Install +```js +(async () => { + const response = await got('https://sindresorhus.com') + .on('downloadProgress', progress => { + // Report download progress + }) + .on('uploadProgress', progress => { + // Report upload progress + }); + + console.log(response); +})(); +``` + +##### .once('retry', retryCount, error) + +To enable retrying on a Got stream, it is required to have a `retry` handler attached.\ +When this event is emitted, you should reset the stream you were writing to and prepare the body again. + +See the [`retry`](#retry-stream) option for an example implementation. + +##### .ip + +Type: `string` + +The remote IP address. + +##### .aborted + +Type: `boolean` + +Indicates whether the request has been aborted or not. + +##### .timings + +The same as `response.timings`. -```sh -npm install got +##### .isFromCache + +The same as `response.isFromCache`. + +##### .socket + +The same as `response.socket`. + +##### .on('error', error) + +The emitted `error` is an instance of [`RequestError`](#gotrequesterror). + +#### Pagination + +#### got.paginate(url, options?) +#### got.paginate.each(url, options?) + +Returns an async iterator: + +```js +(async () => { + const countLimit = 10; + + const pagination = got.paginate('https://api.github.com/repos/sindresorhus/got/commits', { + pagination: {countLimit} + }); + + console.log(`Printing latest ${countLimit} Got commits (newest to oldest):`); + + for await (const commitData of pagination) { + console.log(commitData.commit.message); + } +})(); ``` -**Warning:** This package is native [ESM](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) and no longer provides a CommonJS export. If your project uses CommonJS, you will have to [convert to ESM](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c). Please don't open issues for questions regarding CommonJS / ESM. +See [`options.pagination`](#pagination) for more pagination options. -**Got v11 is no longer maintained and we will not accept any backport requests.** +#### got.paginate.all(url, options?) -## Take a peek +Returns a Promise for an array of all results: -**A [quick start](documentation/quick-start.md) guide is available.** +```js +(async () => { + const countLimit = 10; -### JSON mode + const results = await got.paginate.all('https://api.github.com/repos/sindresorhus/got/commits', { + pagination: {countLimit} + }); -Got has a dedicated option for handling JSON payload.\ -Furthermore, the promise exposes a `.json()` function that returns `Promise`. + console.log(`Printing latest ${countLimit} Got commits (newest to oldest):`); + console.log(results); +})(); +``` + +See [`options.pagination`](#pagination) for more pagination options. + +#### got.get(url, options?) +#### got.post(url, options?) +#### got.put(url, options?) +#### got.patch(url, options?) +#### got.head(url, options?) +#### got.delete(url, options?) + +Sets [`options.method`](#method) to the method name and makes a request. + +### Instances + +#### got.extend(...options) + +Configure a new `got` instance with default `options`. The `options` are merged with the parent instance's `defaults.options` using [`got.mergeOptions`](#gotmergeoptionsparentoptions-newoptions). You can access the resolved options with the `.defaults` property on the instance. + +```js +const client = got.extend({ + prefixUrl: 'https://example.com', + headers: { + 'x-unicorn': 'rainbow' + } +}); + +client.get('demo'); + +/* HTTP Request => + * GET /demo HTTP/1.1 + * Host: example.com + * x-unicorn: rainbow + */ +``` + +```js +(async () => { + const client = got.extend({ + prefixUrl: 'httpbin.org', + headers: { + 'x-foo': 'bar' + } + }); + const {headers} = await client.get('headers').json(); + //=> headers['x-foo'] === 'bar' + + const jsonClient = client.extend({ + responseType: 'json', + resolveBodyOnly: true, + headers: { + 'x-baz': 'qux' + } + }); + const {headers: headers2} = await jsonClient.get('headers'); + //=> headers2['x-foo'] === 'bar' + //=> headers2['x-baz'] === 'qux' +})(); +``` + +Additionally, `got.extend()` accepts two properties from the `defaults` object: `mutableDefaults` and `handlers`. Example: ```js -import got from 'got'; +// You can now modify `mutableGot.defaults.options`. +const mutableGot = got.extend({mutableDefaults: true}); + +const mergedHandlers = got.extend({ + handlers: [ + (options, next) => { + delete options.headers.referer; + + return next(options); + } + ] +}); +``` -const {data} = await got.post('https://httpbin.org/anything', { - json: { - hello: 'world' +**Note:** Handlers can be asynchronous. The recommended approach is: + +```js +const handler = (options, next) => { + if (options.isStream) { + // It's a Stream + return next(options); } -}).json(); -console.log(data); -//=> {"hello": "world"} + // It's a Promise + return (async () => { + try { + const response = await next(options); + response.yourOwnProperty = true; + return response; + } catch (error) { + // Every error will be replaced by this one. + // Before you receive any error here, + // it will be passed to the `beforeError` hooks first. + // Note: this one won't be passed to `beforeError` hook. It's final. + throw new Error('Your very own error.'); + } + })(); +}; + +const instance = got.extend({handlers: [handler]}); ``` -For advanced JSON usage, check out the [`parseJson`](documentation/2-options.md#parsejson) and [`stringifyJson`](documentation/2-options.md#stringifyjson) options. +#### got.extend(...options, ...instances, ...) -**For more useful tips like this, visit the [Tips](documentation/tips.md) page.** +Merges many instances into a single one: +- options are merged using [`got.mergeOptions()`](#gotmergeoptionsparentoptions-newoptions) (including hooks), +- handlers are stored in an array (you can access them through `instance.defaults.handlers`). -## Highlights +```js +const a = {headers: {cat: 'meow'}}; +const b = got.extend({ + options: { + headers: { + cow: 'moo' + } + } +}); -- [Used by 10K+ packages and 5M+ repos](https://github.com/sindresorhus/got/network/dependents) -- [Actively maintained](https://github.com/sindresorhus/got/graphs/contributors) -- [Trusted by many companies](#widely-used) +// The same as `got.extend(a).extend(b)`. +// Note `a` is options and `b` is an instance. +got.extend(a, b); +//=> {headers: {cat: 'meow', cow: 'moo'}} +``` + +#### got.mergeOptions(parent, ...sources) + +Extends parent options. Avoid using [object spread](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#Spread_in_object_literals) as it doesn't work recursively: + +```js +const a = {headers: {cat: 'meow', wolf: ['bark', 'wrrr']}}; +const b = {headers: {cow: 'moo', wolf: ['auuu']}}; + +{...a, ...b} // => {headers: {cow: 'moo', wolf: ['auuu']}} +got.mergeOptions(a, b) // => {headers: {cat: 'meow', cow: 'moo', wolf: ['auuu']}} +``` + +**Note:** Only Got options are merged! Custom user options should be defined via [`options.context`](#context). + +Options are deeply merged to a new object. The value of each key is determined as follows: + +- If the new property is not defined, the old value is used. +- If the new property is explicitly set to `undefined`: + - If the parent property is a plain `object`, the parent value is deeply cloned. + - Otherwise, `undefined` is used. +- If the parent value is an instance of `URLSearchParams`: + - If the new value is a `string`, an `object` or an instance of `URLSearchParams`, a new `URLSearchParams` instance is created. The values are merged using [`urlSearchParams.append(key, value)`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/append). The keys defined in the new value override the keys defined in the parent value. Please note that `null` values point to an empty string and `undefined` values will exclude the entry. + - Otherwise, the only available value is `undefined`. +- If the new property is a plain `object`: + - If the parent property is a plain `object` too, both values are merged recursively into a new `object`. + - Otherwise, only the new value is deeply cloned. +- If the new property is an `Array`, it overwrites the old one with a deep clone of the new property. +- Properties that are not enumerable, such as `context`, `body`, `json`, and `form`, will not be merged. +- Otherwise, the new value is assigned to the key. + +```js +const a = {json: {cat: 'meow'}}; +const b = {json: {cow: 'moo'}}; + +got.mergeOptions(a, b); +//=> {json: {cow: 'moo'}} +``` + +#### got.defaults + +Type: `object` + +The Got defaults used in that instance. + +##### [options](#options) + +##### handlers + +Type: `Function[]`\ +Default: `[]` + +An array of functions. You execute them directly by calling `got()`. They are some sort of "global hooks" - these functions are called first. The last handler (*it's hidden*) is either [`asPromise`](source/core/as-promise/index.ts) or [`asStream`](source/core/index.ts), depending on the `options.isStream` property. + +Each handler takes two arguments: + +###### [options](#options) + +###### next() + +Returns a `Promise` or a `Stream` depending on [`options.isStream`](#isstream). + +```js +const settings = { + handlers: [ + (options, next) => { + if (options.isStream) { + // It's a Stream, so we can perform stream-specific actions on it + return next(options) + .on('request', request => { + setTimeout(() => { + request.abort(); + }, 50); + }); + } + + // It's a Promise + return next(options); + } + ], + options: got.mergeOptions(got.defaults.options, { + responseType: 'json' + }) +}; + +const jsonGot = got.extend(settings); +``` + +##### mutableDefaults + +Type: `boolean`\ +Default: `false` + +A read-only boolean describing whether the defaults are mutable or not. If set to `true`, you can [update headers over time](#hooksafterresponse), for example, update an access token when it expires. + +## Types + +Got exports some handy TypeScript types and interfaces. See the type definition for all the exported types. + +### Got + +TypeScript will automatically infer types for Got instances, but in case you want to define something like dependencies, you can import the available types directly from Got. + +```ts +import {GotRequestFunction} from 'got'; + +interface Dependencies { + readonly post: GotRequestFunction +} +``` + +### Hooks + +When writing hooks, you can refer to their types to keep your interfaces consistent. + +```ts +import {BeforeRequestHook} from 'got'; + +const addAccessToken = (accessToken: string): BeforeRequestHook => options => { + options.path = `${options.path}?access_token=${accessToken}`; +} +``` + +## Errors + +Each error contains an `options` property which are the options Got used to create a request - just to make debugging easier.\ +Additionaly, the errors may have `request` (Got Stream) and `response` (Got Response) properties depending on which phase of the request failed. + +#### got.RequestError + +When a request fails. Contains a `code` property with error class code, like `ECONNREFUSED`. If there is no specific code supplied, `code` defaults to `ERR_GOT_REQUEST_ERROR`. All the errors below inherit this one. + +#### got.CacheError + +When a cache method fails, for example, if the database goes down or there's a filesystem error. Contains a `code` property with `ERR_CACHE_ACCESS` or a more specific failure code. + +#### got.ReadError + +When reading from response stream fails. Contains a `code` property with `ERR_READING_RESPONSE_STREAM` or a more specific failure code. + +#### got.ParseError + +When server response code is 2xx, and parsing body fails. Includes a `response` property. Contains a `code` property with `ERR_BODY_PARSE_FAILURE` or a more specific failure code. + +#### got.UploadError + +When the request body is a stream and an error occurs while reading from that stream. Contains a `code` property with `ERR_UPLOAD` or a more specific failure code. + +#### got.HTTPError + +When the server response code is not 2xx nor 3xx if `options.followRedirect` is `true`, but always except for 304. Includes a `response` property. Contains a `code` property with `ERR_NON_2XX_3XX_RESPONSE` or a more specific failure code. + + +#### got.MaxRedirectsError + +When the server redirects you more than ten times. Includes a `response` property. Contains a `code` property with `ERR_TOO_MANY_REDIRECTS`. + +#### got.UnsupportedProtocolError + +When given an unsupported protocol. Contains a `code` property with `ERR_UNSUPPORTED_PROTOCOL`. + +#### got.TimeoutError + +When the request is aborted due to a [timeout](#timeout). Includes an `event` and `timings` property. Contains a `code` property with `ETIMEDOUT`. + +#### got.CancelError + +When the request is aborted with `.cancel()`. Contains a `code` property with `ERR_CANCELED`. + +## Aborting the request + +The promise returned by Got has a [`.cancel()`](https://github.com/sindresorhus/p-cancelable) method which when called, aborts the request. + +```js +(async () => { + const request = got(url, options); + + // … -## Documentation + // In another part of the code + if (something) { + request.cancel(); + } + + // … + + try { + await request; + } catch (error) { + if (request.isCanceled) { // Or `error instanceof got.CancelError` + // Handle cancelation + } + + // Handle other errors + } +})(); +``` + +When using hooks, simply throw an error to abort the request. + +```js +const got = require('got'); + +(async () => { + const request = got(url, { + hooks: { + beforeRequest: [ + () => { + throw new Error('Oops. Request canceled.'); + } + ] + } + }); + + try { + await request; + } catch (error) { + // … + } +})(); +``` + +To abort the Got Stream request, just call `stream.destroy()`. + +```js +const got = require('got'); + +const stream = got.stream(url); +stream.destroy(); +``` + + +## Cache + +Got implements [RFC 7234](https://httpwg.org/specs/rfc7234.html) compliant HTTP caching which works out of the box in-memory and is easily pluggable with a wide range of storage adapters. Fresh cache entries are served directly from the cache, and stale cache entries are revalidated with `If-None-Match`/`If-Modified-Since` headers. You can read more about the underlying cache behavior in the [`cacheable-request` documentation](https://github.com/lukechilds/cacheable-request). For DNS cache, Got uses [`cacheable-lookup`](https://github.com/szmarczak/cacheable-lookup). + +You can use the JavaScript `Map` type as an in-memory cache: + +```js +const got = require('got'); + +const map = new Map(); + +(async () => { + let response = await got('https://sindresorhus.com', {cache: map}); + console.log(response.isFromCache); + //=> false + + response = await got('https://sindresorhus.com', {cache: map}); + console.log(response.isFromCache); + //=> true +})(); +``` + +Got uses [Keyv](https://github.com/lukechilds/keyv) internally to support a wide range of storage adapters. For something more scalable you could use an [official Keyv storage adapter](https://github.com/lukechilds/keyv#official-storage-adapters): + +``` +$ npm install @keyv/redis +``` + +```js +const got = require('got'); +const KeyvRedis = require('@keyv/redis'); + +const redis = new KeyvRedis('redis://user:pass@localhost:6379'); + +got('https://sindresorhus.com', {cache: redis}); +``` + +Got supports anything that follows the Map API, so it's easy to write your own storage adapter or use a third-party solution. + +For example, the following are all valid storage adapters: + +```js +const storageAdapter = new Map(); +// Or +const storageAdapter = require('./my-storage-adapter'); +// Or +const QuickLRU = require('quick-lru'); +const storageAdapter = new QuickLRU({maxSize: 1000}); + +got('https://sindresorhus.com', {cache: storageAdapter}); +``` + +View the [Keyv docs](https://github.com/lukechilds/keyv) for more information on how to use storage adapters. + +## Proxies + +You can use the [`tunnel`](https://github.com/koichik/node-tunnel) package with the `agent` option to work with proxies: + +```js +const got = require('got'); +const tunnel = require('tunnel'); + +got('https://sindresorhus.com', { + agent: { + https: tunnel.httpsOverHttp({ + proxy: { + host: 'localhost' + } + }) + } +}); +``` + +Otherwise, you can use the [`hpagent`](https://github.com/delvedor/hpagent) package, which keeps the internal sockets alive to be reused. + +```js +const got = require('got'); +const {HttpsProxyAgent} = require('hpagent'); + +got('https://sindresorhus.com', { + agent: { + https: new HttpsProxyAgent({ + keepAlive: true, + keepAliveMsecs: 1000, + maxSockets: 256, + maxFreeSockets: 256, + scheduling: 'lifo', + proxy: 'https://localhost:8080' + }) + } +}); +``` + +Alternatively, use [`global-agent`](https://github.com/gajus/global-agent) to configure a global proxy for all HTTP/HTTPS traffic in your program. + +Read the [`http2-wrapper`](https://github.com/szmarczak/http2-wrapper/#proxy-support) docs to learn about proxying for HTTP/2. + +## Cookies + +You can use the [`tough-cookie`](https://github.com/salesforce/tough-cookie) package: + +```js +const {promisify} = require('util'); +const got = require('got'); +const {CookieJar} = require('tough-cookie'); + +(async () => { + const cookieJar = new CookieJar(); + const setCookie = promisify(cookieJar.setCookie.bind(cookieJar)); + + await setCookie('foo=bar', 'https://example.com'); + await got('https://example.com', {cookieJar}); +})(); +``` + +## Form data + +You can use the [`form-data`](https://github.com/form-data/form-data) package to create POST request with form data: + +```js +const fs = require('fs'); +const got = require('got'); +const FormData = require('form-data'); -By default, Got will retry on failure. To disable this option, set [`options.retry.limit`](documentation/7-retry.md#retry) to 0. +const form = new FormData(); -#### Main API +form.append('my_file', fs.createReadStream('/foo/bar.jpg')); -- [x] [Promise API](documentation/1-promise.md) -- [x] [Options](documentation/2-options.md) -- [x] [Stream API](documentation/3-streams.md) -- [x] [Pagination API](documentation/4-pagination.md) -- [x] [Advanced HTTPS API](documentation/5-https.md) -- [x] [HTTP/2 support](documentation/2-options.md#http2) -- [x] [`Response` class](documentation/3-streams.md#response-2) +got.post('https://example.com', { + body: form +}); +``` + +## OAuth + +You can use the [`oauth-1.0a`](https://github.com/ddo/oauth-1.0a) package to create a signed OAuth request: + +```js +const got = require('got'); +const crypto = require('crypto'); +const OAuth = require('oauth-1.0a'); + +const oauth = OAuth({ + consumer: { + key: process.env.CONSUMER_KEY, + secret: process.env.CONSUMER_SECRET + }, + signature_method: 'HMAC-SHA1', + hash_function: (baseString, key) => crypto.createHmac('sha1', key).update(baseString).digest('base64') +}); + +const token = { + key: process.env.ACCESS_TOKEN, + secret: process.env.ACCESS_TOKEN_SECRET +}; + +const url = 'https://api.twitter.com/1.1/statuses/home_timeline.json'; + +got(url, { + headers: oauth.toHeader(oauth.authorize({url, method: 'GET'}, token)), + responseType: 'json' +}); +``` + +## Unix Domain Sockets + +Requests can also be sent via [unix domain sockets](http://serverfault.com/questions/124517/whats-the-difference-between-unix-socket-and-tcp-ip-socket). Use the following URL scheme: `PROTOCOL://unix:SOCKET:PATH`. + +- `PROTOCOL` - `http` or `https` *(optional)* +- `SOCKET` - Absolute path to a unix domain socket, for example: `/var/run/docker.sock` +- `PATH` - Request path, for example: `/v2/keys` + +```js +const got = require('got'); + +got('http://unix:/var/run/docker.sock:/containers/json'); + +// Or without protocol (HTTP by default) +got('unix:/var/run/docker.sock:/containers/json'); +``` + +## AWS + +Requests to AWS services need to have their headers signed. This can be accomplished by using the [`got4aws`](https://www.npmjs.com/package/got4aws) package. This is an example for querying an ["API Gateway"](https://docs.aws.amazon.com/apigateway/api-reference/signing-requests/) with a signed request. + +```js +const got4aws = require('got4aws');; + +const awsClient = got4aws(); + +const response = await awsClient('https://.execute-api..amazonaws.com//endpoint/path', { + // Request-specific options +}); +``` + +## Testing + +You can test your requests by using the [`nock`](https://github.com/node-nock/nock) package to mock an endpoint: + +```js +const got = require('got'); +const nock = require('nock'); + +nock('https://sindresorhus.com') + .get('/') + .reply(200, 'Hello world!'); + +(async () => { + const response = await got('https://sindresorhus.com'); + console.log(response.body); + //=> 'Hello world!' +})(); +``` + +Bear in mind, that by default `nock` mocks only one request. Got will [retry](#retry) on failed requests by default, causing a `No match for request ...` error. The solution is to either disable retrying (set `options.retry` to `0`) or call `.persist()` on the mocked request. + +```js +const got = require('got'); +const nock = require('nock'); + +const scope = nock('https://sindresorhus.com') + .get('/') + .reply(500, 'Internal server error') + .persist(); + +(async () => { + try { + await got('https://sindresorhus.com') + } catch (error) { + console.log(error.response.body); + //=> 'Internal server error' + + console.log(error.response.retryCount); + //=> 2 + } + + scope.persist(false); +})(); +``` -#### Timeouts and retries +For real integration testing we recommend using [`ava`](https://github.com/avajs/ava) with [`create-test-server`](https://github.com/lukechilds/create-test-server). We're using a macro so we don't have to `server.listen()` and `server.close()` every test. Take a look at one of our tests: -- [x] [Advanced timeout handling](documentation/6-timeout.md) -- [x] [Retries on failure](documentation/7-retry.md) -- [x] [Errors with metadata](documentation/8-errors.md) +```js +test('retry function gets iteration count', withServer, async (t, server, got) => { + let knocks = 0; + server.get('/', (request, response) => { + if (knocks++ === 1) { + response.end('who`s there?'); + } + }); + + await got({ + retry: { + calculateDelay: ({attemptCount}) => { + t.true(is.number(attemptCount)); + return attemptCount < 2 ? 1 : 0; + } + } + }); +}); +``` + +## Tips + +### JSON mode + +To pass an object as the body, you need to use the `json` option. It will be stringified using `JSON.stringify`. Example: + +```js +const got = require('got'); + +(async () => { + const {body} = await got.post('https://httpbin.org/anything', { + json: { + hello: 'world' + }, + responseType: 'json' + }); + + console.log(body.data); + //=> '{"hello":"world"}' +})(); +``` + +To receive a JSON body you can either set `responseType` option to `json` or use `promise.json()`. Example: + +```js +const got = require('got'); + +(async () => { + const body = await got.post('https://httpbin.org/anything', { + json: { + hello: 'world' + } + }).json(); + + console.log(body); + //=> {…} +})(); +``` + +### User Agent + +It's a good idea to set the `'user-agent'` header so the provider can more easily see how their resource is used. By default, it's the URL to this repo. You can omit this header by setting it to `undefined`. + +```js +const got = require('got'); +const pkg = require('./package.json'); + +got('https://sindresorhus.com', { + headers: { + 'user-agent': `my-package/${pkg.version} (https://github.com/username/my-package)` + } +}); + +got('https://sindresorhus.com', { + headers: { + 'user-agent': undefined + } +}); +``` -#### Advanced creation +### 304 Responses -- [x] [Hooks](documentation/9-hooks.md) -- [x] [Instances](documentation/10-instances.md) -- [x] [Progress events & other events](documentation/3-streams.md#events) -- [x] [Plugins](documentation/lets-make-a-plugin.md) -- [x] [Compose](documentation/examples/advanced-creation.js) +Bear in mind; if you send an `if-modified-since` header and receive a `304 Not Modified` response, the body will be empty. It's your responsibility to cache and retrieve the body contents. -#### Cache, Proxy and UNIX sockets +### Custom endpoints -- [x] [RFC compliant caching](documentation/cache.md) -- [x] [Proxy support](documentation/tips.md#proxying) -- [x] [Unix Domain Sockets](documentation/2-options.md#enableunixsockets) +Use `got.extend()` to make it nicer to work with REST APIs. Especially if you use the `prefixUrl` option. -#### Integration +```js +const got = require('got'); +const pkg = require('./package.json'); + +const custom = got.extend({ + prefixUrl: 'example.com', + responseType: 'json', + headers: { + 'user-agent': `my-package/${pkg.version} (https://github.com/username/my-package)` + } +}); -- [x] [TypeScript support](documentation/typescript.md) -- [x] [AWS](documentation/tips.md#aws) -- [x] [Testing](documentation/tips.md#testing) +// Use `custom` exactly how you use `got` +(async () => { + const list = await custom('v1/users/list'); +})(); +``` ---- +## FAQ -### Migration guides +### Why yet another HTTP client? -- [Request migration guide](documentation/migration-guides/request.md) - - [*(Note that Request is unmaintained)*](https://github.com/request/request/issues/3142) -- [Axios](documentation/migration-guides/axios.md) -- [Node.js](documentation/migration-guides/nodejs.md) +Got was created because the popular [`request`](https://github.com/request/request) package is bloated: [![Install size](https://packagephobia.now.sh/badge?p=request)](https://packagephobia.now.sh/result?p=request)\ +Furthermore, Got is fully written in TypeScript and actively maintained. -## Got plugins +### Electron support has been removed -- [`got4aws`](https://github.com/SamVerschueren/got4aws) - Got convenience wrapper to interact with AWS v4 signed APIs -- [`gh-got`](https://github.com/sindresorhus/gh-got) - Got convenience wrapper to interact with the GitHub API -- [`gl-got`](https://github.com/singapore/gl-got) - Got convenience wrapper to interact with the GitLab API -- [`gotql`](https://github.com/khaosdoctor/gotql) - Got convenience wrapper to interact with GraphQL using JSON-parsed queries instead of strings -- [`got-fetch`](https://github.com/alexghr/got-fetch) - Got with a [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) interface -- [`got-scraping`](https://github.com/apify/got-scraping) - Got wrapper specifically designed for web scraping purposes -- [`got-ssrf`](https://github.com/JaneJeon/got-ssrf) - Got wrapper to protect server-side requests against SSRF attacks +The Electron `net` module is not consistent with the Node.js `http` module. See [#899](https://github.com/sindresorhus/got/issues/899) for more info. ## Comparison -| | `got` | [`node-fetch`][n0] | [`ky`][k0] | [`axios`][a0] | [`superagent`][s0] | -|-----------------------|:-------------------:|:--------------------:|:------------------------:|:------------------:|:----------------------:| -| HTTP/2 support | :heavy_check_mark:¹ | :x: | :x: | :x: | :heavy_check_mark:\*\* | -| Browser support | :x: | :heavy_check_mark:\* | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | -| Promise API | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | -| Stream API | :heavy_check_mark: | Node.js only | :x: | :x: | :heavy_check_mark: | -| Pagination API | :heavy_check_mark: | :x: | :x: | :x: | :x: | -| Request cancelation | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | -| RFC compliant caching | :heavy_check_mark: | :x: | :x: | :x: | :x: | -| Cookies (out-of-the-box) | :heavy_check_mark: | :x: | :x: | :x: | :x: | -| Follows redirects | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | -| Retries on failure | :heavy_check_mark: | :x: | :heavy_check_mark: | :x: | :heavy_check_mark: | -| Progress events | :heavy_check_mark: | :x: | :heavy_check_mark:\*\*\* | Browser only | :heavy_check_mark: | -| Handles gzip/deflate | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | -| Advanced timeouts | :heavy_check_mark: | :x: | :x: | :x: | :x: | -| Timings | :heavy_check_mark: | :x: | :x: | :x: | :x: | -| Errors with metadata | :heavy_check_mark: | :x: | :heavy_check_mark: | :heavy_check_mark: | :x: | -| JSON mode | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | -| Custom defaults | :heavy_check_mark: | :x: | :heavy_check_mark: | :heavy_check_mark: | :x: | -| Composable | :heavy_check_mark: | :x: | :x: | :x: | :heavy_check_mark: | -| Hooks | :heavy_check_mark: | :x: | :heavy_check_mark: | :heavy_check_mark: | :x: | -| Issues open | [![][gio]][g1] | [![][nio]][n1] | [![][kio]][k1] | [![][aio]][a1] | [![][sio]][s1] | -| Issues closed | [![][gic]][g2] | [![][nic]][n2] | [![][kic]][k2] | [![][aic]][a2] | [![][sic]][s2] | -| Downloads | [![][gd]][g3] | [![][nd]][n3] | [![][kd]][k3] | [![][ad]][a3] | [![][sd]][s3] | -| Coverage | TBD | [![][nc]][n4] | [![][kc]][k4] | [![][ac]][a4] | [![][sc]][s4] | -| Build | [![][gb]][g5] | [![][nb]][n5] | [![][kb]][k5] | [![][ab]][a5] | [![][sb]][s5] | -| Bugs | [![][gbg]][g6] | [![][nbg]][n6] | [![][kbg]][k6] | [![][abg]][a6] | [![][sbg]][s6] | -| Dependents | [![][gdp]][g7] | [![][ndp]][n7] | [![][kdp]][k7] | [![][adp]][a7] | [![][sdp]][s7] | -| Install size | [![][gis]][g8] | [![][nis]][n8] | [![][kis]][k8] | [![][ais]][a8] | [![][sis]][s8] | -| GitHub stars | [![][gs]][g9] | [![][ns]][n9] | [![][ks]][k9] | [![][as]][a9] | [![][ss]][s9] | -| TypeScript support | [![][gts]][g10] | [![][nts]][n10] | [![][kts]][k10] | [![][ats]][a10] | [![][sts]][s11] | -| Last commit | [![][glc]][g11] | [![][nlc]][n11] | [![][klc]][k11] | [![][alc]][a11] | [![][slc]][s11] | +| | `got` | [`request`][r0] | [`node-fetch`][n0] | [`ky`][k0] | [`axios`][a0] | [`superagent`][s0] | +|-----------------------|:------------------:|:------------------:|:--------------------:|:------------------------:|:------------------:|:----------------------:| +| HTTP/2 support | :sparkle: | :x: | :x: | :x: | :x: | :heavy_check_mark:\*\* | +| Browser support | :x: | :x: | :heavy_check_mark:\* | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | +| Promise API | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | +| Stream API | :heavy_check_mark: | :heavy_check_mark: | Node.js only | :x: | :x: | :heavy_check_mark: | +| Pagination API | :heavy_check_mark: | :x: | :x: | :x: | :x: | :x: | +| Request cancelation | :heavy_check_mark: | :x: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | +| RFC compliant caching | :heavy_check_mark: | :x: | :x: | :x: | :x: | :x: | +| Cookies (out-of-box) | :heavy_check_mark: | :heavy_check_mark: | :x: | :x: | :x: | :x: | +| Follows redirects | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | +| Retries on failure | :heavy_check_mark: | :x: | :x: | :heavy_check_mark: | :x: | :heavy_check_mark: | +| Progress events | :heavy_check_mark: | :x: | :x: | :heavy_check_mark:\*\*\* | Browser only | :heavy_check_mark: | +| Handles gzip/deflate | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | +| Advanced timeouts | :heavy_check_mark: | :x: | :x: | :x: | :x: | :x: | +| Timings | :heavy_check_mark: | :heavy_check_mark: | :x: | :x: | :x: | :x: | +| Errors with metadata | :heavy_check_mark: | :x: | :x: | :heavy_check_mark: | :heavy_check_mark: | :x: | +| JSON mode | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | +| Custom defaults | :heavy_check_mark: | :heavy_check_mark: | :x: | :heavy_check_mark: | :heavy_check_mark: | :x: | +| Composable | :heavy_check_mark: | :x: | :x: | :x: | :x: | :heavy_check_mark: | +| Hooks | :heavy_check_mark: | :x: | :x: | :heavy_check_mark: | :heavy_check_mark: | :x: | +| Issues open | [![][gio]][g1] | [![][rio]][r1] | [![][nio]][n1] | [![][kio]][k1] | [![][aio]][a1] | [![][sio]][s1] | +| Issues closed | [![][gic]][g2] | [![][ric]][r2] | [![][nic]][n2] | [![][kic]][k2] | [![][aic]][a2] | [![][sic]][s2] | +| Downloads | [![][gd]][g3] | [![][rd]][r3] | [![][nd]][n3] | [![][kd]][k3] | [![][ad]][a3] | [![][sd]][s3] | +| Coverage | [![][gc]][g4] | [![][rc]][r4] | [![][nc]][n4] | [![][kc]][k4] | [![][ac]][a4] | [![][sc]][s4] | +| Build | [![][gb]][g5] | [![][rb]][r5] | [![][nb]][n5] | [![][kb]][k5] | [![][ab]][a5] | [![][sb]][s5] | +| Bugs | [![][gbg]][g6] | [![][rbg]][r6] | [![][nbg]][n6] | [![][kbg]][k6] | [![][abg]][a6] | [![][sbg]][s6] | +| Dependents | [![][gdp]][g7] | [![][rdp]][r7] | [![][ndp]][n7] | [![][kdp]][k7] | [![][adp]][a7] | [![][sdp]][s7] | +| Install size | [![][gis]][g8] | [![][ris]][r8] | [![][nis]][n8] | [![][kis]][k8] | [![][ais]][a8] | [![][sis]][s8] | +| GitHub stars | [![][gs]][g9] | [![][rs]][r9] | [![][ns]][n9] | [![][ks]][k9] | [![][as]][a9] | [![][ss]][s9] | +| TypeScript support | [![][gts]][g10] | [![][rts]][r10] | [![][nts]][n10] | [![][kts]][k10] | [![][ats]][a10] | [![][sts]][s11] | +| Last commit | [![][glc]][g11] | [![][rlc]][r11] | [![][nlc]][n11] | [![][klc]][k11] | [![][alc]][a11] | [![][slc]][s11] | \* It's almost API compatible with the browser `fetch` API.\ \*\* Need to switch the protocol manually. Doesn't accept PUSH streams and doesn't reuse HTTP/2 sessions.\ \*\*\* Currently, only `DownloadProgress` event is supported, `UploadProgress` event is not supported.\ -¹ Requires Node.js 15.10.0 or above.\ :sparkle: Almost-stable feature, but the API may change. Don't hesitate to try it out!\ :grey_question: Feature in early stage of development. Very experimental. [k0]: https://github.com/sindresorhus/ky +[r0]: https://github.com/request/request [n0]: https://github.com/node-fetch/node-fetch [a0]: https://github.com/axios/axios [s0]: https://github.com/visionmedia/superagent -[gio]: https://img.shields.io/github/issues-raw/sindresorhus/got?color=gray&label -[kio]: https://img.shields.io/github/issues-raw/sindresorhus/ky?color=gray&label -[nio]: https://img.shields.io/github/issues-raw/bitinn/node-fetch?color=gray&label -[aio]: https://img.shields.io/github/issues-raw/axios/axios?color=gray&label -[sio]: https://img.shields.io/github/issues-raw/visionmedia/superagent?color=gray&label +[gio]: https://badgen.net/github/open-issues/sindresorhus/got?label +[kio]: https://badgen.net/github/open-issues/sindresorhus/ky?label +[rio]: https://badgen.net/github/open-issues/request/request?label +[nio]: https://badgen.net/github/open-issues/bitinn/node-fetch?label +[aio]: https://badgen.net/github/open-issues/axios/axios?label +[sio]: https://badgen.net/github/open-issues/visionmedia/superagent?label [g1]: https://github.com/sindresorhus/got/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc [k1]: https://github.com/sindresorhus/ky/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc +[r1]: https://github.com/request/request/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc [n1]: https://github.com/bitinn/node-fetch/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc [a1]: https://github.com/axios/axios/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc [s1]: https://github.com/visionmedia/superagent/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc -[gic]: https://img.shields.io/github/issues-closed-raw/sindresorhus/got?color=blue&label -[kic]: https://img.shields.io/github/issues-closed-raw/sindresorhus/ky?color=blue&label -[nic]: https://img.shields.io/github/issues-closed-raw/bitinn/node-fetch?color=blue&label -[aic]: https://img.shields.io/github/issues-closed-raw/axios/axios?color=blue&label -[sic]: https://img.shields.io/github/issues-closed-raw/visionmedia/superagent?color=blue&label +[gic]: https://badgen.net/github/closed-issues/sindresorhus/got?label +[kic]: https://badgen.net/github/closed-issues/sindresorhus/ky?label +[ric]: https://badgen.net/github/closed-issues/request/request?label +[nic]: https://badgen.net/github/closed-issues/bitinn/node-fetch?label +[aic]: https://badgen.net/github/closed-issues/axios/axios?label +[sic]: https://badgen.net/github/closed-issues/visionmedia/superagent?label [g2]: https://github.com/sindresorhus/got/issues?q=is%3Aissue+is%3Aclosed+sort%3Aupdated-desc [k2]: https://github.com/sindresorhus/ky/issues?q=is%3Aissue+is%3Aclosed+sort%3Aupdated-desc +[r2]: https://github.com/request/request/issues?q=is%3Aissue+is%3Aclosed+sort%3Aupdated-desc [n2]: https://github.com/bitinn/node-fetch/issues?q=is%3Aissue+is%3Aclosed+sort%3Aupdated-desc [a2]: https://github.com/axios/axios/issues?q=is%3Aissue+is%3Aclosed+sort%3Aupdated-desc [s2]: https://github.com/visionmedia/superagent/issues?q=is%3Aissue+is%3Aclosed+sort%3Aupdated-desc -[gd]: https://img.shields.io/npm/dm/got?color=darkgreen&label -[kd]: https://img.shields.io/npm/dm/ky?color=darkgreen&label -[nd]: https://img.shields.io/npm/dm/node-fetch?color=darkgreen&label -[ad]: https://img.shields.io/npm/dm/axios?color=darkgreen&label -[sd]: https://img.shields.io/npm/dm/superagent?color=darkgreen&label +[gd]: https://badgen.net/npm/dm/got?label +[kd]: https://badgen.net/npm/dm/ky?label +[rd]: https://badgen.net/npm/dm/request?label +[nd]: https://badgen.net/npm/dm/node-fetch?label +[ad]: https://badgen.net/npm/dm/axios?label +[sd]: https://badgen.net/npm/dm/superagent?label [g3]: https://www.npmjs.com/package/got [k3]: https://www.npmjs.com/package/ky +[r3]: https://www.npmjs.com/package/request [n3]: https://www.npmjs.com/package/node-fetch [a3]: https://www.npmjs.com/package/axios [s3]: https://www.npmjs.com/package/superagent -[gc]: https://img.shields.io/coveralls/github/sindresorhus/got?color=0b9062&label -[kc]: https://img.shields.io/codecov/c/github/sindresorhus/ky?color=0b9062&label -[nc]: https://img.shields.io/coveralls/github/bitinn/node-fetch?color=0b9062&label -[ac]: https://img.shields.io/coveralls/github/mzabriskie/axios?color=0b9062&label -[sc]: https://img.shields.io/codecov/c/github/visionmedia/superagent?color=0b9062&label +[gc]: https://badgen.net/coveralls/c/github/sindresorhus/got?label +[kc]: https://badgen.net/codecov/c/github/sindresorhus/ky?label +[rc]: https://badgen.net/coveralls/c/github/request/request?label +[nc]: https://badgen.net/coveralls/c/github/bitinn/node-fetch?label +[ac]: https://badgen.net/coveralls/c/github/mzabriskie/axios?label +[sc]: https://badgen.net/codecov/c/github/visionmedia/superagent?label [g4]: https://coveralls.io/github/sindresorhus/got [k4]: https://codecov.io/gh/sindresorhus/ky +[r4]: https://coveralls.io/github/request/request [n4]: https://coveralls.io/github/bitinn/node-fetch [a4]: https://coveralls.io/github/mzabriskie/axios [s4]: https://codecov.io/gh/visionmedia/superagent -[gb]: https://github.com/sindresorhus/got/actions/workflows/main.yml/badge.svg -[kb]: https://github.com/sindresorhus/ky/actions/workflows/main.yml/badge.svg -[nb]: https://img.shields.io/travis/bitinn/node-fetch?label -[ab]: https://img.shields.io/travis/axios/axios?label -[sb]: https://img.shields.io/travis/visionmedia/superagent?label - -[g5]: https://github.com/sindresorhus/got/actions/workflows/main.yml -[k5]: https://github.com/sindresorhus/ky/actions/workflows/main.yml +[gb]: https://badgen.net/travis/sindresorhus/got?label +[kb]: https://badgen.net/travis/sindresorhus/ky?label +[rb]: https://badgen.net/travis/request/request?label +[nb]: https://badgen.net/travis/bitinn/node-fetch?label +[ab]: https://badgen.net/travis/axios/axios?label +[sb]: https://badgen.net/travis/visionmedia/superagent?label + +[g5]: https://travis-ci.com/github/sindresorhus/got +[k5]: https://travis-ci.com/github/sindresorhus/ky +[r5]: https://travis-ci.org/github/request/request [n5]: https://travis-ci.org/github/bitinn/node-fetch [a5]: https://travis-ci.org/github/axios/axios [s5]: https://travis-ci.org/github/visionmedia/superagent -[gbg]: https://img.shields.io/github/issues-raw/sindresorhus/got/bug?color=darkred&label -[kbg]: https://img.shields.io/github/issues-raw/sindresorhus/ky/bug?color=darkred&label -[nbg]: https://img.shields.io/github/issues-raw/bitinn/node-fetch/bug?color=darkred&label -[abg]: https://img.shields.io/github/issues-raw/axios/axios/bug-fix?color=darkred&label -[sbg]: https://img.shields.io/github/issues-raw/visionmedia/superagent/Bug?color=darkred&label +[gbg]: https://badgen.net/github/label-issues/sindresorhus/got/bug/open?label +[kbg]: https://badgen.net/github/label-issues/sindresorhus/ky/bug/open?label +[rbg]: https://badgen.net/github/label-issues/request/request/Needs%20investigation/open?label +[nbg]: https://badgen.net/github/label-issues/bitinn/node-fetch/bug/open?label +[abg]: https://badgen.net/github/label-issues/axios/axios/type:confirmed%20bug/open?label +[sbg]: https://badgen.net/github/label-issues/visionmedia/superagent/Bug/open?label [g6]: https://github.com/sindresorhus/got/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3Abug [k6]: https://github.com/sindresorhus/ky/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3Abug +[r6]: https://github.com/request/request/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A"Needs+investigation" [n6]: https://github.com/bitinn/node-fetch/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3Abug -[a6]: https://github.com/axios/axios/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%22bug-fix%22 +[a6]: https://github.com/axios/axios/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%22type%3Aconfirmed+bug%22 [s6]: https://github.com/visionmedia/superagent/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3ABug -[gdp]: https://badgen.net/npm/dependents/got?color=orange&label -[kdp]: https://badgen.net/npm/dependents/ky?color=orange&label -[ndp]: https://badgen.net/npm/dependents/node-fetch?color=orange&label -[adp]: https://badgen.net/npm/dependents/axios?color=orange&label -[sdp]: https://badgen.net/npm/dependents/superagent?color=orange&label +[gdp]: https://badgen.net/npm/dependents/got?label +[kdp]: https://badgen.net/npm/dependents/ky?label +[rdp]: https://badgen.net/npm/dependents/request?label +[ndp]: https://badgen.net/npm/dependents/node-fetch?label +[adp]: https://badgen.net/npm/dependents/axios?label +[sdp]: https://badgen.net/npm/dependents/superagent?label [g7]: https://www.npmjs.com/package/got?activeTab=dependents [k7]: https://www.npmjs.com/package/ky?activeTab=dependents +[r7]: https://www.npmjs.com/package/request?activeTab=dependents [n7]: https://www.npmjs.com/package/node-fetch?activeTab=dependents [a7]: https://www.npmjs.com/package/axios?activeTab=dependents [s7]: https://www.npmjs.com/package/visionmedia?activeTab=dependents -[gis]: https://badgen.net/packagephobia/install/got?color=blue&label -[kis]: https://badgen.net/packagephobia/install/ky?color=blue&label -[nis]: https://badgen.net/packagephobia/install/node-fetch?color=blue&label -[ais]: https://badgen.net/packagephobia/install/axios?color=blue&label -[sis]: https://badgen.net/packagephobia/install/superagent?color=blue&label - -[g8]: https://packagephobia.com/result?p=got -[k8]: https://packagephobia.com/result?p=ky -[n8]: https://packagephobia.com/result?p=node-fetch -[a8]: https://packagephobia.com/result?p=axios -[s8]: https://packagephobia.com/result?p=superagent +[gis]: https://badgen.net/packagephobia/install/got?label +[kis]: https://badgen.net/packagephobia/install/ky?label +[ris]: https://badgen.net/packagephobia/install/request?label +[nis]: https://badgen.net/packagephobia/install/node-fetch?label +[ais]: https://badgen.net/packagephobia/install/axios?label +[sis]: https://badgen.net/packagephobia/install/superagent?label + +[g8]: https://packagephobia.now.sh/result?p=got +[k8]: https://packagephobia.now.sh/result?p=ky +[r8]: https://packagephobia.now.sh/result?p=request +[n8]: https://packagephobia.now.sh/result?p=node-fetch +[a8]: https://packagephobia.now.sh/result?p=axios +[s8]: https://packagephobia.now.sh/result?p=superagent -[gs]: https://img.shields.io/github/stars/sindresorhus/got?color=white&label -[ks]: https://img.shields.io/github/stars/sindresorhus/ky?color=white&label -[ns]: https://img.shields.io/github/stars/bitinn/node-fetch?color=white&label -[as]: https://img.shields.io/github/stars/axios/axios?color=white&label -[ss]: https://img.shields.io/github/stars/visionmedia/superagent?color=white&label +[gs]: https://badgen.net/github/stars/sindresorhus/got?label +[ks]: https://badgen.net/github/stars/sindresorhus/ky?label +[rs]: https://badgen.net/github/stars/request/request?label +[ns]: https://badgen.net/github/stars/bitinn/node-fetch?label +[as]: https://badgen.net/github/stars/axios/axios?label +[ss]: https://badgen.net/github/stars/visionmedia/superagent?label [g9]: https://github.com/sindresorhus/got [k9]: https://github.com/sindresorhus/ky +[r9]: https://github.com/request/request [n9]: https://github.com/node-fetch/node-fetch [a9]: https://github.com/axios/axios [s9]: https://github.com/visionmedia/superagent @@ -355,111 +2352,81 @@ By default, Got will retry on failure. To disable this option, set [`options.ret [gts]: https://badgen.net/npm/types/got?label [kts]: https://badgen.net/npm/types/ky?label +[rts]: https://badgen.net/npm/types/request?label [nts]: https://badgen.net/npm/types/node-fetch?label [ats]: https://badgen.net/npm/types/axios?label [sts]: https://badgen.net/npm/types/superagent?label [g10]: https://github.com/sindresorhus/got [k10]: https://github.com/sindresorhus/ky +[r10]: https://github.com/request/request [n10]: https://github.com/node-fetch/node-fetch [a10]: https://github.com/axios/axios [s10]: https://github.com/visionmedia/superagent -[glc]: https://img.shields.io/github/last-commit/sindresorhus/got?color=gray&label -[klc]: https://img.shields.io/github/last-commit/sindresorhus/ky?color=gray&label -[nlc]: https://img.shields.io/github/last-commit/bitinn/node-fetch?color=gray&label -[alc]: https://img.shields.io/github/last-commit/axios/axios?color=gray&label -[slc]: https://img.shields.io/github/last-commit/visionmedia/superagent?color=gray&label +[glc]: https://badgen.net/github/last-commit/sindresorhus/got?label +[klc]: https://badgen.net/github/last-commit/sindresorhus/ky?label +[rlc]: https://badgen.net/github/last-commit/request/request?label +[nlc]: https://badgen.net/github/last-commit/bitinn/node-fetch?label +[alc]: https://badgen.net/github/last-commit/axios/axios?label +[slc]: https://badgen.net/github/last-commit/visionmedia/superagent?label [g11]: https://github.com/sindresorhus/got/commits [k11]: https://github.com/sindresorhus/ky/commits +[r11]: https://github.com/request/request/commits [n11]: https://github.com/node-fetch/node-fetch/commits [a11]: https://github.com/axios/axios/commits [s11]: https://github.com/visionmedia/superagent/commits [Click here][InstallSizeOfTheDependencies] to see the install size of the Got dependencies. -[InstallSizeOfTheDependencies]: https://packagephobia.com/result?p=@sindresorhus/is@4.0.1,@szmarczak/http-timer@4.0.5,@types/cacheable-request@6.0.1,@types/responselike@1.0.0,cacheable-lookup@6.0.0,cacheable-request@7.0.2,decompress-response@6.0.0,get-stream@6.0.1,http2-wrapper@2.0.5,lowercase-keys@2.0.0,p-cancelable@2.1.1,responselike@2.0.0 +[InstallSizeOfTheDependencies]: https://packagephobia.com/result?p=@sindresorhus/is@3.0.0,@szmarczak/http-timer@4.0.5,@types/cacheable-request@6.0.1,@types/responselike@1.0.0,cacheable-lookup@5.0.3,cacheable-request@7.0.1,decompress-response@6.0.0,http2-wrapper@1.0.0,lowercase-keys@2.0.0,p-cancelable@2.0.0,responselike@2.0.0 + +## Related + +- [gh-got](https://github.com/sindresorhus/gh-got) - Got convenience wrapper to interact with the GitHub API +- [gl-got](https://github.com/singapore/gl-got) - Got convenience wrapper to interact with the GitLab API +- [travis-got](https://github.com/samverschueren/travis-got) - Got convenience wrapper to interact with the Travis API +- [graphql-got](https://github.com/kevva/graphql-got) - Got convenience wrapper to interact with GraphQL +- [GotQL](https://github.com/khaosdoctor/gotql) - Got convenience wrapper to interact with GraphQL using JSON-parsed queries instead of strings +- [got-fetch](https://github.com/alexghr/got-fetch) - Got with a `fetch` interface ## Maintainers -[![Sindre Sorhus](https://github.com/sindresorhus.png?size=100)](https://sindresorhus.com) | [![Szymon Marczak](https://github.com/szmarczak.png?size=100)](https://github.com/szmarczak) ----|--- -[Sindre Sorhus](https://sindresorhus.com) | [Szymon Marczak](https://github.com/szmarczak) +[![Sindre Sorhus](https://github.com/sindresorhus.png?size=100)](https://sindresorhus.com) | [![Szymon Marczak](https://github.com/szmarczak.png?size=100)](https://github.com/szmarczak) | [![Giovanni Minotti](https://github.com/Giotino.png?size=100)](https://github.com/Giotino) +---|---|--- +[Sindre Sorhus](https://sindresorhus.com) | [Szymon Marczak](https://github.com/szmarczak) | [Giovanni Minotti](https://github.com/Giotino) + +###### Former + +- [Vsevolod Strukchinsky](https://github.com/floatdrop) +- [Alexander Tesfamichael](https://github.com/alextes) +- [Brandon Smith](https://github.com/brandon93s) +- [Luke Childs](https://github.com/lukechilds) ## These amazing companies are using Got - - - - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - -
- - - - - - - - - - - -
- - - - + +     + +     + +     + +     + +     + +     + +     + +     + +     +
@@ -503,6 +2470,8 @@ By default, Got will retry on failure. To disable this option, set [`options.ret > > — Mirzayev Farid -> Got has been a crucial component of Apify's scraping for years. We use it to extract data from billions of web pages every month, and we really appreciate the powerful API and extensibility, which allowed us to build our own specialized HTTP client on top of Got. The support has always been stellar too. -> -> — Ondra Urban +## For enterprise + +Available as part of the Tidelift Subscription. + +The maintainers of `got` and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-got?utm_source=npm-got&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/setup-pandoc/node_modules/http2-wrapper/README.md b/setup-pandoc/node_modules/http2-wrapper/README.md index 6510a7df4..09b5f480f 100644 --- a/setup-pandoc/node_modules/http2-wrapper/README.md +++ b/setup-pandoc/node_modules/http2-wrapper/README.md @@ -19,7 +19,6 @@ I recommend adapting to the [`http2`](https://nodejs.org/api/http2.html) module > `$ yarn add http2-wrapper` ## Usage - ```js const http2 = require('http2-wrapper'); @@ -87,8 +86,6 @@ request.end('456'); **Note:** The `session` option was renamed to `tlsSession` for better readability. -**Note:** The `timeout` option applies to HTTP/2 streams only. In order to set session timeout, pass an Agent with custom `timeout` option set. - ### http2.auto(url, options, callback) Performs [ALPN](https://nodejs.org/api/tls.html#tls_alpn_and_sni) negotiation. @@ -101,7 +98,7 @@ const http2 = require('http2-wrapper'); const options = { hostname: 'httpbin.org', - protocol: 'http:', // Try changing this to https: + protocol: 'http:', // Note the `http:` protocol here path: '/post', method: 'POST', headers: { @@ -162,30 +159,6 @@ An instance of [`quick-lru`](https://github.com/sindresorhus/quick-lru) used for There is a maximum of 100 entries. You can modify the limit through `protocolCache.maxSize` - note that the change will be visible globally. -### http2.auto.createResolveProtocol(cache, queue, connect) - -#### cache - -Type: `Map` - -This is the store where cached ALPN protocols are put into. - -#### queue - -Type: `Map` - -This is the store that contains pending ALPN negotiation promises. - -#### connect - -Type: `(options, callback) => TLSSocket | Promise` - -See https://github.com/szmarczak/resolve-alpn#connect - -### http2.auto.resolveProtocol(options) - -Returns a `Promise<{alpnProtocol: string}>`. - ### http2.request(url, options, callback) Same as [`https.request`](https://nodejs.org/api/https.html#https_https_request_options_callback). @@ -194,7 +167,7 @@ Same as [`https.request`](https://nodejs.org/api/https.html#https_https_request_ Type: `Http2Session`
-The session used to make the actual request. If none provided, it will use `options.agent` to get one. +The session used to make the actual request. If none provided, it will use `options.agent`. ### http2.get(url, options, callback) @@ -227,21 +200,21 @@ class MyAgent extends http2.Agent { http2.get({ hostname: 'google.com', agent: new MyAgent() -}, response => { - response.on('data', chunk => console.log(`Received chunk of ${chunk.length} bytes`)); +}, res => { + res.on('data', chunk => console.log(`Received chunk of ${chunk.length} bytes`)); }); ``` #### options -Each option is an `Agent` property and can be changed later. +Each option is assigned to each `Agent` instance and can be changed later. ##### timeout Type: `number`
-Default: `0` +Default: `60000` -If there's no activity after `timeout` milliseconds, the session will be closed. If `0`, no timeout is applied. +If there's no activity after `timeout` milliseconds, the session will be closed. ##### maxSessions @@ -250,12 +223,14 @@ Default: `Infinity` The maximum amount of sessions in total. -##### maxEmptySessions +##### maxFreeSessions Type: `number`
Default: `10` -The maximum amount of empty sessions in total. An empty session is a session with no pending requests. +The maximum amount of free sessions in total. This only applies to sessions with no pending requests. + +**Note:** It is possible that the amount will be exceeded when sessions have at least 1 pending request. ##### maxCachedTlsSessions @@ -264,10 +239,9 @@ Default: `100` The maximum amount of cached TLS sessions. -#### agent.protocol +#### Agent.normalizeOrigin(url) -Type: `string`
-Default: `https:` +Returns a string representing the origin of the URL. #### agent.settings @@ -282,7 +256,7 @@ Returns a string representing normalized options. ```js Agent.normalizeOptions({servername: 'example.com'}); -// => ':::::::::::::::::::::::::::::::::::::' +// => ':example.com' ``` #### agent.getSession(origin, options) @@ -291,18 +265,16 @@ Agent.normalizeOptions({servername: 'example.com'}); Type: `string` `URL` `object` -Origin used to create new session. +An origin used to create new session. ##### [options](https://nodejs.org/api/http2.html#http2_http2_connect_authority_options_listener) Type: `object` -Options used to create new session. +The options used to create new session. Returns a Promise giving free `Http2Session`. If no free sessions are found, a new one is created. -A session is considered free when pending streams count is less than max concurrent streams settings. - #### agent.getSession([origin](#origin), [options](options-1), listener) ##### listener @@ -326,133 +298,172 @@ Returns a Promise giving `Http2Stream`. Returns a new `TLSSocket`. It defaults to `Agent.connect(origin, options)`. -#### agent.closeEmptySessions(count) - -##### count - -Type: `number` -Default: `Number.POSITIVE_INFINITY` +#### agent.closeFreeSessions() -Makes an attempt to close empty sessions. Only sessions with 0 concurrent streams will be closed. +Makes an attempt to close free sessions. Only sessions with 0 concurrent streams will be closed. #### agent.destroy(reason) Destroys **all** sessions. -#### agent.emptySessionCount +#### Event: 'session' -Type: `number` +```js +agent.on('session', session => { + // A new session has been created by the Agent. +}); +``` -A number of empty sessions. +## Proxy support -#### agent.pendingSessionCount +An example of a full-featured proxy server can be found [here](examples/proxy/server.js). It supports **mirroring, custom authorities and the CONNECT protocol**. -Type: `number` +### Mirroring -A number of pending sessions. +To mirror another server we need to use only [`http2-proxy`](https://github.com/nxtedition/node-http2-proxy). We don't need the CONNECT protocol or custom authorities. -#### agent.sessionCount +To see the result, just navigate to the server's address. -Type: `number` +### HTTP/1 over HTTP/2 -A number of all sessions held by the Agent. +Since we don't care about mirroring, the server needs to support the CONNECT protocol in this case. -#### Event: 'session' +The client looks like this: ```js -agent.on('session', session => { - // A new session has been created by the Agent. -}); -``` - -## Proxy support +const https = require('https'); +const http2 = require('http2'); -Currently `http2-wrapper` provides support for these proxies: +const session = http2.connect('https://localhost:8000', { + // For demo purposes only! + rejectUnauthorized: false +}); -- `HttpOverHttp2` -- `HttpsOverHttp2` -- `Http2OverHttp2` -- `Http2OverHttp` -- `Http2OverHttps` +session.ref(); -Any of the above can be accessed via `http2wrapper.proxies`. Check out the [`examples/proxies`](examples/proxies) directory to learn more. +https.request('https://httpbin.org/anything', { + createConnection: options => { + return session.request({ + ':method': 'CONNECT', + ':authority': `${options.host}:${options.port}` + }); + } +}, response => { + console.log('statusCode:', response.statusCode); + console.log('headers:', response.headers); -**Note:** If you use the `http2.auto` function, the real IP address will leak. `http2wrapper` is not aware of the context. It will create a connection to the end server using your real IP address to get the ALPN protocol. Then it will create another connection using proxy. To migitate this, you need to pass a custom `resolveProtocol` function as an option: + const body = []; + response.on('data', chunk => { + body.push(chunk); + }); + response.on('end', () => { + console.log('body:', Buffer.concat(body).toString()); -```js -const resolveAlpnProxy = new URL('https://username:password@localhost:8000'); -const connect = async (options, callback) => new Promise((resolve, reject) => { - const host = `${options.host}:${options.port}`; - - (async () => { - try { - const request = await http2.auto(resolveAlpnProxy, { - method: 'CONNECT', - headers: { - host - }, - path: host, - - // For demo purposes only! - rejectUnauthorized: false, - }); + session.unref(); + }); +}).end(); +``` - request.end(); +### HTTP/2 over HTTP/2 - request.once('error', reject); +It's a tricky one! We cannot create an HTTP/2 session on top of an HTTP/2 stream. But... we can still specify the `:authority` header, no need to use the CONNECT protocol here. - request.once('connect', (response, socket, head) => { - if (head.length > 0) { - reject(new Error(`Unexpected data before CONNECT tunnel: ${head.length} bytes`)); +The client looks like this: - socket.destroy(); - return; - } +```js +const http2 = require('../../source'); +const {Agent} = http2; - const tlsSocket = tls.connect({ - ...options, - socket - }, callback); +class ProxyAgent extends Agent { + constructor(url, options) { + super(options); - resolve(tlsSocket); - }); - } catch (error) { - reject(error); - } - })(); -}); + this.origin = url; + } -// This is required to prevent leaking real IP address on ALPN negotiation -const resolveProtocol = http2.auto.createResolveProtocol(new Map(), new Map(), connect); + request(origin, sessionOptions, headers, streamOptions) { + return super.request(this.origin, sessionOptions, { + ...headers, + ':authority': (new URL(origin)).host + }, streamOptions); + } +} -const request = await http2.auto('https://httpbin.org/anything', { - agent: {…}, - resolveProtocol +const request = http2.request({ + hostname: 'httpbin.org', + protocol: 'https:', + path: '/anything', + agent: new ProxyAgent('https://localhost:8000'), + // For demo purposes only! + rejectUnauthorized: false }, response => { - // Read the response here + console.log('statusCode:', response.statusCode); + console.log('headers:', response.headers); + + const body = []; + response.on('data', chunk => { + body.push(chunk); + }); + response.on('end', () => { + console.log('body:', Buffer.concat(body).toString()); + }); }); +request.on('error', console.error); + request.end(); ``` -See [`unknown-over-unknown.js`](examples/proxies/unknown-over-unknown.js) to learn more. +## Notes + + - If you're interested in [WebSockets over HTTP/2](https://tools.ietf.org/html/rfc8441), then [check out this discussion](https://github.com/websockets/ws/issues/1458). + - [HTTP/2 sockets cannot be malformed](https://github.com/nodejs/node/blob/cc8250fab86486632fdeb63892be735d7628cd13/lib/internal/http2/core.js#L725), therefore modifying the socket will have no effect. + - You can make [a custom Agent](examples/push-stream/index.js) to support push streams. -## Mirroring another server +## Benchmarks -See [`examples/proxies/mirror.js`](examples/proxies/mirror.js) for an example. +CPU: Intel i7-7700k (governor: performance)
+Server: H2O v2.2.5 [`h2o.conf`](h2o.conf)
+Node: v14.5.0 +Linux: 5.6.18-156.current + +`auto` means `http2wrapper.auto`. + +``` +http2-wrapper x 12,181 ops/sec ±3.39% (75 runs sampled) +http2-wrapper - preconfigured session x 13,140 ops/sec ±2.51% (79 runs sampled) +http2-wrapper - auto x 11,412 ops/sec ±2.55% (78 runs sampled) +http2 x 16,050 ops/sec ±1.39% (86 runs sampled) +https - auto - keepalive x 12,288 ops/sec ±2.69% (79 runs sampled) +https - keepalive x 12,155 ops/sec ±3.32% (78 runs sampled) +https x 1,604 ops/sec ±2.03% (77 runs sampled) +http x 6,041 ops/sec ±3.82% (76 runs sampled) +Fastest is http2 +``` -## [WebSockets over HTTP/2](https://tools.ietf.org/html/rfc8441) +`http2-wrapper`: +- 32% **less** performant than `http2` +- as performant as `https - keepalive` +- 100% **more** performant than `http` -See [`examples/ws`](examples/ws) for an example. +`http2-wrapper - preconfigured session`: +- 22% **less** performant than `http2` +- 8% **more** performant than `https - keepalive` +- 118% **more** performant than `http` -## Push streams +`http2-wrapper - auto`: +- 41% **less** performant than `http2` +- 8% **less** performant than `https - keepalive` +- 89% **more** performant than `http` -See [`examples/push-stream`](examples/push-stream) for an example. +`https - auto - keepalive`: +- 31% **less** performant than `http2` +- as performant as `https - keepalive` +- 103% **more** performant than `http` ## Related -- [`got`](https://github.com/sindresorhus/got) - Simplified HTTP requests -- [`http2-proxy`](https://github.com/nxtedition/node-http2-proxy) - A simple http/2 & http/1.1 spec compliant proxy helper for Node. + - [`got`](https://github.com/sindresorhus/got) - Simplified HTTP requests ## License diff --git a/setup-pandoc/node_modules/http2-wrapper/index.d.ts b/setup-pandoc/node_modules/http2-wrapper/index.d.ts deleted file mode 100644 index 474e01998..000000000 --- a/setup-pandoc/node_modules/http2-wrapper/index.d.ts +++ /dev/null @@ -1,141 +0,0 @@ -// See https://github.com/facebook/jest/issues/2549 -// eslint-disable-next-line node/prefer-global/url -import {URL} from 'url'; -import {EventEmitter} from 'events'; -import tls = require('tls'); -import http = require('http'); -import https = require('https'); -import http2 = require('http2'); - -// Note: do not convert this to import from. -import QuickLRU = require('quick-lru'); - -export interface RequestOptions extends Omit { - tlsSession?: tls.ConnectionOptions['session']; - h2session?: http2.ClientHttp2Session; - agent?: Agent | false; - - // Required because @types/node is missing types - ALPNProtocols?: string[]; -} - -export interface AutoRequestOptions extends Omit { - agent?: { - http?: http.Agent | false; - https?: https.Agent | false; - http2?: Agent | false; - }; - resolveProtocol?: ResolveProtocolFunction; -} - -export interface EntryFunction { - (): Promise; - - completed: boolean; - destroyed: boolean; - listeners: PromiseListeners; -} - -export interface AgentOptions { - timeout?: number; - maxSessions?: number; - maxEmptySessions?: number; - maxCachedTlsSessions?: number; -} - -export interface PromiseListeners { - resolve: (value: unknown) => void; - reject: (error: Error) => void; -} - -export class Agent extends EventEmitter { - sessions: Record; - queue: Record>; - - timeout: number; - maxSessions: number; - maxEmptySessions: number; - protocol: string; - settings: http2.Settings; - - tlsSessionCache: QuickLRU; - - emptySessionCount: number; - pendingSessionCount: number; - sessionCount: number; - - constructor(options?: AgentOptions); - - static connect(origin: URL, options: http2.SecureClientSessionOptions): tls.TLSSocket; - - normalizeOptions(options: http2.ClientSessionRequestOptions): string; - - getSession(origin: string | URL, options?: http2.SecureClientSessionOptions, listeners?: PromiseListeners): Promise; - request(origin: string | URL, options?: http2.SecureClientSessionOptions, headers?: http2.OutgoingHttpHeaders, streamOptions?: http2.ClientSessionRequestOptions): Promise; - - createConnection(origin: URL, options: http2.SecureClientSessionOptions): Promise; - - closeEmptySessions(count?: number): void; - destroy(reason?: Error): void; -} - -export interface ProxyOptions { - headers?: http2.OutgoingHttpHeaders; - raw?: boolean; - url: URL | string; -} - -export namespace proxies { - class HttpOverHttp2 extends http.Agent { - constructor(options: http.AgentOptions & {proxyOptions: ProxyOptions}); - } - - class HttpsOverHttp2 extends https.Agent { - constructor(options: https.AgentOptions & {proxyOptions: ProxyOptions}); - } - - class Http2OverHttp2 extends Agent { - constructor(options: AgentOptions & {proxyOptions: ProxyOptions}); - } - - class Http2OverHttp extends Agent { - constructor(options: AgentOptions & {proxyOptions: ProxyOptions}); - } - - class Http2OverHttps extends Agent { - constructor(options: AgentOptions & {proxyOptions: ProxyOptions}); - } -} - -export type RequestFunction = - ((url: string | URL, options?: O, callback?: (response: http.IncomingMessage) => void) => T) & - ((url: string | URL, callback?: (response: http.IncomingMessage) => void) => T) & - ((options: O, callback?: (response: http.IncomingMessage) => void) => T); - -export const globalAgent: Agent; - -export type ResolveProtocolResult = { - alpnProtocol: string; - socket?: tls.TLSSocket; - timeout?: boolean; -}; -export type ResolveProtocolFunction = (options: AutoRequestOptions) => Promise; - -type Promisable = T | Promise; - -export type ResolveProtocolConnectFunction = (options: tls.ConnectionOptions, callback: () => void) => Promisable; - -export const request: RequestFunction; -export const get: RequestFunction; -export const auto: RequestFunction, AutoRequestOptions> & { - protocolCache: QuickLRU; - resolveProtocol: ResolveProtocolFunction; - createResolveProtocol: (cache: Map, queue: Map>, connect?: ResolveProtocolConnectFunction) => ResolveProtocolFunction; -}; - -export { - ClientRequest, - IncomingMessage -} from 'http'; - -export * from 'http2'; diff --git a/setup-pandoc/node_modules/http2-wrapper/package.json b/setup-pandoc/node_modules/http2-wrapper/package.json index 5c9c4a56a..d47894ffe 100644 --- a/setup-pandoc/node_modules/http2-wrapper/package.json +++ b/setup-pandoc/node_modules/http2-wrapper/package.json @@ -1,18 +1,16 @@ { "name": "http2-wrapper", - "version": "2.2.1", + "version": "1.0.3", "description": "HTTP2 client, just with the familiar `https` API", "main": "source", - "types": "index.d.ts", "engines": { "node": ">=10.19.0" }, "scripts": { - "test": "xo && nyc --reporter=lcovonly --reporter=text --reporter=html ava && tsd" + "test": "xo && nyc --reporter=lcovonly --reporter=text --reporter=html ava" }, "files": [ - "source", - "index.d.ts" + "source" ], "keywords": [ "http2", @@ -32,50 +30,25 @@ "homepage": "https://github.com/szmarczak/http2-wrapper#readme", "dependencies": { "quick-lru": "^5.1.1", - "resolve-alpn": "^1.2.0" + "resolve-alpn": "^1.0.0" }, "devDependencies": { - "@sindresorhus/is": "^4.0.1", - "ava": "^3.15.0", + "@sindresorhus/is": "^3.0.0", + "ava": "^3.10.1", "benchmark": "^2.1.4", - "get-stream": "^6.0.1", - "got": "^11.8.2", - "http2-proxy": "^5.0.53", - "https-proxy-agent": "^5.0.0", + "get-stream": "^5.1.0", + "got": "^11.5.0", + "http2-proxy": "^5.0.51", "lolex": "^6.0.0", - "many-keys-map": "^1.0.3", + "many-keys-map": "^1.0.2", "nyc": "^15.1.0", "p-event": "^4.2.0", - "tempy": "^1.0.1", + "tempy": "^0.5.0", "to-readable-stream": "^2.1.0", - "tsd": "^0.17.0", - "websocket-stream": "^5.5.2", - "ws": "^7.5.3", - "xo": "0.39.1" + "tsd": "^0.13.1", + "xo": "^0.32.1" }, "ava": { - "timeout": "10s" - }, - "nyc": { - "include": [ - "source" - ] - }, - "xo": { - "rules": { - "unicorn/no-for-loop": "off", - "unicorn/prefer-module": "off", - "comma-dangle": "off", - "@typescript-eslint/comma-dangle": "off", - "quotes": [ - "error", - "single", - { - "avoidEscape": true, - "allowTemplateLiterals": true - } - ], - "operator-linebreak": ["error", "before"] - } + "timeout": "2m" } } diff --git a/setup-pandoc/node_modules/http2-wrapper/source/agent.js b/setup-pandoc/node_modules/http2-wrapper/source/agent.js index 922d202ba..b2b1cff89 100644 --- a/setup-pandoc/node_modules/http2-wrapper/source/agent.js +++ b/setup-pandoc/node_modules/http2-wrapper/source/agent.js @@ -1,70 +1,47 @@ 'use strict'; -// See https://github.com/facebook/jest/issues/2549 -// eslint-disable-next-line node/prefer-global/url -const {URL} = require('url'); const EventEmitter = require('events'); const tls = require('tls'); const http2 = require('http2'); const QuickLRU = require('quick-lru'); -const delayAsyncDestroy = require('./utils/delay-async-destroy.js'); -const kCurrentStreamCount = Symbol('currentStreamCount'); +const kCurrentStreamsCount = Symbol('currentStreamsCount'); const kRequest = Symbol('request'); const kOriginSet = Symbol('cachedOriginSet'); const kGracefullyClosing = Symbol('gracefullyClosing'); -const kLength = Symbol('length'); const nameKeys = [ - // Not an Agent option actually - 'createConnection', - // `http2.connect()` options 'maxDeflateDynamicTableSize', - 'maxSettings', 'maxSessionMemory', 'maxHeaderListPairs', 'maxOutstandingPings', 'maxReservedRemoteStreams', 'maxSendHeaderBlockLength', 'paddingStrategy', - 'peerMaxConcurrentStreams', - 'settings', - // `tls.connect()` source options - 'family', + // `tls.connect()` options 'localAddress', + 'path', 'rejectUnauthorized', - - // `tls.connect()` secure context options - 'pskCallback', 'minDHSize', - // `tls.connect()` destination options - // - `servername` is automatically validated, skip it - // - `host` and `port` just describe the destination server, - 'path', - 'socket', - // `tls.createSecureContext()` options 'ca', 'cert', - 'sigalgs', - 'ciphers', 'clientCertEngine', - 'crl', - 'dhparam', - 'ecdhCurve', - 'honorCipherOrder', + 'ciphers', 'key', - 'privateKeyEngine', - 'privateKeyIdentifier', - 'maxVersion', - 'minVersion', 'pfx', - 'secureOptions', + 'servername', + 'minVersion', + 'maxVersion', 'secureProtocol', - 'sessionIdContext', - 'ticketKeys' + 'crl', + 'honorCipherOrder', + 'ecdhCurve', + 'dhparam', + 'secureOptions', + 'sessionIdContext' ]; const getSortedIndex = (array, value, compare) => { @@ -74,7 +51,9 @@ const getSortedIndex = (array, value, compare) => { while (low < high) { const mid = (low + high) >>> 1; + /* istanbul ignore next */ if (compare(array[mid], value)) { + // This never gets called because we use descending sort. Better to have this anyway. low = mid + 1; } else { high = mid; @@ -84,28 +63,25 @@ const getSortedIndex = (array, value, compare) => { return low; }; -const compareSessions = (a, b) => a.remoteSettings.maxConcurrentStreams > b.remoteSettings.maxConcurrentStreams; +const compareSessions = (a, b) => { + return a.remoteSettings.maxConcurrentStreams > b.remoteSettings.maxConcurrentStreams; +}; // See https://tools.ietf.org/html/rfc8336 const closeCoveredSessions = (where, session) => { // Clients SHOULD NOT emit new requests on any connection whose Origin // Set is a proper subset of another connection's Origin Set, and they // SHOULD close it once all outstanding requests are satisfied. - for (let index = 0; index < where.length; index++) { - const coveredSession = where[index]; - + for (const coveredSession of where) { if ( - // Unfortunately `.every()` returns true for an empty array - coveredSession[kOriginSet].length > 0 - // The set is a proper subset when its length is less than the other set. - && coveredSession[kOriginSet].length < session[kOriginSet].length + coveredSession[kOriginSet].length < session[kOriginSet].length && // And the other set includes all elements of the subset. - && coveredSession[kOriginSet].every(origin => session[kOriginSet].includes(origin)) + coveredSession[kOriginSet].every(origin => session[kOriginSet].includes(origin)) && // Makes sure that the session can handle all requests from the covered session. - && (coveredSession[kCurrentStreamCount] + session[kCurrentStreamCount]) <= session.remoteSettings.maxConcurrentStreams + coveredSession[kCurrentStreamsCount] + session[kCurrentStreamsCount] <= session.remoteSettings.maxConcurrentStreams ) { // This allows pending requests to finish and prevents making new requests. gracefullyClose(coveredSession); @@ -115,45 +91,62 @@ const closeCoveredSessions = (where, session) => { // This is basically inverted `closeCoveredSessions(...)`. const closeSessionIfCovered = (where, coveredSession) => { - for (let index = 0; index < where.length; index++) { - const session = where[index]; - + for (const session of where) { if ( - coveredSession[kOriginSet].length > 0 - && coveredSession[kOriginSet].length < session[kOriginSet].length - && coveredSession[kOriginSet].every(origin => session[kOriginSet].includes(origin)) - && (coveredSession[kCurrentStreamCount] + session[kCurrentStreamCount]) <= session.remoteSettings.maxConcurrentStreams + coveredSession[kOriginSet].length < session[kOriginSet].length && + coveredSession[kOriginSet].every(origin => session[kOriginSet].includes(origin)) && + coveredSession[kCurrentStreamsCount] + session[kCurrentStreamsCount] <= session.remoteSettings.maxConcurrentStreams ) { gracefullyClose(coveredSession); + } + } +}; + +const getSessions = ({agent, isFree}) => { + const result = {}; + + // eslint-disable-next-line guard-for-in + for (const normalizedOptions in agent.sessions) { + const sessions = agent.sessions[normalizedOptions]; - return true; + const filtered = sessions.filter(session => { + const result = session[Agent.kCurrentStreamsCount] < session.remoteSettings.maxConcurrentStreams; + + return isFree ? result : !result; + }); + + if (filtered.length !== 0) { + result[normalizedOptions] = filtered; } } - return false; + return result; }; const gracefullyClose = session => { session[kGracefullyClosing] = true; - if (session[kCurrentStreamCount] === 0) { + if (session[kCurrentStreamsCount] === 0) { session.close(); } }; class Agent extends EventEmitter { - constructor({timeout = 0, maxSessions = Number.POSITIVE_INFINITY, maxEmptySessions = 10, maxCachedTlsSessions = 100} = {}) { + constructor({timeout = 60000, maxSessions = Infinity, maxFreeSessions = 10, maxCachedTlsSessions = 100} = {}) { super(); + // A session is considered busy when its current streams count + // is equal to or greater than the `maxConcurrentStreams` value. + + // A session is considered free when its current streams count + // is less than the `maxConcurrentStreams` value. + // SESSIONS[NORMALIZED_OPTIONS] = []; this.sessions = {}; // The queue for creating new sessions. It looks like this: // QUEUE[NORMALIZED_OPTIONS][NORMALIZED_ORIGIN] = ENTRY_FUNCTION // - // It's faster when there are many origins. If there's only one, then QUEUE[`${options}:${origin}`] is faster. - // I guess object creation / deletion is causing the slowdown. - // // The entry function has `listeners`, `completed` and `destroyed` properties. // `listeners` is an array of objects containing `resolve` and `reject` functions. // `completed` is a boolean. It's set to true after ENTRY_FUNCTION is executed. @@ -166,90 +159,69 @@ class Agent extends EventEmitter { // Max sessions in total this.maxSessions = maxSessions; - // Max empty sessions in total - this.maxEmptySessions = maxEmptySessions; + // Max free sessions in total + // TODO: decreasing `maxFreeSessions` should close some sessions + this.maxFreeSessions = maxFreeSessions; - this._emptySessionCount = 0; - this._sessionCount = 0; + this._freeSessionsCount = 0; + this._sessionsCount = 0; // We don't support push streams by default. this.settings = { - enablePush: false, - initialWindowSize: 1024 * 1024 * 32 // 32MB, see https://github.com/nodejs/node/issues/38426 + enablePush: false }; // Reusing TLS sessions increases performance. this.tlsSessionCache = new QuickLRU({maxSize: maxCachedTlsSessions}); } - get protocol() { - return 'https:'; + static normalizeOrigin(url, servername) { + if (typeof url === 'string') { + url = new URL(url); + } + + if (servername && url.hostname !== servername) { + url.hostname = servername; + } + + return url.origin; } normalizeOptions(options) { let normalized = ''; - for (let index = 0; index < nameKeys.length; index++) { - const key = nameKeys[index]; - - normalized += ':'; - - if (options && options[key] !== undefined) { - normalized += options[key]; + if (options) { + for (const key of nameKeys) { + if (options[key]) { + normalized += `:${options[key]}`; + } } } return normalized; } - _processQueue() { - if (this._sessionCount >= this.maxSessions) { - this.closeEmptySessions(this.maxSessions - this._sessionCount + 1); + _tryToCreateNewSession(normalizedOptions, normalizedOrigin) { + if (!(normalizedOptions in this.queue) || !(normalizedOrigin in this.queue[normalizedOptions])) { return; } - // eslint-disable-next-line guard-for-in - for (const normalizedOptions in this.queue) { - // eslint-disable-next-line guard-for-in - for (const normalizedOrigin in this.queue[normalizedOptions]) { - const item = this.queue[normalizedOptions][normalizedOrigin]; - - // The entry function can be run only once. - if (!item.completed) { - item.completed = true; - - item(); - } - } - } - } - - _isBetterSession(thisStreamCount, thatStreamCount) { - return thisStreamCount > thatStreamCount; - } - - _accept(session, listeners, normalizedOrigin, options) { - let index = 0; - - while (index < listeners.length && session[kCurrentStreamCount] < session.remoteSettings.maxConcurrentStreams) { - // We assume `resolve(...)` calls `request(...)` *directly*, - // otherwise the session will get overloaded. - listeners[index].resolve(session); - - index++; - } + const item = this.queue[normalizedOptions][normalizedOrigin]; - listeners.splice(0, index); + // The entry function can be run only once. + // BUG: The session may be never created when: + // - the first condition is false AND + // - this function is never called with the same arguments in the future. + if (this._sessionsCount < this.maxSessions && !item.completed) { + item.completed = true; - if (listeners.length > 0) { - this.getSession(normalizedOrigin, options, listeners); - listeners.length = 0; + item(); } } getSession(origin, options, listeners) { return new Promise((resolve, reject) => { - if (Array.isArray(listeners) && listeners.length > 0) { + if (Array.isArray(listeners)) { listeners = [...listeners]; // Resolve the current promise ASAP, we're just moving the listeners. @@ -259,33 +231,17 @@ class Agent extends EventEmitter { listeners = [{resolve, reject}]; } - try { - // Parse origin - if (typeof origin === 'string') { - origin = new URL(origin); - } else if (!(origin instanceof URL)) { - throw new TypeError('The `origin` argument needs to be a string or an URL object'); - } + const normalizedOptions = this.normalizeOptions(options); + const normalizedOrigin = Agent.normalizeOrigin(origin, options && options.servername); - if (options) { - // Validate servername - const {servername} = options; - const {hostname} = origin; - if (servername && hostname !== servername) { - throw new Error(`Origin ${hostname} differs from servername ${servername}`); - } - } - } catch (error) { - for (let index = 0; index < listeners.length; index++) { - listeners[index].reject(error); + if (normalizedOrigin === undefined) { + for (const {reject} of listeners) { + reject(new TypeError('The `origin` argument needs to be a string or an URL object')); } return; } - const normalizedOptions = this.normalizeOptions(options); - const normalizedOrigin = origin.origin; - if (normalizedOptions in this.sessions) { const sessions = this.sessions[normalizedOptions]; @@ -295,55 +251,56 @@ class Agent extends EventEmitter { // We could just do this.sessions[normalizedOptions].find(...) but that isn't optimal. // Additionally, we are looking for session which has biggest current pending streams count. - // - // |------------| |------------| |------------| |------------| - // | Session: A | | Session: B | | Session: C | | Session: D | - // | Pending: 5 |-| Pending: 8 |-| Pending: 9 |-| Pending: 4 | - // | Max: 10 | | Max: 10 | | Max: 9 | | Max: 5 | - // |------------| |------------| |------------| |------------| - // ^ - // | - // pick this one -- - // - for (let index = 0; index < sessions.length; index++) { - const session = sessions[index]; - + for (const session of sessions) { const sessionMaxConcurrentStreams = session.remoteSettings.maxConcurrentStreams; if (sessionMaxConcurrentStreams < maxConcurrentStreams) { break; } - if (!session[kOriginSet].includes(normalizedOrigin)) { - continue; - } + if (session[kOriginSet].includes(normalizedOrigin)) { + const sessionCurrentStreamsCount = session[kCurrentStreamsCount]; + + if ( + sessionCurrentStreamsCount >= sessionMaxConcurrentStreams || + session[kGracefullyClosing] || + // Unfortunately the `close` event isn't called immediately, + // so `session.destroyed` is `true`, but `session.closed` is `false`. + session.destroyed + ) { + continue; + } - const sessionCurrentStreamsCount = session[kCurrentStreamCount]; + // We only need set this once. + if (!optimalSession) { + maxConcurrentStreams = sessionMaxConcurrentStreams; + } - if ( - sessionCurrentStreamsCount >= sessionMaxConcurrentStreams - || session[kGracefullyClosing] - // Unfortunately the `close` event isn't called immediately, - // so `session.destroyed` is `true`, but `session.closed` is `false`. - || session.destroyed - ) { - continue; + // We're looking for the session which has biggest current pending stream count, + // in order to minimalize the amount of active sessions. + if (sessionCurrentStreamsCount > currentStreamsCount) { + optimalSession = session; + currentStreamsCount = sessionCurrentStreamsCount; + } } + } - // We only need set this once. - if (!optimalSession) { - maxConcurrentStreams = sessionMaxConcurrentStreams; - } + if (optimalSession) { + /* istanbul ignore next: safety check */ + if (listeners.length !== 1) { + for (const {reject} of listeners) { + const error = new Error( + `Expected the length of listeners to be 1, got ${listeners.length}.\n` + + 'Please report this to https://github.com/szmarczak/http2-wrapper/' + ); + + reject(error); + } - // Either get the session which has biggest current stream count or the lowest. - if (this._isBetterSession(sessionCurrentStreamsCount, currentStreamsCount)) { - optimalSession = session; - currentStreamsCount = sessionCurrentStreamsCount; + return; } - } - if (optimalSession) { - this._accept(optimalSession, listeners, normalizedOrigin, options); + listeners[0].resolve(optimalSession); return; } } @@ -352,12 +309,14 @@ class Agent extends EventEmitter { if (normalizedOrigin in this.queue[normalizedOptions]) { // There's already an item in the queue, just attach ourselves to it. this.queue[normalizedOptions][normalizedOrigin].listeners.push(...listeners); + + // This shouldn't be executed here. + // See the comment inside _tryToCreateNewSession. + this._tryToCreateNewSession(normalizedOptions, normalizedOrigin); return; } } else { - this.queue[normalizedOptions] = { - [kLength]: 0 - }; + this.queue[normalizedOptions] = {}; } // The entry must be removed from the queue IMMEDIATELY when: @@ -368,58 +327,29 @@ class Agent extends EventEmitter { if (normalizedOptions in this.queue && this.queue[normalizedOptions][normalizedOrigin] === entry) { delete this.queue[normalizedOptions][normalizedOrigin]; - if (--this.queue[normalizedOptions][kLength] === 0) { + if (Object.keys(this.queue[normalizedOptions]).length === 0) { delete this.queue[normalizedOptions]; } } }; // The main logic is here - const entry = async () => { - this._sessionCount++; - + const entry = () => { const name = `${normalizedOrigin}:${normalizedOptions}`; let receivedSettings = false; - let socket; try { - const computedOptions = {...options}; - - if (computedOptions.settings === undefined) { - computedOptions.settings = this.settings; - } - - if (computedOptions.session === undefined) { - computedOptions.session = this.tlsSessionCache.get(name); - } - - const createConnection = computedOptions.createConnection || this.createConnection; - - // A hacky workaround to enable async `createConnection` - socket = await createConnection.call(this, origin, computedOptions); - computedOptions.createConnection = () => socket; - - const session = http2.connect(origin, computedOptions); - session[kCurrentStreamCount] = 0; + const session = http2.connect(origin, { + createConnection: this.createConnection, + settings: this.settings, + session: this.tlsSessionCache.get(name), + ...options + }); + session[kCurrentStreamsCount] = 0; session[kGracefullyClosing] = false; - // Node.js return https://false:443 instead of https://1.1.1.1:443 - const getOriginSet = () => { - const {socket} = session; - - let originSet; - if (socket.servername === false) { - socket.servername = socket.remoteAddress; - originSet = session.originSet; - socket.servername = false; - } else { - originSet = session.originSet; - } - - return originSet; - }; - - const isFree = () => session[kCurrentStreamCount] < session.remoteSettings.maxConcurrentStreams; + const isFree = () => session[kCurrentStreamsCount] < session.remoteSettings.maxConcurrentStreams; + let wasFree = true; session.socket.once('session', tlsSession => { this.tlsSessionCache.set(name, tlsSession); @@ -427,8 +357,8 @@ class Agent extends EventEmitter { session.once('error', error => { // Listeners are empty when the session successfully connected. - for (let index = 0; index < listeners.length; index++) { - listeners[index].reject(error); + for (const {reject} of listeners) { + reject(error); } // The connection got broken, purge the cache. @@ -437,73 +367,68 @@ class Agent extends EventEmitter { session.setTimeout(this.timeout, () => { // Terminates all streams owned by this session. + // TODO: Maybe the streams should have a "Session timed out" error? session.destroy(); }); session.once('close', () => { - this._sessionCount--; - if (receivedSettings) { - // Assumes session `close` is emitted after request `close` - this._emptySessionCount--; + // 1. If it wasn't free then no need to decrease because + // it has been decreased already in session.request(). + // 2. `stream.once('close')` won't increment the count + // because the session is already closed. + if (wasFree) { + this._freeSessionsCount--; + } + + this._sessionsCount--; // This cannot be moved to the stream logic, // because there may be a session that hadn't made a single request. const where = this.sessions[normalizedOptions]; + where.splice(where.indexOf(session), 1); - if (where.length === 1) { + if (where.length === 0) { delete this.sessions[normalizedOptions]; - } else { - where.splice(where.indexOf(session), 1); } } else { // Broken connection - removeFromQueue(); - const error = new Error('Session closed without receiving a SETTINGS frame'); error.code = 'HTTP2WRAPPER_NOSETTINGS'; - for (let index = 0; index < listeners.length; index++) { - listeners[index].reject(error); + for (const {reject} of listeners) { + reject(error); } + + removeFromQueue(); } // There may be another session awaiting. - this._processQueue(); + this._tryToCreateNewSession(normalizedOptions, normalizedOrigin); }); // Iterates over the queue and processes listeners. const processListeners = () => { - const queue = this.queue[normalizedOptions]; - if (!queue) { + if (!(normalizedOptions in this.queue) || !isFree()) { return; } - const originSet = session[kOriginSet]; - - for (let index = 0; index < originSet.length; index++) { - const origin = originSet[index]; - - if (origin in queue) { - const {listeners, completed} = queue[origin]; - - let index = 0; + for (const origin of session[kOriginSet]) { + if (origin in this.queue[normalizedOptions]) { + const {listeners} = this.queue[normalizedOptions][origin]; // Prevents session overloading. - while (index < listeners.length && isFree()) { + while (listeners.length !== 0 && isFree()) { // We assume `resolve(...)` calls `request(...)` *directly*, // otherwise the session will get overloaded. - listeners[index].resolve(session); - - index++; + listeners.shift().resolve(session); } - queue[origin].listeners.splice(0, index); + const where = this.queue[normalizedOptions]; + if (where[origin].listeners.length === 0) { + delete where[origin]; - if (queue[origin].listeners.length === 0 && !completed) { - delete queue[origin]; - - if (--queue[kLength] === 0) { + if (Object.keys(where).length === 0) { delete this.queue[normalizedOptions]; break; } @@ -519,59 +444,39 @@ class Agent extends EventEmitter { // The Origin Set cannot shrink. No need to check if it suddenly became covered by another one. session.on('origin', () => { - session[kOriginSet] = getOriginSet() || []; - session[kGracefullyClosing] = false; - closeSessionIfCovered(this.sessions[normalizedOptions], session); + session[kOriginSet] = session.originSet; - if (session[kGracefullyClosing] || !isFree()) { + if (!isFree()) { + // The session is full. return; } processListeners(); - if (!isFree()) { - return; - } - // Close covered sessions (if possible). closeCoveredSessions(this.sessions[normalizedOptions], session); }); session.once('remoteSettings', () => { + // Fix Node.js bug preventing the process from exiting + session.ref(); + session.unref(); + + this._sessionsCount++; + // The Agent could have been destroyed already. if (entry.destroyed) { const error = new Error('Agent has been destroyed'); - for (let index = 0; index < listeners.length; index++) { - listeners[index].reject(error); + for (const listener of listeners) { + listener.reject(error); } session.destroy(); return; } - // See https://github.com/nodejs/node/issues/38426 - if (session.setLocalWindowSize) { - session.setLocalWindowSize(1024 * 1024 * 4); // 4 MB - } - - session[kOriginSet] = getOriginSet() || []; - - if (session.socket.encrypted) { - const mainOrigin = session[kOriginSet][0]; - if (mainOrigin !== normalizedOrigin) { - const error = new Error(`Requested origin ${normalizedOrigin} does not match server ${mainOrigin}`); - - for (let index = 0; index < listeners.length; index++) { - listeners[index].reject(error); - } - - session.destroy(); - return; - } - } - - removeFromQueue(); + session[kOriginSet] = session.originSet; { const where = this.sessions; @@ -584,28 +489,30 @@ class Agent extends EventEmitter { } } + this._freeSessionsCount += 1; receivedSettings = true; - this._emptySessionCount++; this.emit('session', session); - this._accept(session, listeners, normalizedOrigin, options); - if (session[kCurrentStreamCount] === 0 && this._emptySessionCount > this.maxEmptySessions) { - this.closeEmptySessions(this._emptySessionCount - this.maxEmptySessions); + processListeners(); + removeFromQueue(); + + // TODO: Close last recently used (or least used?) session + if (session[kCurrentStreamsCount] === 0 && this._freeSessionsCount > this.maxFreeSessions) { + session.close(); + } + + // Check if we haven't managed to execute all listeners. + if (listeners.length !== 0) { + // Request for a new session with predefined listeners. + this.getSession(normalizedOrigin, options, listeners); + listeners.length = 0; } // `session.remoteSettings.maxConcurrentStreams` might get increased session.on('remoteSettings', () => { - if (!isFree()) { - return; - } - processListeners(); - if (!isFree()) { - return; - } - // In case the Origin Set changes closeCoveredSessions(this.sessions[normalizedOptions], session); }); @@ -623,31 +530,45 @@ class Agent extends EventEmitter { // The process won't exit until the session is closed or all requests are gone. session.ref(); - if (session[kCurrentStreamCount]++ === 0) { - this._emptySessionCount--; + ++session[kCurrentStreamsCount]; + + if (session[kCurrentStreamsCount] === session.remoteSettings.maxConcurrentStreams) { + this._freeSessionsCount--; } stream.once('close', () => { - if (--session[kCurrentStreamCount] === 0) { - this._emptySessionCount++; - session.unref(); + wasFree = isFree(); - if (this._emptySessionCount > this.maxEmptySessions || session[kGracefullyClosing]) { - session.close(); - return; - } - } + --session[kCurrentStreamsCount]; - if (session.destroyed || session.closed) { - return; - } + if (!session.destroyed && !session.closed) { + closeSessionIfCovered(this.sessions[normalizedOptions], session); + + if (isFree() && !session.closed) { + if (!wasFree) { + this._freeSessionsCount++; + + wasFree = true; + } - if (isFree() && !closeSessionIfCovered(this.sessions[normalizedOptions], session)) { - closeCoveredSessions(this.sessions[normalizedOptions], session); - processListeners(); + const isEmpty = session[kCurrentStreamsCount] === 0; - if (session[kCurrentStreamCount] === 0) { - this._processQueue(); + if (isEmpty) { + session.unref(); + } + + if ( + isEmpty && + ( + this._freeSessionsCount > this.maxFreeSessions || + session[kGracefullyClosing] + ) + ) { + session.close(); + } else { + closeCoveredSessions(this.sessions[normalizedOptions], session); + processListeners(); + } } } }); @@ -655,12 +576,11 @@ class Agent extends EventEmitter { return stream; }; } catch (error) { - removeFromQueue(); - this._sessionCount--; - - for (let index = 0; index < listeners.length; index++) { - listeners[index].reject(error); + for (const listener of listeners) { + listener.reject(error); } + + removeFromQueue(); } }; @@ -669,8 +589,7 @@ class Agent extends EventEmitter { entry.destroyed = false; this.queue[normalizedOptions][normalizedOrigin] = entry; - this.queue[normalizedOptions][kLength]++; - this._processQueue(); + this._tryToCreateNewSession(normalizedOptions, normalizedOrigin); }); } @@ -680,12 +599,7 @@ class Agent extends EventEmitter { reject, resolve: session => { try { - const stream = session.request(headers, streamOptions); - - // Do not throw before `request(...)` has been awaited - delayAsyncDestroy(stream); - - resolve(stream); + resolve(session.request(headers, streamOptions)); } catch (error) { reject(error); } @@ -694,7 +608,7 @@ class Agent extends EventEmitter { }); } - async createConnection(origin, options) { + createConnection(origin, options) { return Agent.connect(origin, options); } @@ -702,92 +616,52 @@ class Agent extends EventEmitter { options.ALPNProtocols = ['h2']; const port = origin.port || 443; - const host = origin.hostname; + const host = origin.hostname || origin.host; if (typeof options.servername === 'undefined') { options.servername = host; } - const socket = tls.connect(port, host, options); - - if (options.socket) { - socket._peername = { - family: undefined, - address: undefined, - port - }; - } - - return socket; + return tls.connect(port, host, options); } - closeEmptySessions(maxCount = Number.POSITIVE_INFINITY) { - let closedCount = 0; - - const {sessions} = this; - - // eslint-disable-next-line guard-for-in - for (const key in sessions) { - const thisSessions = sessions[key]; - - for (let index = 0; index < thisSessions.length; index++) { - const session = thisSessions[index]; - - if (session[kCurrentStreamCount] === 0) { - closedCount++; + closeFreeSessions() { + for (const sessions of Object.values(this.sessions)) { + for (const session of sessions) { + if (session[kCurrentStreamsCount] === 0) { session.close(); - - if (closedCount >= maxCount) { - return closedCount; - } } } } - - return closedCount; } destroy(reason) { - const {sessions, queue} = this; - - // eslint-disable-next-line guard-for-in - for (const key in sessions) { - const thisSessions = sessions[key]; - - for (let index = 0; index < thisSessions.length; index++) { - thisSessions[index].destroy(reason); + for (const sessions of Object.values(this.sessions)) { + for (const session of sessions) { + session.destroy(reason); } } - // eslint-disable-next-line guard-for-in - for (const normalizedOptions in queue) { - const entries = queue[normalizedOptions]; - - // eslint-disable-next-line guard-for-in - for (const normalizedOrigin in entries) { - entries[normalizedOrigin].destroyed = true; + for (const entriesOfAuthority of Object.values(this.queue)) { + for (const entry of Object.values(entriesOfAuthority)) { + entry.destroyed = true; } } // New requests should NOT attach to destroyed sessions this.queue = {}; - this.tlsSessionCache.clear(); - } - - get emptySessionCount() { - return this._emptySessionCount; } - get pendingSessionCount() { - return this._sessionCount - this._emptySessionCount; + get freeSessions() { + return getSessions({agent: this, isFree: true}); } - get sessionCount() { - return this._sessionCount; + get busySessions() { + return getSessions({agent: this, isFree: false}); } } -Agent.kCurrentStreamCount = kCurrentStreamCount; +Agent.kCurrentStreamsCount = kCurrentStreamsCount; Agent.kGracefullyClosing = kGracefullyClosing; module.exports = { diff --git a/setup-pandoc/node_modules/http2-wrapper/source/auto.js b/setup-pandoc/node_modules/http2-wrapper/source/auto.js index 153a202c4..af4e9baed 100644 --- a/setup-pandoc/node_modules/http2-wrapper/source/auto.js +++ b/setup-pandoc/node_modules/http2-wrapper/source/auto.js @@ -1,15 +1,11 @@ 'use strict'; -// See https://github.com/facebook/jest/issues/2549 -// eslint-disable-next-line node/prefer-global/url -const {URL, urlToHttpOptions} = require('url'); const http = require('http'); const https = require('https'); const resolveALPN = require('resolve-alpn'); const QuickLRU = require('quick-lru'); -const {Agent, globalAgent} = require('./agent.js'); -const Http2ClientRequest = require('./client-request.js'); -const calculateServerName = require('./utils/calculate-server-name.js'); -const delayAsyncDestroy = require('./utils/delay-async-destroy.js'); +const Http2ClientRequest = require('./client-request'); +const calculateServerName = require('./utils/calculate-server-name'); +const urlToOptions = require('./utils/url-to-options'); const cache = new QuickLRU({maxSize: 100}); const queue = new Map(); @@ -29,24 +25,10 @@ const installSocket = (agent, socket, options) => { socket.on('close', onClose); - const onTimeout = () => { - const {freeSockets} = agent; - - for (const sockets of Object.values(freeSockets)) { - if (sockets.includes(socket)) { - socket.destroy(); - return; - } - } - }; - - socket.on('timeout', onTimeout); - const onRemove = () => { agent.removeSocket(socket, options); socket.off('close', onClose); socket.off('free', onFree); - socket.off('timeout', onTimeout); socket.off('agentRemove', onRemove); }; @@ -55,65 +37,76 @@ const installSocket = (agent, socket, options) => { agent.emit('free', socket, options); }; -const createResolveProtocol = (cache, queue = new Map(), connect = undefined) => { - return async options => { - const name = `${options.host}:${options.port}:${options.ALPNProtocols.sort()}`; +const resolveProtocol = async options => { + const name = `${options.host}:${options.port}:${options.ALPNProtocols.sort()}`; - if (!cache.has(name)) { - if (queue.has(name)) { - const result = await queue.get(name); - return {alpnProtocol: result.alpnProtocol}; - } + if (!cache.has(name)) { + if (queue.has(name)) { + const result = await queue.get(name); + return result.alpnProtocol; + } + + const {path, agent} = options; + options.path = options.socketPath; - const {path} = options; - options.path = options.socketPath; + const resultPromise = resolveALPN(options); + queue.set(name, resultPromise); - const resultPromise = resolveALPN(options, connect); - queue.set(name, resultPromise); + try { + const {socket, alpnProtocol} = await resultPromise; + cache.set(name, alpnProtocol); - try { - const result = await resultPromise; + options.path = path; - cache.set(name, result.alpnProtocol); - queue.delete(name); + if (alpnProtocol === 'h2') { + // https://github.com/nodejs/node/issues/33343 + socket.destroy(); + } else { + const {globalAgent} = https; + const defaultCreateConnection = https.Agent.prototype.createConnection; - options.path = path; + if (agent) { + if (agent.createConnection === defaultCreateConnection) { + installSocket(agent, socket, options); + } else { + socket.destroy(); + } + } else if (globalAgent.createConnection === defaultCreateConnection) { + installSocket(globalAgent, socket, options); + } else { + socket.destroy(); + } + } - return result; - } catch (error) { - queue.delete(name); + queue.delete(name); - options.path = path; + return alpnProtocol; + } catch (error) { + queue.delete(name); - throw error; - } + throw error; } + } - return {alpnProtocol: cache.get(name)}; - }; + return cache.get(name); }; -const defaultResolveProtocol = createResolveProtocol(cache, queue); - module.exports = async (input, options, callback) => { - if (typeof input === 'string') { - input = urlToHttpOptions(new URL(input)); - } else if (input instanceof URL) { - input = urlToHttpOptions(input); - } else { - input = {...input}; + if (typeof input === 'string' || input instanceof URL) { + input = urlToOptions(new URL(input)); } - if (typeof options === 'function' || options === undefined) { - // (options, callback) + if (typeof options === 'function') { callback = options; - options = input; - } else { - // (input, options, callback) - options = Object.assign(input, options); + options = undefined; } - options.ALPNProtocols = options.ALPNProtocols || ['h2', 'http/1.1']; + options = { + ALPNProtocols: ['h2', 'http/1.1'], + ...input, + ...options, + resolveSocket: true + }; if (!Array.isArray(options.ALPNProtocols) || options.ALPNProtocols.length === 0) { throw new Error('The `ALPNProtocols` option must be an Array with at least one entry'); @@ -124,102 +117,33 @@ module.exports = async (input, options, callback) => { options.host = options.hostname || options.host || 'localhost'; options.session = options.tlsSession; - options.servername = options.servername || calculateServerName((options.headers && options.headers.host) || options.host); + options.servername = options.servername || calculateServerName(options); options.port = options.port || (isHttps ? 443 : 80); options._defaultAgent = isHttps ? https.globalAgent : http.globalAgent; - const resolveProtocol = options.resolveProtocol || defaultResolveProtocol; - - // Note: We don't support `h2session` here - - let {agent} = options; - if (agent !== undefined && agent !== false && agent.constructor.name !== 'Object') { - throw new Error('The `options.agent` can be only an object `http`, `https` or `http2` properties'); - } - - if (isHttps) { - options.resolveSocket = true; + const agents = options.agent; - let {socket, alpnProtocol, timeout} = await resolveProtocol(options); - - if (timeout) { - if (socket) { - socket.destroy(); - } - - const error = new Error(`Timed out resolving ALPN: ${options.timeout} ms`); - error.code = 'ETIMEDOUT'; - error.ms = options.timeout; - - throw error; - } - - // We can't accept custom `createConnection` because the API is different for HTTP/2 - if (socket && options.createConnection) { - socket.destroy(); - socket = undefined; + if (agents) { + if (agents.addRequest) { + throw new Error('The `options.agent` object can contain only `http`, `https` or `http2` properties'); } - delete options.resolveSocket; - - const isHttp2 = alpnProtocol === 'h2'; - - if (agent) { - agent = isHttp2 ? agent.http2 : agent.https; - options.agent = agent; - } - - if (agent === undefined) { - agent = isHttp2 ? globalAgent : https.globalAgent; - } - - if (socket) { - if (agent === false) { - socket.destroy(); - } else { - const defaultCreateConnection = (isHttp2 ? Agent : https.Agent).prototype.createConnection; - - if (agent.createConnection === defaultCreateConnection) { - if (isHttp2) { - options._reuseSocket = socket; - } else { - installSocket(agent, socket, options); - } - } else { - socket.destroy(); - } - } - } - - if (isHttp2) { - return delayAsyncDestroy(new Http2ClientRequest(options, callback)); - } - } else if (agent) { - options.agent = agent.http; + options.agent = agents[isHttps ? 'https' : 'http']; } - // If we're sending HTTP/1.1, handle any explicitly set H2 headers in the options: - if (options.headers) { - options.headers = {...options.headers}; + if (isHttps) { + const protocol = await resolveProtocol(options); - // :authority is equivalent to the HTTP/1.1 host header - if (options.headers[':authority']) { - if (!options.headers.host) { - options.headers.host = options.headers[':authority']; + if (protocol === 'h2') { + if (agents) { + options.agent = agents.http2; } - delete options.headers[':authority']; + return new Http2ClientRequest(options, callback); } - - // Remove other HTTP/2 headers as they have their counterparts in the options - delete options.headers[':method']; - delete options.headers[':scheme']; - delete options.headers[':path']; } - return delayAsyncDestroy(http.request(options, callback)); + return http.request(options, callback); }; module.exports.protocolCache = cache; -module.exports.resolveProtocol = defaultResolveProtocol; -module.exports.createResolveProtocol = createResolveProtocol; diff --git a/setup-pandoc/node_modules/http2-wrapper/source/client-request.js b/setup-pandoc/node_modules/http2-wrapper/source/client-request.js index 2fd226628..b712967f2 100644 --- a/setup-pandoc/node_modules/http2-wrapper/source/client-request.js +++ b/setup-pandoc/node_modules/http2-wrapper/source/client-request.js @@ -1,26 +1,24 @@ 'use strict'; -// See https://github.com/facebook/jest/issues/2549 -// eslint-disable-next-line node/prefer-global/url -const {URL, urlToHttpOptions} = require('url'); const http2 = require('http2'); const {Writable} = require('stream'); -const {Agent, globalAgent} = require('./agent.js'); -const IncomingMessage = require('./incoming-message.js'); -const proxyEvents = require('./utils/proxy-events.js'); +const {Agent, globalAgent} = require('./agent'); +const IncomingMessage = require('./incoming-message'); +const urlToOptions = require('./utils/url-to-options'); +const proxyEvents = require('./utils/proxy-events'); +const isRequestPseudoHeader = require('./utils/is-request-pseudo-header'); const { ERR_INVALID_ARG_TYPE, ERR_INVALID_PROTOCOL, - ERR_HTTP_HEADERS_SENT -} = require('./utils/errors.js'); -const validateHeaderName = require('./utils/validate-header-name.js'); -const validateHeaderValue = require('./utils/validate-header-value.js'); -const proxySocketHandler = require('./utils/proxy-socket-handler.js'); + ERR_HTTP_HEADERS_SENT, + ERR_INVALID_HTTP_TOKEN, + ERR_HTTP_INVALID_HEADER_VALUE, + ERR_INVALID_CHAR +} = require('./utils/errors'); const { HTTP2_HEADER_STATUS, HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, - HTTP2_HEADER_AUTHORITY, HTTP2_METHOD_CONNECT } = http2.constants; @@ -30,66 +28,59 @@ const kSession = Symbol('session'); const kOptions = Symbol('options'); const kFlushedHeaders = Symbol('flushedHeaders'); const kJobs = Symbol('jobs'); -const kPendingAgentPromise = Symbol('pendingAgentPromise'); + +const isValidHttpToken = /^[\^`\-\w!#$%&*+.|~]+$/; +const isInvalidHeaderValue = /[^\t\u0020-\u007E\u0080-\u00FF]/; class ClientRequest extends Writable { constructor(input, options, callback) { super({ - autoDestroy: false, - emitClose: false + autoDestroy: false }); - if (typeof input === 'string') { - input = urlToHttpOptions(new URL(input)); - } else if (input instanceof URL) { - input = urlToHttpOptions(input); - } else { - input = {...input}; + const hasInput = typeof input === 'string' || input instanceof URL; + if (hasInput) { + input = urlToOptions(input instanceof URL ? input : new URL(input)); } if (typeof options === 'function' || options === undefined) { // (options, callback) callback = options; - options = input; + options = hasInput ? input : {...input}; } else { // (input, options, callback) - options = Object.assign(input, options); + options = {...input, ...options}; } if (options.h2session) { this[kSession] = options.h2session; - - if (this[kSession].destroyed) { - throw new Error('The session has been closed already'); - } - - this.protocol = this[kSession].socket.encrypted ? 'https:' : 'http:'; } else if (options.agent === false) { - this.agent = new Agent({maxEmptySessions: 0}); + this.agent = new Agent({maxFreeSessions: 0}); } else if (typeof options.agent === 'undefined' || options.agent === null) { - this.agent = globalAgent; + if (typeof options.createConnection === 'function') { + // This is a workaround - we don't have to create the session on our own. + this.agent = new Agent({maxFreeSessions: 0}); + this.agent.createConnection = options.createConnection; + } else { + this.agent = globalAgent; + } } else if (typeof options.agent.request === 'function') { this.agent = options.agent; } else { - throw new ERR_INVALID_ARG_TYPE('options.agent', ['http2wrapper.Agent-like Object', 'undefined', 'false'], options.agent); + throw new ERR_INVALID_ARG_TYPE('options.agent', ['Agent-like Object', 'undefined', 'false'], options.agent); } - if (this.agent) { - this.protocol = this.agent.protocol; + if (options.protocol && options.protocol !== 'https:') { + throw new ERR_INVALID_PROTOCOL(options.protocol, 'https:'); } - if (options.protocol && options.protocol !== this.protocol) { - throw new ERR_INVALID_PROTOCOL(options.protocol, this.protocol); - } - - if (!options.port) { - options.port = options.defaultPort || (this.agent && this.agent.defaultPort) || 443; - } + const port = options.port || options.defaultPort || (this.agent && this.agent.defaultPort) || 443; + const host = options.hostname || options.host || 'localhost'; - options.host = options.hostname || options.host || 'localhost'; - - // Unused + // Don't enforce the origin via options. It may be changed in an Agent. delete options.hostname; + delete options.host; + delete options.port; const {timeout} = options; options.timeout = undefined; @@ -97,26 +88,19 @@ class ClientRequest extends Writable { this[kHeaders] = Object.create(null); this[kJobs] = []; - this[kPendingAgentPromise] = undefined; - this.socket = null; this.connection = null; this.method = options.method || 'GET'; - - if (!(this.method === 'CONNECT' && (options.path === '/' || options.path === undefined))) { - this.path = options.path; - } + this.path = options.path; this.res = null; this.aborted = false; this.reusedSocket = false; - const {headers} = options; - if (headers) { - // eslint-disable-next-line guard-for-in - for (const header in headers) { - this.setHeader(header, headers[header]); + if (options.headers) { + for (const [header, value] of Object.entries(options.headers)) { + this.setHeader(header, value); } } @@ -130,21 +114,18 @@ class ClientRequest extends Writable { this[kOptions] = options; // Clients that generate HTTP/2 requests directly SHOULD use the :authority pseudo-header field instead of the Host header field. - this[kOrigin] = new URL(`${this.protocol}//${options.servername || options.host}:${options.port}`); - - // A socket is being reused - const reuseSocket = options._reuseSocket; - if (reuseSocket) { - options.createConnection = (...args) => { - if (reuseSocket.destroyed) { - return this.agent.createConnection(...args); - } + if (port === 443) { + this[kOrigin] = `https://${host}`; - return reuseSocket; - }; + if (!(':authority' in this[kHeaders])) { + this[kHeaders][':authority'] = host; + } + } else { + this[kOrigin] = `https://${host}:${port}`; - // eslint-disable-next-line promise/prefer-await-to-then - this.agent.getSession(this[kOrigin], this[kOptions]).catch(() => {}); + if (!(':authority' in this[kHeaders])) { + this[kHeaders][':authority'] = `${host}:${port}`; + } } if (timeout) { @@ -169,27 +150,15 @@ class ClientRequest extends Writable { } get path() { - const header = this.method === 'CONNECT' ? HTTP2_HEADER_AUTHORITY : HTTP2_HEADER_PATH; - - return this[kHeaders][header]; + return this[kHeaders][HTTP2_HEADER_PATH]; } set path(value) { if (value) { - const header = this.method === 'CONNECT' ? HTTP2_HEADER_AUTHORITY : HTTP2_HEADER_PATH; - - this[kHeaders][header] = value; + this[kHeaders][HTTP2_HEADER_PATH] = value; } } - get host() { - return this[kOrigin].hostname; - } - - set host(_value) { - // Do nothing as this is read only. - } - get _mustNotHaveABody() { return this.method === 'GET' || this.method === 'HEAD' || this.method === 'DELETE'; } @@ -213,11 +182,15 @@ class ClientRequest extends Writable { } _final(callback) { + if (this.destroyed) { + return; + } + this.flushHeaders(); const callEnd = () => { - // For GET, HEAD and DELETE and CONNECT - if (this._mustNotHaveABody || this.method === 'CONNECT') { + // For GET, HEAD and DELETE + if (this._mustNotHaveABody) { callback(); return; } @@ -246,25 +219,13 @@ class ClientRequest extends Writable { this.destroy(); } - async _destroy(error, callback) { + _destroy(error, callback) { if (this.res) { this.res._dump(); } if (this._request) { this._request.destroy(); - } else { - process.nextTick(() => { - this.emit('close'); - }); - } - - try { - await this[kPendingAgentPromise]; - } catch (internalError) { - if (this.aborted) { - error = internalError; - } } callback(error); @@ -290,45 +251,46 @@ class ClientRequest extends Writable { // Forwards `timeout`, `continue`, `close` and `error` events to this instance. if (!isConnectMethod) { - // TODO: Should we proxy `close` here? - proxyEvents(stream, this, ['timeout', 'continue']); + proxyEvents(stream, this, ['timeout', 'continue', 'close', 'error']); } - stream.once('error', error => { - this.destroy(error); - }); - - stream.once('aborted', () => { - const {res} = this; - if (res) { - res.aborted = true; - res.emit('aborted'); - res.destroy(); - } else { - this.destroy(new Error('The server aborted the HTTP/2 stream')); - } - }); + // Wait for the `finish` event. We don't want to emit the `response` event + // before `request.end()` is called. + const waitForEnd = fn => { + return (...args) => { + if (!this.writable && !this.destroyed) { + fn(...args); + } else { + this.once('finish', () => { + fn(...args); + }); + } + }; + }; - const onResponse = (headers, flags, rawHeaders) => { + // This event tells we are ready to listen for the data. + stream.once('response', waitForEnd((headers, flags, rawHeaders) => { // If we were to emit raw request stream, it would be as fast as the native approach. // Note that wrapping the raw stream in a Proxy instance won't improve the performance (already tested it). const response = new IncomingMessage(this.socket, stream.readableHighWaterMark); this.res = response; - // Undocumented, but it is used by `cacheable-request` - response.url = `${this[kOrigin].origin}${this.path}`; - response.req = this; response.statusCode = headers[HTTP2_HEADER_STATUS]; response.headers = headers; response.rawHeaders = rawHeaders; response.once('end', () => { - response.complete = true; + if (this.aborted) { + response.aborted = true; + response.emit('aborted'); + } else { + response.complete = true; - // Has no effect, just be consistent with the Node.js behavior - response.socket = null; - response.connection = null; + // Has no effect, just be consistent with the Node.js behavior + response.socket = null; + response.connection = null; + } }); if (isConnectMethod) { @@ -351,9 +313,7 @@ class ClientRequest extends Writable { }); stream.once('end', () => { - if (!this.aborted) { - response.push(null); - } + response.push(null); }); if (!this.emit('response', response)) { @@ -361,123 +321,50 @@ class ClientRequest extends Writable { response._dump(); } } - }; - - // This event tells we are ready to listen for the data. - stream.once('response', onResponse); + })); // Emits `information` event - stream.once('headers', headers => this.emit('information', {statusCode: headers[HTTP2_HEADER_STATUS]})); + stream.once('headers', waitForEnd( + headers => this.emit('information', {statusCode: headers[HTTP2_HEADER_STATUS]}) + )); - stream.once('trailers', (trailers, flags, rawTrailers) => { + stream.once('trailers', waitForEnd((trailers, flags, rawTrailers) => { const {res} = this; - // https://github.com/nodejs/node/issues/41251 - if (res === null) { - onResponse(trailers, flags, rawTrailers); - return; - } - // Assigns trailers to the response object. res.trailers = trailers; res.rawTrailers = rawTrailers; - }); - - stream.once('close', () => { - const {aborted, res} = this; - if (res) { - if (aborted) { - res.aborted = true; - res.emit('aborted'); - res.destroy(); - } + })); - const finish = () => { - res.emit('close'); - - this.destroy(); - this.emit('close'); - }; - - if (res.readable) { - res.once('end', finish); - } else { - finish(); - } - - return; - } - - if (!this.destroyed) { - this.destroy(new Error('The HTTP/2 stream has been early terminated')); - this.emit('close'); - return; - } - - this.destroy(); - this.emit('close'); - }); - - this.socket = new Proxy(stream, proxySocketHandler); + const {socket} = stream.session; + this.socket = socket; + this.connection = socket; for (const job of this[kJobs]) { job(); } - this[kJobs].length = 0; - this.emit('socket', this.socket); }; - if (!(HTTP2_HEADER_AUTHORITY in this[kHeaders]) && !isConnectMethod) { - this[kHeaders][HTTP2_HEADER_AUTHORITY] = this[kOrigin].host; - } - // Makes a HTTP2 request if (this[kSession]) { try { onStream(this[kSession].request(this[kHeaders])); } catch (error) { - this.destroy(error); + this.emit('error', error); } } else { this.reusedSocket = true; try { - const promise = this.agent.request(this[kOrigin], this[kOptions], this[kHeaders]); - this[kPendingAgentPromise] = promise; - - onStream(await promise); - - this[kPendingAgentPromise] = false; + onStream(await this.agent.request(this[kOrigin], this[kOptions], this[kHeaders])); } catch (error) { - this[kPendingAgentPromise] = false; - - this.destroy(error); + this.emit('error', error); } } } - get connection() { - return this.socket; - } - - set connection(value) { - this.socket = value; - } - - getHeaderNames() { - return Object.keys(this[kHeaders]); - } - - hasHeader(name) { - if (typeof name !== 'string') { - throw new ERR_INVALID_ARG_TYPE('name', 'string', name); - } - - return Boolean(this[kHeaders][name.toLowerCase()]); - } - getHeader(name) { if (typeof name !== 'string') { throw new ERR_INVALID_ARG_TYPE('name', 'string', name); @@ -507,24 +394,19 @@ class ClientRequest extends Writable { throw new ERR_HTTP_HEADERS_SENT('set'); } - validateHeaderName(name); - validateHeaderValue(name, value); - - const lowercased = name.toLowerCase(); - - if (lowercased === 'connection') { - if (value.toLowerCase() === 'keep-alive') { - return; - } + if (typeof name !== 'string' || (!isValidHttpToken.test(name) && !isRequestPseudoHeader(name))) { + throw new ERR_INVALID_HTTP_TOKEN('Header name', name); + } - throw new Error(`Invalid 'connection' header: ${value}`); + if (typeof value === 'undefined') { + throw new ERR_HTTP_INVALID_HEADER_VALUE(value, name); } - if (lowercased === 'host' && this.method === 'CONNECT') { - this[kHeaders][HTTP2_HEADER_AUTHORITY] = value; - } else { - this[kHeaders][lowercased] = value; + if (isInvalidHeaderValue.test(value)) { + throw new ERR_INVALID_CHAR('header content', name); } + + this[kHeaders][name.toLowerCase()] = value; } setNoDelay() { diff --git a/setup-pandoc/node_modules/http2-wrapper/source/incoming-message.js b/setup-pandoc/node_modules/http2-wrapper/source/incoming-message.js index 780e0510e..7d5c0d378 100644 --- a/setup-pandoc/node_modules/http2-wrapper/source/incoming-message.js +++ b/setup-pandoc/node_modules/http2-wrapper/source/incoming-message.js @@ -4,9 +4,8 @@ const {Readable} = require('stream'); class IncomingMessage extends Readable { constructor(socket, highWaterMark) { super({ - emitClose: false, - autoDestroy: true, - highWaterMark + highWaterMark, + autoDestroy: false }); this.statusCode = null; @@ -26,26 +25,12 @@ class IncomingMessage extends Readable { this.rawTrailers = []; this.socket = socket; + this.connection = socket; this._dumped = false; } - get connection() { - return this.socket; - } - - set connection(value) { - this.socket = value; - } - - _destroy(error, callback) { - if (!this.readableEnded) { - this.aborted = true; - } - - // See https://github.com/nodejs/node/issues/35303 - callback(); - + _destroy(error) { this.req._request.destroy(error); } diff --git a/setup-pandoc/node_modules/http2-wrapper/source/index.js b/setup-pandoc/node_modules/http2-wrapper/source/index.js index 7a2a49c93..fb83349da 100644 --- a/setup-pandoc/node_modules/http2-wrapper/source/index.js +++ b/setup-pandoc/node_modules/http2-wrapper/source/index.js @@ -1,25 +1,13 @@ 'use strict'; const http2 = require('http2'); -const { - Agent, - globalAgent -} = require('./agent.js'); -const ClientRequest = require('./client-request.js'); -const IncomingMessage = require('./incoming-message.js'); -const auto = require('./auto.js'); -const { - HttpOverHttp2, - HttpsOverHttp2 -} = require('./proxies/h1-over-h2.js'); -const Http2OverHttp2 = require('./proxies/h2-over-h2.js'); -const { - Http2OverHttp, - Http2OverHttps -} = require('./proxies/h2-over-h1.js'); -const validateHeaderName = require('./utils/validate-header-name.js'); -const validateHeaderValue = require('./utils/validate-header-value.js'); +const agent = require('./agent'); +const ClientRequest = require('./client-request'); +const IncomingMessage = require('./incoming-message'); +const auto = require('./auto'); -const request = (url, options, callback) => new ClientRequest(url, options, callback); +const request = (url, options, callback) => { + return new ClientRequest(url, options, callback); +}; const get = (url, options, callback) => { // eslint-disable-next-line unicorn/prevent-abbreviations @@ -33,18 +21,8 @@ module.exports = { ...http2, ClientRequest, IncomingMessage, - Agent, - globalAgent, + ...agent, request, get, - auto, - proxies: { - HttpOverHttp2, - HttpsOverHttp2, - Http2OverHttp2, - Http2OverHttp, - Http2OverHttps - }, - validateHeaderName, - validateHeaderValue + auto }; diff --git a/setup-pandoc/node_modules/http2-wrapper/source/proxies/get-auth-headers.js b/setup-pandoc/node_modules/http2-wrapper/source/proxies/get-auth-headers.js deleted file mode 100644 index 364a858a7..000000000 --- a/setup-pandoc/node_modules/http2-wrapper/source/proxies/get-auth-headers.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict'; - -module.exports = self => { - const {username, password} = self.proxyOptions.url; - - if (username || password) { - const data = `${username}:${password}`; - const authorization = `Basic ${Buffer.from(data).toString('base64')}`; - - return { - 'proxy-authorization': authorization, - authorization - }; - } - - return {}; -}; diff --git a/setup-pandoc/node_modules/http2-wrapper/source/proxies/h1-over-h2.js b/setup-pandoc/node_modules/http2-wrapper/source/proxies/h1-over-h2.js deleted file mode 100644 index 15a4f78b2..000000000 --- a/setup-pandoc/node_modules/http2-wrapper/source/proxies/h1-over-h2.js +++ /dev/null @@ -1,90 +0,0 @@ -'use strict'; -const tls = require('tls'); -const http = require('http'); -const https = require('https'); -const JSStreamSocket = require('../utils/js-stream-socket.js'); -const {globalAgent} = require('../agent.js'); -const UnexpectedStatusCodeError = require('./unexpected-status-code-error.js'); -const initialize = require('./initialize.js'); -const getAuthorizationHeaders = require('./get-auth-headers.js'); - -const createConnection = (self, options, callback) => { - (async () => { - try { - const {proxyOptions} = self; - const {url, headers, raw} = proxyOptions; - - const stream = await globalAgent.request(url, proxyOptions, { - ...getAuthorizationHeaders(self), - ...headers, - ':method': 'CONNECT', - ':authority': `${options.host}:${options.port}` - }); - - stream.once('error', callback); - stream.once('response', headers => { - const statusCode = headers[':status']; - - if (statusCode !== 200) { - callback(new UnexpectedStatusCodeError(statusCode, '')); - return; - } - - const encrypted = self instanceof https.Agent; - - if (raw && encrypted) { - options.socket = stream; - const secureStream = tls.connect(options); - - secureStream.once('close', () => { - stream.destroy(); - }); - - callback(null, secureStream); - return; - } - - const socket = new JSStreamSocket(stream); - socket.encrypted = false; - socket._handle.getpeername = out => { - out.family = undefined; - out.address = undefined; - out.port = undefined; - }; - - callback(null, socket); - }); - } catch (error) { - callback(error); - } - })(); -}; - -class HttpOverHttp2 extends http.Agent { - constructor(options) { - super(options); - - initialize(this, options.proxyOptions); - } - - createConnection(options, callback) { - createConnection(this, options, callback); - } -} - -class HttpsOverHttp2 extends https.Agent { - constructor(options) { - super(options); - - initialize(this, options.proxyOptions); - } - - createConnection(options, callback) { - createConnection(this, options, callback); - } -} - -module.exports = { - HttpOverHttp2, - HttpsOverHttp2 -}; diff --git a/setup-pandoc/node_modules/http2-wrapper/source/proxies/h2-over-h1.js b/setup-pandoc/node_modules/http2-wrapper/source/proxies/h2-over-h1.js deleted file mode 100644 index 8764f0782..000000000 --- a/setup-pandoc/node_modules/http2-wrapper/source/proxies/h2-over-h1.js +++ /dev/null @@ -1,48 +0,0 @@ -'use strict'; -const http = require('http'); -const https = require('https'); -const Http2OverHttpX = require('./h2-over-hx.js'); -const getAuthorizationHeaders = require('./get-auth-headers.js'); - -const getStream = request => new Promise((resolve, reject) => { - const onConnect = (response, socket, head) => { - socket.unshift(head); - - request.off('error', reject); - resolve([socket, response.statusCode, response.statusMessage]); - }; - - request.once('error', reject); - request.once('connect', onConnect); -}); - -class Http2OverHttp extends Http2OverHttpX { - async _getProxyStream(authority) { - const {proxyOptions} = this; - const {url, headers} = this.proxyOptions; - - const network = url.protocol === 'https:' ? https : http; - - // `new URL('https://localhost/httpbin.org:443')` results in - // a `/httpbin.org:443` path, which has an invalid leading slash. - const request = network.request({ - ...proxyOptions, - hostname: url.hostname, - port: url.port, - path: authority, - headers: { - ...getAuthorizationHeaders(this), - ...headers, - host: authority - }, - method: 'CONNECT' - }).end(); - - return getStream(request); - } -} - -module.exports = { - Http2OverHttp, - Http2OverHttps: Http2OverHttp -}; diff --git a/setup-pandoc/node_modules/http2-wrapper/source/proxies/h2-over-h2.js b/setup-pandoc/node_modules/http2-wrapper/source/proxies/h2-over-h2.js deleted file mode 100644 index 414c5e914..000000000 --- a/setup-pandoc/node_modules/http2-wrapper/source/proxies/h2-over-h2.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; -const {globalAgent} = require('../agent.js'); -const Http2OverHttpX = require('./h2-over-hx.js'); -const getAuthorizationHeaders = require('./get-auth-headers.js'); - -const getStatusCode = stream => new Promise((resolve, reject) => { - stream.once('error', reject); - stream.once('response', headers => { - stream.off('error', reject); - resolve(headers[':status']); - }); -}); - -class Http2OverHttp2 extends Http2OverHttpX { - async _getProxyStream(authority) { - const {proxyOptions} = this; - - const headers = { - ...getAuthorizationHeaders(this), - ...proxyOptions.headers, - ':method': 'CONNECT', - ':authority': authority - }; - - const stream = await globalAgent.request(proxyOptions.url, proxyOptions, headers); - const statusCode = await getStatusCode(stream); - - return [stream, statusCode, '']; - } -} - -module.exports = Http2OverHttp2; diff --git a/setup-pandoc/node_modules/http2-wrapper/source/proxies/h2-over-hx.js b/setup-pandoc/node_modules/http2-wrapper/source/proxies/h2-over-hx.js deleted file mode 100644 index 0f5a104bc..000000000 --- a/setup-pandoc/node_modules/http2-wrapper/source/proxies/h2-over-hx.js +++ /dev/null @@ -1,40 +0,0 @@ -'use strict'; -const {Agent} = require('../agent.js'); -const JSStreamSocket = require('../utils/js-stream-socket.js'); -const UnexpectedStatusCodeError = require('./unexpected-status-code-error.js'); -const initialize = require('./initialize.js'); - -class Http2OverHttpX extends Agent { - constructor(options) { - super(options); - - initialize(this, options.proxyOptions); - } - - async createConnection(origin, options) { - const authority = `${origin.hostname}:${origin.port || 443}`; - - const [stream, statusCode, statusMessage] = await this._getProxyStream(authority); - if (statusCode !== 200) { - throw new UnexpectedStatusCodeError(statusCode, statusMessage); - } - - if (this.proxyOptions.raw) { - options.socket = stream; - } else { - const socket = new JSStreamSocket(stream); - socket.encrypted = false; - socket._handle.getpeername = out => { - out.family = undefined; - out.address = undefined; - out.port = undefined; - }; - - return socket; - } - - return super.createConnection(origin, options); - } -} - -module.exports = Http2OverHttpX; diff --git a/setup-pandoc/node_modules/http2-wrapper/source/proxies/initialize.js b/setup-pandoc/node_modules/http2-wrapper/source/proxies/initialize.js deleted file mode 100644 index e4c58898e..000000000 --- a/setup-pandoc/node_modules/http2-wrapper/source/proxies/initialize.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; -// See https://github.com/facebook/jest/issues/2549 -// eslint-disable-next-line node/prefer-global/url -const {URL} = require('url'); -const checkType = require('../utils/check-type.js'); - -module.exports = (self, proxyOptions) => { - checkType('proxyOptions', proxyOptions, ['object']); - checkType('proxyOptions.headers', proxyOptions.headers, ['object', 'undefined']); - checkType('proxyOptions.raw', proxyOptions.raw, ['boolean', 'undefined']); - checkType('proxyOptions.url', proxyOptions.url, [URL, 'string']); - - const url = new URL(proxyOptions.url); - - self.proxyOptions = { - raw: true, - ...proxyOptions, - headers: {...proxyOptions.headers}, - url - }; -}; diff --git a/setup-pandoc/node_modules/http2-wrapper/source/proxies/unexpected-status-code-error.js b/setup-pandoc/node_modules/http2-wrapper/source/proxies/unexpected-status-code-error.js deleted file mode 100644 index c7f02164a..000000000 --- a/setup-pandoc/node_modules/http2-wrapper/source/proxies/unexpected-status-code-error.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -class UnexpectedStatusCodeError extends Error { - constructor(statusCode, statusMessage = '') { - super(`The proxy server rejected the request with status code ${statusCode} (${statusMessage || 'empty status message'})`); - this.statusCode = statusCode; - this.statusMessage = statusMessage; - } -} - -module.exports = UnexpectedStatusCodeError; diff --git a/setup-pandoc/node_modules/http2-wrapper/source/utils/calculate-server-name.js b/setup-pandoc/node_modules/http2-wrapper/source/utils/calculate-server-name.js index a8ba061c8..b05c099ff 100644 --- a/setup-pandoc/node_modules/http2-wrapper/source/utils/calculate-server-name.js +++ b/setup-pandoc/node_modules/http2-wrapper/source/utils/calculate-server-name.js @@ -1,27 +1,25 @@ 'use strict'; -const {isIP} = require('net'); -const assert = require('assert'); +const net = require('net'); +/* istanbul ignore file: https://github.com/nodejs/node/blob/v13.0.1/lib/_http_agent.js */ -const getHost = host => { - if (host[0] === '[') { - const idx = host.indexOf(']'); +module.exports = options => { + let servername = options.host; + const hostHeader = options.headers && options.headers.host; - assert(idx !== -1); - return host.slice(1, idx); + if (hostHeader) { + if (hostHeader.startsWith('[')) { + const index = hostHeader.indexOf(']'); + if (index === -1) { + servername = hostHeader; + } else { + servername = hostHeader.slice(1, -1); + } + } else { + servername = hostHeader.split(':', 1)[0]; + } } - const idx = host.indexOf(':'); - if (idx === -1) { - return host; - } - - return host.slice(0, idx); -}; - -module.exports = host => { - const servername = getHost(host); - - if (isIP(servername)) { + if (net.isIP(servername)) { return ''; } diff --git a/setup-pandoc/node_modules/http2-wrapper/source/utils/check-type.js b/setup-pandoc/node_modules/http2-wrapper/source/utils/check-type.js deleted file mode 100644 index ddfefdce8..000000000 --- a/setup-pandoc/node_modules/http2-wrapper/source/utils/check-type.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -const checkType = (name, value, types) => { - const valid = types.some(type => { - const typeofType = typeof type; - if (typeofType === 'string') { - return typeof value === type; - } - - return value instanceof type; - }); - - if (!valid) { - const names = types.map(type => typeof type === 'string' ? type : type.name); - - throw new TypeError(`Expected '${name}' to be a type of ${names.join(' or ')}, got ${typeof value}`); - } -}; - -module.exports = checkType; diff --git a/setup-pandoc/node_modules/http2-wrapper/source/utils/delay-async-destroy.js b/setup-pandoc/node_modules/http2-wrapper/source/utils/delay-async-destroy.js deleted file mode 100644 index 53d81cf1e..000000000 --- a/setup-pandoc/node_modules/http2-wrapper/source/utils/delay-async-destroy.js +++ /dev/null @@ -1,33 +0,0 @@ -'use strict'; - -module.exports = stream => { - if (stream.listenerCount('error') !== 0) { - return stream; - } - - stream.__destroy = stream._destroy; - stream._destroy = (...args) => { - const callback = args.pop(); - - stream.__destroy(...args, async error => { - await Promise.resolve(); - callback(error); - }); - }; - - const onError = error => { - // eslint-disable-next-line promise/prefer-await-to-then - Promise.resolve().then(() => { - stream.emit('error', error); - }); - }; - - stream.once('error', onError); - - // eslint-disable-next-line promise/prefer-await-to-then - Promise.resolve().then(() => { - stream.off('error', onError); - }); - - return stream; -}; diff --git a/setup-pandoc/node_modules/http2-wrapper/source/utils/errors.js b/setup-pandoc/node_modules/http2-wrapper/source/utils/errors.js index 7be9e6b5f..501828345 100644 --- a/setup-pandoc/node_modules/http2-wrapper/source/utils/errors.js +++ b/setup-pandoc/node_modules/http2-wrapper/source/utils/errors.js @@ -24,28 +24,22 @@ makeError(TypeError, 'ERR_INVALID_ARG_TYPE', args => { return `The "${args[0]}" ${type} must be ${isManyTypes ? 'one of' : 'of'} type ${valid}. Received ${typeof args[2]}`; }); -makeError(TypeError, 'ERR_INVALID_PROTOCOL', args => - `Protocol "${args[0]}" not supported. Expected "${args[1]}"` -); - -makeError(Error, 'ERR_HTTP_HEADERS_SENT', args => - `Cannot ${args[0]} headers after they are sent to the client` -); - -makeError(TypeError, 'ERR_INVALID_HTTP_TOKEN', args => - `${args[0]} must be a valid HTTP token [${args[1]}]` -); - -makeError(TypeError, 'ERR_HTTP_INVALID_HEADER_VALUE', args => - `Invalid value "${args[0]} for header "${args[1]}"` -); - -makeError(TypeError, 'ERR_INVALID_CHAR', args => - `Invalid character in ${args[0]} [${args[1]}]` -); - -makeError( - Error, - 'ERR_HTTP2_NO_SOCKET_MANIPULATION', - 'HTTP/2 sockets should not be directly manipulated (e.g. read and written)' -); +makeError(TypeError, 'ERR_INVALID_PROTOCOL', args => { + return `Protocol "${args[0]}" not supported. Expected "${args[1]}"`; +}); + +makeError(Error, 'ERR_HTTP_HEADERS_SENT', args => { + return `Cannot ${args[0]} headers after they are sent to the client`; +}); + +makeError(TypeError, 'ERR_INVALID_HTTP_TOKEN', args => { + return `${args[0]} must be a valid HTTP token [${args[1]}]`; +}); + +makeError(TypeError, 'ERR_HTTP_INVALID_HEADER_VALUE', args => { + return `Invalid value "${args[0]} for header "${args[1]}"`; +}); + +makeError(TypeError, 'ERR_INVALID_CHAR', args => { + return `Invalid character in ${args[0]} [${args[1]}]`; +}); diff --git a/setup-pandoc/node_modules/http2-wrapper/source/utils/js-stream-socket.js b/setup-pandoc/node_modules/http2-wrapper/source/utils/js-stream-socket.js deleted file mode 100644 index ac22280c7..000000000 --- a/setup-pandoc/node_modules/http2-wrapper/source/utils/js-stream-socket.js +++ /dev/null @@ -1,8 +0,0 @@ -'use strict'; -const stream = require('stream'); -const tls = require('tls'); - -// Really awesome hack. -const JSStreamSocket = (new tls.TLSSocket(new stream.PassThrough()))._handle._parentWrap.constructor; - -module.exports = JSStreamSocket; diff --git a/setup-pandoc/node_modules/http2-wrapper/source/utils/proxy-socket-handler.js b/setup-pandoc/node_modules/http2-wrapper/source/utils/proxy-socket-handler.js deleted file mode 100644 index 89a0ac4d8..000000000 --- a/setup-pandoc/node_modules/http2-wrapper/source/utils/proxy-socket-handler.js +++ /dev/null @@ -1,102 +0,0 @@ -'use strict'; -const {ERR_HTTP2_NO_SOCKET_MANIPULATION} = require('./errors.js'); - -/* istanbul ignore file */ -/* https://github.com/nodejs/node/blob/6eec858f34a40ffa489c1ec54bb24da72a28c781/lib/internal/http2/compat.js#L195-L272 */ - -const proxySocketHandler = { - has(stream, property) { - // Replaced [kSocket] with .socket - const reference = stream.session === undefined ? stream : stream.session.socket; - return (property in stream) || (property in reference); - }, - - get(stream, property) { - switch (property) { - case 'on': - case 'once': - case 'end': - case 'emit': - case 'destroy': - return stream[property].bind(stream); - case 'writable': - case 'destroyed': - return stream[property]; - case 'readable': - if (stream.destroyed) { - return false; - } - - return stream.readable; - case 'setTimeout': { - const {session} = stream; - if (session !== undefined) { - return session.setTimeout.bind(session); - } - - return stream.setTimeout.bind(stream); - } - - case 'write': - case 'read': - case 'pause': - case 'resume': - throw new ERR_HTTP2_NO_SOCKET_MANIPULATION(); - default: { - // Replaced [kSocket] with .socket - const reference = stream.session === undefined ? stream : stream.session.socket; - const value = reference[property]; - - return typeof value === 'function' ? value.bind(reference) : value; - } - } - }, - - getPrototypeOf(stream) { - if (stream.session !== undefined) { - // Replaced [kSocket] with .socket - return Reflect.getPrototypeOf(stream.session.socket); - } - - return Reflect.getPrototypeOf(stream); - }, - - set(stream, property, value) { - switch (property) { - case 'writable': - case 'readable': - case 'destroyed': - case 'on': - case 'once': - case 'end': - case 'emit': - case 'destroy': - stream[property] = value; - return true; - case 'setTimeout': { - const {session} = stream; - if (session === undefined) { - stream.setTimeout = value; - } else { - session.setTimeout = value; - } - - return true; - } - - case 'write': - case 'read': - case 'pause': - case 'resume': - throw new ERR_HTTP2_NO_SOCKET_MANIPULATION(); - default: { - // Replaced [kSocket] with .socket - const reference = stream.session === undefined ? stream : stream.session.socket; - reference[property] = value; - return true; - } - } - } -}; - -module.exports = proxySocketHandler; diff --git a/setup-pandoc/node_modules/http2-wrapper/source/utils/url-to-options.js b/setup-pandoc/node_modules/http2-wrapper/source/utils/url-to-options.js new file mode 100644 index 000000000..36d1580a0 --- /dev/null +++ b/setup-pandoc/node_modules/http2-wrapper/source/utils/url-to-options.js @@ -0,0 +1,25 @@ +'use strict'; +/* istanbul ignore file: https://github.com/nodejs/node/blob/a91293d4d9ab403046ab5eb022332e4e3d249bd3/lib/internal/url.js#L1257 */ + +module.exports = url => { + const options = { + protocol: url.protocol, + hostname: typeof url.hostname === 'string' && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname, + host: url.host, + hash: url.hash, + search: url.search, + pathname: url.pathname, + href: url.href, + path: `${url.pathname || ''}${url.search || ''}` + }; + + if (typeof url.port === 'string' && url.port.length !== 0) { + options.port = Number(url.port); + } + + if (url.username || url.password) { + options.auth = `${url.username || ''}:${url.password || ''}`; + } + + return options; +}; diff --git a/setup-pandoc/node_modules/http2-wrapper/source/utils/validate-header-name.js b/setup-pandoc/node_modules/http2-wrapper/source/utils/validate-header-name.js deleted file mode 100644 index 82cbc3450..000000000 --- a/setup-pandoc/node_modules/http2-wrapper/source/utils/validate-header-name.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; -const {ERR_INVALID_HTTP_TOKEN} = require('./errors.js'); -const isRequestPseudoHeader = require('./is-request-pseudo-header.js'); - -const isValidHttpToken = /^[\^`\-\w!#$%&*+.|~]+$/; - -module.exports = name => { - if (typeof name !== 'string' || (!isValidHttpToken.test(name) && !isRequestPseudoHeader(name))) { - throw new ERR_INVALID_HTTP_TOKEN('Header name', name); - } -}; diff --git a/setup-pandoc/node_modules/http2-wrapper/source/utils/validate-header-value.js b/setup-pandoc/node_modules/http2-wrapper/source/utils/validate-header-value.js deleted file mode 100644 index 749c985d6..000000000 --- a/setup-pandoc/node_modules/http2-wrapper/source/utils/validate-header-value.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict'; -const { - ERR_HTTP_INVALID_HEADER_VALUE, - ERR_INVALID_CHAR -} = require('./errors.js'); - -const isInvalidHeaderValue = /[^\t\u0020-\u007E\u0080-\u00FF]/; - -module.exports = (name, value) => { - if (typeof value === 'undefined') { - throw new ERR_HTTP_INVALID_HEADER_VALUE(value, name); - } - - if (isInvalidHeaderValue.test(value)) { - throw new ERR_INVALID_CHAR('header content', name); - } -}; diff --git a/setup-pandoc/node_modules/lowercase-keys/index.d.ts b/setup-pandoc/node_modules/lowercase-keys/index.d.ts index c500205fb..dc90a7516 100644 --- a/setup-pandoc/node_modules/lowercase-keys/index.d.ts +++ b/setup-pandoc/node_modules/lowercase-keys/index.d.ts @@ -5,10 +5,12 @@ Lowercase the keys of an object. @example ``` -import lowercaseKeys from 'lowercase-keys'; +import lowercaseKeys = require('lowercase-keys'); lowercaseKeys({FOO: true, bAr: false}); //=> {foo: true, bar: false} ``` */ -export default function lowercaseKeys(object: Record): Record; +declare function lowercaseKeys(object: {[key: string]: T}): {[key: string]: T}; + +export = lowercaseKeys; diff --git a/setup-pandoc/node_modules/lowercase-keys/index.js b/setup-pandoc/node_modules/lowercase-keys/index.js index c1e27e453..357fb8f4e 100644 --- a/setup-pandoc/node_modules/lowercase-keys/index.js +++ b/setup-pandoc/node_modules/lowercase-keys/index.js @@ -1,3 +1,10 @@ -export default function lowercaseKeys(object) { - return Object.fromEntries(Object.entries(object).map(([key, value]) => [key.toLowerCase(), value])); -} +'use strict'; +module.exports = object => { + const result = {}; + + for (const [key, value] of Object.entries(object)) { + result[key.toLowerCase()] = value; + } + + return result; +}; diff --git a/setup-pandoc/node_modules/lowercase-keys/license b/setup-pandoc/node_modules/lowercase-keys/license index fa7ceba3e..e7af2f771 100644 --- a/setup-pandoc/node_modules/lowercase-keys/license +++ b/setup-pandoc/node_modules/lowercase-keys/license @@ -1,6 +1,6 @@ MIT License -Copyright (c) Sindre Sorhus (https://sindresorhus.com) +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: diff --git a/setup-pandoc/node_modules/lowercase-keys/package.json b/setup-pandoc/node_modules/lowercase-keys/package.json index dd9e59149..c11d81300 100644 --- a/setup-pandoc/node_modules/lowercase-keys/package.json +++ b/setup-pandoc/node_modules/lowercase-keys/package.json @@ -1,19 +1,16 @@ { "name": "lowercase-keys", - "version": "3.0.0", + "version": "2.0.0", "description": "Lowercase the keys of an object", "license": "MIT", "repository": "sindresorhus/lowercase-keys", - "funding": "https://github.com/sponsors/sindresorhus", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", - "url": "https://sindresorhus.com" + "url": "sindresorhus.com" }, - "type": "module", - "exports": "./index.js", "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + "node": ">=8" }, "scripts": { "test": "xo && ava && tsd" @@ -34,8 +31,8 @@ "key" ], "devDependencies": { - "ava": "^3.15.0", - "tsd": "^0.18.0", - "xo": "^0.45.0" + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" } } diff --git a/setup-pandoc/node_modules/lowercase-keys/readme.md b/setup-pandoc/node_modules/lowercase-keys/readme.md index cea0af5ce..b1ed06108 100644 --- a/setup-pandoc/node_modules/lowercase-keys/readme.md +++ b/setup-pandoc/node_modules/lowercase-keys/readme.md @@ -1,32 +1,32 @@ -# lowercase-keys +# lowercase-keys [![Build Status](https://travis-ci.org/sindresorhus/lowercase-keys.svg?branch=master)](https://travis-ci.org/sindresorhus/lowercase-keys) > Lowercase the keys of an object -Check out [`map-obj`](https://github.com/sindresorhus/map-obj) if you need support for deep iteration. ## Install -```sh -npm install lowercase-keys ``` +$ npm install lowercase-keys +``` + ## Usage ```js -import lowercaseKeys from 'lowercase-keys'; +const lowercaseKeys = require('lowercase-keys'); lowercaseKeys({FOO: true, bAr: false}); //=> {foo: true, bar: false} ``` + ## API ### lowercaseKeys(object) Returns a new object with the keys lowercased. -## lowercase-keys for enterprise -Available as part of the Tidelift Subscription. +## License -The maintainers of lowercase-keys and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-lowercase-keys?utm_source=npm-lowercase-keys&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/setup-pandoc/node_modules/mimic-response/index.d.ts b/setup-pandoc/node_modules/mimic-response/index.d.ts deleted file mode 100644 index 324613fb2..000000000 --- a/setup-pandoc/node_modules/mimic-response/index.d.ts +++ /dev/null @@ -1,29 +0,0 @@ -import {IncomingMessage} from 'node:http'; - -/** -Mimic a [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage) - -Makes `toStream` include the properties from `fromStream`. - -@param fromStream - The stream to copy the properties from. -@param toStream - The stream to copy the properties to. -@return The same object as `toStream`. - -@example -``` -import {PassThrough as PassThroughStream} from 'node:stream'; -import mimicResponse from 'mimic-response'; - -const responseStream = getHttpResponseStream(); -const myStream = new PassThroughStream(); - -mimicResponse(responseStream, myStream); - -console.log(myStream.statusCode); -//=> 200 -``` -*/ -export default function mimicResponse( - fromStream: IncomingMessage, - toStream: T, -): T & IncomingMessage; diff --git a/setup-pandoc/node_modules/mimic-response/index.js b/setup-pandoc/node_modules/mimic-response/index.js index a2e898f66..d5e33be47 100644 --- a/setup-pandoc/node_modules/mimic-response/index.js +++ b/setup-pandoc/node_modules/mimic-response/index.js @@ -1,75 +1,32 @@ +'use strict'; + // We define these manually to ensure they're always copied // even if they would move up the prototype chain // https://nodejs.org/api/http.html#http_class_http_incomingmessage -const knownProperties = [ - 'aborted', - 'complete', +const knownProps = [ + 'destroy', + 'setTimeout', + 'socket', 'headers', + 'trailers', + 'rawHeaders', + 'statusCode', 'httpVersion', 'httpVersionMinor', 'httpVersionMajor', - 'method', - 'rawHeaders', 'rawTrailers', - 'setTimeout', - 'socket', - 'statusCode', - 'statusMessage', - 'trailers', - 'url', + 'statusMessage' ]; -export default function mimicResponse(fromStream, toStream) { - if (toStream._readableState.autoDestroy) { - throw new Error('The second stream must have the `autoDestroy` option set to `false`'); - } - - const fromProperties = new Set([...Object.keys(fromStream), ...knownProperties]); - - const properties = {}; +module.exports = (fromStream, toStream) => { + const fromProps = new Set(Object.keys(fromStream).concat(knownProps)); - for (const property of fromProperties) { - // Don't overwrite existing properties. - if (property in toStream) { + for (const prop of fromProps) { + // Don't overwrite existing properties + if (prop in toStream) { continue; } - properties[property] = { - get() { - const value = fromStream[property]; - const isFunction = typeof value === 'function'; - - return isFunction ? value.bind(fromStream) : value; - }, - set(value) { - fromStream[property] = value; - }, - enumerable: true, - configurable: false, - }; + toStream[prop] = typeof fromStream[prop] === 'function' ? fromStream[prop].bind(fromStream) : fromStream[prop]; } - - Object.defineProperties(toStream, properties); - - fromStream.once('aborted', () => { - toStream.destroy(); - - toStream.emit('aborted'); - }); - - fromStream.once('close', () => { - if (fromStream.complete) { - if (toStream.readable) { - toStream.once('end', () => { - toStream.emit('close'); - }); - } else { - toStream.emit('close'); - } - } else { - toStream.emit('close'); - } - }); - - return toStream; -} +}; diff --git a/setup-pandoc/node_modules/mimic-response/license b/setup-pandoc/node_modules/mimic-response/license index fa7ceba3e..e7af2f771 100644 --- a/setup-pandoc/node_modules/mimic-response/license +++ b/setup-pandoc/node_modules/mimic-response/license @@ -1,6 +1,6 @@ MIT License -Copyright (c) Sindre Sorhus (https://sindresorhus.com) +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: diff --git a/setup-pandoc/node_modules/mimic-response/package.json b/setup-pandoc/node_modules/mimic-response/package.json index bf5e8ca5c..689cb61ef 100644 --- a/setup-pandoc/node_modules/mimic-response/package.json +++ b/setup-pandoc/node_modules/mimic-response/package.json @@ -1,44 +1,37 @@ { - "name": "mimic-response", - "version": "4.0.0", - "description": "Mimic a Node.js HTTP response stream", - "license": "MIT", - "repository": "sindresorhus/mimic-response", - "funding": "https://github.com/sponsors/sindresorhus", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "https://sindresorhus.com" - }, - "type": "module", - "exports": "./index.js", - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "scripts": { - "test": "xo && ava && tsd" - }, - "files": [ - "index.d.ts", - "index.js" - ], - "keywords": [ - "mimic", - "response", - "stream", - "http", - "https", - "request", - "get", - "core" - ], - "devDependencies": { - "@types/node": "^16.4.13", - "ava": "^3.15.0", - "create-test-server": "^3.0.1", - "p-event": "^4.2.0", - "pify": "^5.0.0", - "tsd": "^0.17.0", - "xo": "^0.44.0" - } + "name": "mimic-response", + "version": "1.0.1", + "description": "Mimic a Node.js HTTP response stream", + "license": "MIT", + "repository": "sindresorhus/mimic-response", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=4" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js" + ], + "keywords": [ + "mimic", + "response", + "stream", + "http", + "https", + "request", + "get", + "core" + ], + "devDependencies": { + "ava": "*", + "create-test-server": "^0.1.0", + "pify": "^3.0.0", + "xo": "*" + } } diff --git a/setup-pandoc/node_modules/mimic-response/readme.md b/setup-pandoc/node_modules/mimic-response/readme.md index 09f12995c..e07ec661c 100644 --- a/setup-pandoc/node_modules/mimic-response/readme.md +++ b/setup-pandoc/node_modules/mimic-response/readme.md @@ -1,21 +1,23 @@ -# mimic-response +# mimic-response [![Build Status](https://travis-ci.org/sindresorhus/mimic-response.svg?branch=master)](https://travis-ci.org/sindresorhus/mimic-response) > Mimic a [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage) + ## Install ``` $ npm install mimic-response ``` + ## Usage ```js -import {PassThrough as PassThroughStream} from 'node:stream'; -import mimicResponse from 'mimic-response'; +const stream = require('stream'); +const mimicResponse = require('mimic-response'); const responseStream = getHttpResponseStream(); -const myStream = new PassThroughStream(); +const myStream = new stream.PassThrough(); mimicResponse(responseStream, myStream); @@ -23,31 +25,11 @@ console.log(myStream.statusCode); //=> 200 ``` + ## API ### mimicResponse(from, to) -**Note #1:** The `from.destroy(error)` function is not proxied. You have to call it manually: - -```js -import {PassThrough as PassThroughStream} from 'node:stream'; -import mimicResponse from 'mimic-response'; - -const responseStream = getHttpResponseStream(); - -const myStream = new PassThroughStream({ - destroy(error, callback) { - responseStream.destroy(); - - callback(error); - } -}); - -myStream.destroy(); -``` - -Please note that `myStream` and `responseStream` never throw. The error is passed to the request instead. - #### from Type: `Stream` @@ -60,19 +42,13 @@ Type: `Stream` Any stream. + ## Related - [mimic-fn](https://github.com/sindresorhus/mimic-fn) - Make a function mimic another one - [clone-response](https://github.com/lukechilds/clone-response) - Clone a Node.js response stream ---- - -
- - Get professional support for this package with a Tidelift subscription - -
- - Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. -
-
+ +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/setup-pandoc/node_modules/normalize-url/index.d.ts b/setup-pandoc/node_modules/normalize-url/index.d.ts index 0dd9203e9..ca40f8f0d 100644 --- a/setup-pandoc/node_modules/normalize-url/index.d.ts +++ b/setup-pandoc/node_modules/normalize-url/index.d.ts @@ -1,295 +1,259 @@ -export type Options = { - /** - @default 'http' - */ - readonly defaultProtocol?: 'https' | 'http'; +declare namespace normalizeUrl { + interface Options { + /** + @default 'http:' + */ + readonly defaultProtocol?: string; - /** - Prepends `defaultProtocol` to the URL if it's protocol-relative. + /** + Prepends `defaultProtocol` to the URL if it's protocol-relative. - @default true + @default true - @example - ``` - normalizeUrl('//sindresorhus.com'); - //=> 'http://sindresorhus.com' + @example + ``` + normalizeUrl('//sindresorhus.com:80/'); + //=> 'http://sindresorhus.com' - normalizeUrl('//sindresorhus.com', {normalizeProtocol: false}); - //=> '//sindresorhus.com' - ``` - */ - readonly normalizeProtocol?: boolean; + normalizeUrl('//sindresorhus.com:80/', {normalizeProtocol: false}); + //=> '//sindresorhus.com' + ``` + */ + readonly normalizeProtocol?: boolean; - /** - Normalizes HTTPS URLs to HTTP. + /** + Normalizes `https:` URLs to `http:`. - @default false + @default false - @example - ``` - normalizeUrl('https://sindresorhus.com'); - //=> 'https://sindresorhus.com' + @example + ``` + normalizeUrl('https://sindresorhus.com:80/'); + //=> 'https://sindresorhus.com' - normalizeUrl('https://sindresorhus.com', {forceHttp: true}); - //=> 'http://sindresorhus.com' - ``` - */ - readonly forceHttp?: boolean; + normalizeUrl('https://sindresorhus.com:80/', {forceHttp: true}); + //=> 'http://sindresorhus.com' + ``` + */ + readonly forceHttp?: boolean; - /** - Normalizes HTTP URLs to HTTPS. + /** + Normalizes `http:` URLs to `https:`. - This option cannot be used with the `forceHttp` option at the same time. + This option can't be used with the `forceHttp` option at the same time. - @default false + @default false - @example - ``` - normalizeUrl('http://sindresorhus.com'); - //=> 'http://sindresorhus.com' + @example + ``` + normalizeUrl('https://sindresorhus.com:80/'); + //=> 'https://sindresorhus.com' - normalizeUrl('http://sindresorhus.com', {forceHttps: true}); - //=> 'https://sindresorhus.com' - ``` - */ - readonly forceHttps?: boolean; + normalizeUrl('http://sindresorhus.com:80/', {forceHttps: true}); + //=> 'https://sindresorhus.com' + ``` + */ + readonly forceHttps?: boolean; - /** - Strip the [authentication](https://en.wikipedia.org/wiki/Basic_access_authentication) part of a URL. + /** + Strip the [authentication](https://en.wikipedia.org/wiki/Basic_access_authentication) part of a URL. - @default true + @default true - @example - ``` - normalizeUrl('user:password@sindresorhus.com'); - //=> 'https://sindresorhus.com' + @example + ``` + normalizeUrl('user:password@sindresorhus.com'); + //=> 'https://sindresorhus.com' - normalizeUrl('user:password@sindresorhus.com', {stripAuthentication: false}); - //=> 'https://user:password@sindresorhus.com' - ``` - */ - readonly stripAuthentication?: boolean; + normalizeUrl('user:password@sindresorhus.com', {stripAuthentication: false}); + //=> 'https://user:password@sindresorhus.com' + ``` + */ + readonly stripAuthentication?: boolean; - /** - Removes hash from the URL. + /** + Removes hash from the URL. + + @default false - @default false + @example + ``` + normalizeUrl('sindresorhus.com/about.html#contact'); + //=> 'http://sindresorhus.com/about.html#contact' - @example - ``` - normalizeUrl('sindresorhus.com/about.html#contact'); - //=> 'http://sindresorhus.com/about.html#contact' + normalizeUrl('sindresorhus.com/about.html#contact', {stripHash: true}); + //=> 'http://sindresorhus.com/about.html' + ``` + */ + readonly stripHash?: boolean; - normalizeUrl('sindresorhus.com/about.html#contact', {stripHash: true}); - //=> 'http://sindresorhus.com/about.html' - ``` - */ - readonly stripHash?: boolean; + /** + Removes HTTP(S) protocol from an URL `http://sindresorhus.com` → `sindresorhus.com`. - /** - Remove the protocol from the URL: `http://sindresorhus.com` → `sindresorhus.com`. + @default false - It will only remove `https://` and `http://` protocols. + @example + ``` + normalizeUrl('https://sindresorhus.com'); + //=> 'https://sindresorhus.com' - @default false + normalizeUrl('sindresorhus.com', {stripProtocol: true}); + //=> 'sindresorhus.com' + ``` + */ + readonly stripProtocol?: boolean; - @example - ``` - normalizeUrl('https://sindresorhus.com'); - //=> 'https://sindresorhus.com' + /** + Strip the [text fragment](https://web.dev/text-fragments/) part of the URL - normalizeUrl('sindresorhus.com', {stripProtocol: true}); - //=> 'sindresorhus.com' - ``` - */ - readonly stripProtocol?: boolean; + __Note:__ The text fragment will always be removed if the `stripHash` option is set to `true`, as the hash contains the text fragment. - /** - Strip the [text fragment](https://web.dev/text-fragments/) part of the URL + @default true - __Note:__ The text fragment will always be removed if the `stripHash` option is set to `true`, as the hash contains the text fragment. + @example + ``` + normalizeUrl('http://sindresorhus.com/about.html#:~:text=hello'); + //=> 'http://sindresorhus.com/about.html#' - @default true + normalizeUrl('http://sindresorhus.com/about.html#section:~:text=hello'); + //=> 'http://sindresorhus.com/about.html#section' - @example - ``` - normalizeUrl('http://sindresorhus.com/about.html#:~:text=hello'); - //=> 'http://sindresorhus.com/about.html#' + normalizeUrl('http://sindresorhus.com/about.html#:~:text=hello', {stripTextFragment: false}); + //=> 'http://sindresorhus.com/about.html#:~:text=hello' - normalizeUrl('http://sindresorhus.com/about.html#section:~:text=hello'); - //=> 'http://sindresorhus.com/about.html#section' + normalizeUrl('http://sindresorhus.com/about.html#section:~:text=hello', {stripTextFragment: false}); + //=> 'http://sindresorhus.com/about.html#section:~:text=hello' + ``` + */ + readonly stripTextFragment?: boolean; + + /** + Removes `www.` from the URL. - normalizeUrl('http://sindresorhus.com/about.html#:~:text=hello', {stripTextFragment: false}); - //=> 'http://sindresorhus.com/about.html#:~:text=hello' + @default true - normalizeUrl('http://sindresorhus.com/about.html#section:~:text=hello', {stripTextFragment: false}); - //=> 'http://sindresorhus.com/about.html#section:~:text=hello' - ``` - */ - readonly stripTextFragment?: boolean; + @example + ``` + normalizeUrl('http://www.sindresorhus.com'); + //=> 'http://sindresorhus.com' - /** - Removes `www.` from the URL. - - @default true - - @example - ``` - normalizeUrl('http://www.sindresorhus.com'); - //=> 'http://sindresorhus.com' - - normalizeUrl('http://www.sindresorhus.com', {stripWWW: false}); - //=> 'http://www.sindresorhus.com' - ``` - */ - readonly stripWWW?: boolean; - - /** - Removes query parameters that matches any of the provided strings or regexes. - - @default [/^utm_\w+/i] - - @example - ``` - normalizeUrl('www.sindresorhus.com?foo=bar&ref=test_ref', { - removeQueryParameters: ['ref'] - }); - //=> 'http://sindresorhus.com/?foo=bar' - ``` - - If a boolean is provided, `true` will remove all the query parameters. - - ``` - normalizeUrl('www.sindresorhus.com?foo=bar', { - removeQueryParameters: true - }); - //=> 'http://sindresorhus.com' - ``` - - `false` will not remove any query parameter. - - ``` - normalizeUrl('www.sindresorhus.com?foo=bar&utm_medium=test&ref=test_ref', { - removeQueryParameters: false - }); - //=> 'http://www.sindresorhus.com/?foo=bar&ref=test_ref&utm_medium=test' - ``` - */ - readonly removeQueryParameters?: ReadonlyArray | boolean; - - /** - Keeps only query parameters that matches any of the provided strings or regexes. - - __Note__: It overrides the `removeQueryParameters` option. - - @default undefined - - @example - ``` - normalizeUrl('https://sindresorhus.com?foo=bar&ref=unicorn', { - keepQueryParameters: ['ref'] - }); - //=> 'https://sindresorhus.com/?ref=unicorn' - ``` - */ - readonly keepQueryParameters?: ReadonlyArray; - - /** - Removes trailing slash. - - __Note__: Trailing slash is always removed if the URL doesn't have a pathname unless the `removeSingleSlash` option is set to `false`. - - @default true - - @example - ``` - normalizeUrl('http://sindresorhus.com/redirect/'); - //=> 'http://sindresorhus.com/redirect' - - normalizeUrl('http://sindresorhus.com/redirect/', {removeTrailingSlash: false}); - //=> 'http://sindresorhus.com/redirect/' - - normalizeUrl('http://sindresorhus.com/', {removeTrailingSlash: false}); - //=> 'http://sindresorhus.com' - ``` - */ - readonly removeTrailingSlash?: boolean; - - /** - Remove a sole `/` pathname in the output. This option is independent of `removeTrailingSlash`. - - @default true - - @example - ``` - normalizeUrl('https://sindresorhus.com/'); - //=> 'https://sindresorhus.com' - - normalizeUrl('https://sindresorhus.com/', {removeSingleSlash: false}); - //=> 'https://sindresorhus.com/' - ``` - */ - readonly removeSingleSlash?: boolean; - - /** - Removes the default directory index file from path that matches any of the provided strings or regexes. - When `true`, the regex `/^index\.[a-z]+$/` is used. - - @default false - - @example - ``` - normalizeUrl('www.sindresorhus.com/foo/default.php', { - removeDirectoryIndex: [/^default\.[a-z]+$/] - }); - //=> 'http://sindresorhus.com/foo' - ``` - */ - readonly removeDirectoryIndex?: boolean | ReadonlyArray; - - /** - Removes an explicit port number from the URL. - - Port 443 is always removed from HTTPS URLs and 80 is always removed from HTTP URLs regardless of this option. - - @default false - - @example - ``` - normalizeUrl('sindresorhus.com:123', { - removeExplicitPort: true - }); - //=> 'http://sindresorhus.com' - ``` - */ - readonly removeExplicitPort?: boolean; - - /** - Sorts the query parameters alphabetically by key. - - @default true - - @example - ``` - normalizeUrl('www.sindresorhus.com?b=two&a=one&c=three', { - sortQueryParameters: false - }); - //=> 'http://sindresorhus.com/?b=two&a=one&c=three' - ``` - */ - readonly sortQueryParameters?: boolean; -}; + normalizeUrl('http://www.sindresorhus.com', {stripWWW: false}); + //=> 'http://www.sindresorhus.com' + ``` + */ + readonly stripWWW?: boolean; + + /** + Removes query parameters that matches any of the provided strings or regexes. + + @default [/^utm_\w+/i] + + @example + ``` + normalizeUrl('www.sindresorhus.com?foo=bar&ref=test_ref', { + removeQueryParameters: ['ref'] + }); + //=> 'http://sindresorhus.com/?foo=bar' + ``` + + If a boolean is provided, `true` will remove all the query parameters. + + ``` + normalizeUrl('www.sindresorhus.com?foo=bar', { + removeQueryParameters: true + }); + //=> 'http://sindresorhus.com' + ``` + + `false` will not remove any query parameter. + + ``` + normalizeUrl('www.sindresorhus.com?foo=bar&utm_medium=test&ref=test_ref', { + removeQueryParameters: false + }); + //=> 'http://www.sindresorhus.com/?foo=bar&ref=test_ref&utm_medium=test' + ``` + */ + readonly removeQueryParameters?: ReadonlyArray | boolean; + + /** + Removes trailing slash. + + __Note__: Trailing slash is always removed if the URL doesn't have a pathname unless the `removeSingleSlash` option is set to `false`. + + @default true + + @example + ``` + normalizeUrl('http://sindresorhus.com/redirect/'); + //=> 'http://sindresorhus.com/redirect' + + normalizeUrl('http://sindresorhus.com/redirect/', {removeTrailingSlash: false}); + //=> 'http://sindresorhus.com/redirect/' + + normalizeUrl('http://sindresorhus.com/', {removeTrailingSlash: false}); + //=> 'http://sindresorhus.com' + ``` + */ + readonly removeTrailingSlash?: boolean; + + /** + Remove a sole `/` pathname in the output. This option is independant of `removeTrailingSlash`. + + @default true + + @example + ``` + normalizeUrl('https://sindresorhus.com/'); + //=> 'https://sindresorhus.com' + + normalizeUrl('https://sindresorhus.com/', {removeSingleSlash: false}); + //=> 'https://sindresorhus.com/' + ``` + */ + readonly removeSingleSlash?: boolean; + + /** + Removes the default directory index file from path that matches any of the provided strings or regexes. + When `true`, the regex `/^index\.[a-z]+$/` is used. + + @default false + + @example + ``` + normalizeUrl('www.sindresorhus.com/foo/default.php', { + removeDirectoryIndex: [/^default\.[a-z]+$/] + }); + //=> 'http://sindresorhus.com/foo' + ``` + */ + readonly removeDirectoryIndex?: ReadonlyArray; + + /** + Sorts the query parameters alphabetically by key. + + @default true + + @example + ``` + normalizeUrl('www.sindresorhus.com?b=two&a=one&c=three', { + sortQueryParameters: false + }); + //=> 'http://sindresorhus.com/?b=two&a=one&c=three' + ``` + */ + readonly sortQueryParameters?: boolean; + } +} /** [Normalize](https://en.wikipedia.org/wiki/URL_normalization) a URL. -URLs with custom protocols are not normalized and just passed through by default. Supported protocols are: `https`, `http`, `file`, and `data`. - @param url - URL to normalize, including [data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs). @example ``` -import normalizeUrl from 'normalize-url'; +import normalizeUrl = require('normalize-url'); normalizeUrl('sindresorhus.com'); //=> 'http://sindresorhus.com' @@ -298,4 +262,6 @@ normalizeUrl('//www.sindresorhus.com:80/../baz?b=bar&a=foo'); //=> 'http://sindresorhus.com/baz?a=foo&b=bar' ``` */ -export default function normalizeUrl(url: string, options?: Options): string; +declare function normalizeUrl(url: string, options?: normalizeUrl.Options): string; + +export = normalizeUrl; diff --git a/setup-pandoc/node_modules/normalize-url/index.js b/setup-pandoc/node_modules/normalize-url/index.js index 47ae24c7b..c9340ab94 100644 --- a/setup-pandoc/node_modules/normalize-url/index.js +++ b/setup-pandoc/node_modules/normalize-url/index.js @@ -1,22 +1,11 @@ +'use strict'; + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs const DATA_URL_DEFAULT_MIME_TYPE = 'text/plain'; const DATA_URL_DEFAULT_CHARSET = 'us-ascii'; -const testParameter = (name, filters) => filters.some(filter => filter instanceof RegExp ? filter.test(name) : filter === name); - -const supportedProtocols = new Set([ - 'https:', - 'http:', - 'file:', -]); - -const hasCustomProtocol = urlString => { - try { - const {protocol} = new URL(urlString); - return protocol.endsWith(':') && !supportedProtocols.has(protocol); - } catch { - return false; - } +const testParameter = (name, filters) => { + return filters.some(filter => filter instanceof RegExp ? filter.test(name) : filter === name); }; const normalizeDataURL = (urlString, {stripHash}) => { @@ -37,7 +26,7 @@ const normalizeDataURL = (urlString, {stripHash}) => { } // Lowercase MIME type - const mimeType = mediaType.shift()?.toLowerCase() ?? ''; + const mimeType = (mediaType.shift() || '').toLowerCase(); const attributes = mediaType .map(attribute => { let [key, value = ''] = attribute.split('=').map(string => string.trim()); @@ -56,23 +45,23 @@ const normalizeDataURL = (urlString, {stripHash}) => { .filter(Boolean); const normalizedMediaType = [ - ...attributes, + ...attributes ]; if (isBase64) { normalizedMediaType.push('base64'); } - if (normalizedMediaType.length > 0 || (mimeType && mimeType !== DATA_URL_DEFAULT_MIME_TYPE)) { + if (normalizedMediaType.length !== 0 || (mimeType && mimeType !== DATA_URL_DEFAULT_MIME_TYPE)) { normalizedMediaType.unshift(mimeType); } return `data:${normalizedMediaType.join(';')},${isBase64 ? data.trim() : data}${hash ? `#${hash}` : ''}`; }; -export default function normalizeUrl(urlString, options) { +const normalizeUrl = (urlString, options) => { options = { - defaultProtocol: 'http', + defaultProtocol: 'http:', normalizeProtocol: true, forceHttp: false, forceHttps: false, @@ -84,16 +73,10 @@ export default function normalizeUrl(urlString, options) { removeTrailingSlash: true, removeSingleSlash: true, removeDirectoryIndex: false, - removeExplicitPort: false, sortQueryParameters: true, - ...options, + ...options }; - // Legacy: Append `:` to the protocol if missing. - if (typeof options.defaultProtocol === 'string' && !options.defaultProtocol.endsWith(':')) { - options.defaultProtocol = `${options.defaultProtocol}:`; - } - urlString = urlString.trim(); // Data URL @@ -101,8 +84,8 @@ export default function normalizeUrl(urlString, options) { return normalizeDataURL(urlString, options); } - if (hasCustomProtocol(urlString)) { - return urlString; + if (/^view-source:/i.test(urlString)) { + throw new Error('`view-source:` is not supported as it is a non-standard protocol'); } const hasRelativeProtocol = urlString.startsWith('//'); @@ -113,73 +96,43 @@ export default function normalizeUrl(urlString, options) { urlString = urlString.replace(/^(?!(?:\w+:)?\/\/)|^\/\//, options.defaultProtocol); } - const urlObject = new URL(urlString); + const urlObj = new URL(urlString); if (options.forceHttp && options.forceHttps) { throw new Error('The `forceHttp` and `forceHttps` options cannot be used together'); } - if (options.forceHttp && urlObject.protocol === 'https:') { - urlObject.protocol = 'http:'; + if (options.forceHttp && urlObj.protocol === 'https:') { + urlObj.protocol = 'http:'; } - if (options.forceHttps && urlObject.protocol === 'http:') { - urlObject.protocol = 'https:'; + if (options.forceHttps && urlObj.protocol === 'http:') { + urlObj.protocol = 'https:'; } // Remove auth if (options.stripAuthentication) { - urlObject.username = ''; - urlObject.password = ''; + urlObj.username = ''; + urlObj.password = ''; } // Remove hash if (options.stripHash) { - urlObject.hash = ''; + urlObj.hash = ''; } else if (options.stripTextFragment) { - urlObject.hash = urlObject.hash.replace(/#?:~:text.*?$/i, ''); + urlObj.hash = urlObj.hash.replace(/#?:~:text.*?$/i, ''); } // Remove duplicate slashes if not preceded by a protocol - // NOTE: This could be implemented using a single negative lookbehind - // regex, but we avoid that to maintain compatibility with older js engines - // which do not have support for that feature. - if (urlObject.pathname) { - // TODO: Replace everything below with `urlObject.pathname = urlObject.pathname.replace(/(? 0) { - let pathComponents = urlObject.pathname.split('/'); + let pathComponents = urlObj.pathname.split('/'); const lastComponent = pathComponents[pathComponents.length - 1]; if (testParameter(lastComponent, options.removeDirectoryIndex)) { - pathComponents = pathComponents.slice(0, -1); - urlObject.pathname = pathComponents.slice(1).join('/') + '/'; + pathComponents = pathComponents.slice(0, pathComponents.length - 1); + urlObj.pathname = pathComponents.slice(1).join('/') + '/'; } } - if (urlObject.hostname) { + if (urlObj.hostname) { // Remove trailing dot - urlObject.hostname = urlObject.hostname.replace(/\.$/, ''); + urlObj.hostname = urlObj.hostname.replace(/\.$/, ''); // Remove `www.` - if (options.stripWWW && /^www\.(?!www\.)[a-z\-\d]{1,63}\.[a-z.\-\d]{2,63}$/.test(urlObject.hostname)) { + if (options.stripWWW && /^www\.(?!www\.)(?:[a-z\-\d]{1,63})\.(?:[a-z.\-\d]{2,63})$/.test(urlObj.hostname)) { // Each label should be max 63 at length (min: 1). // Source: https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names // Each TLD should be up to 63 characters long (min: 2). // It is technically possible to have a single character TLD, but none currently exist. - urlObject.hostname = urlObject.hostname.replace(/^www\./, ''); + urlObj.hostname = urlObj.hostname.replace(/^www\./, ''); } } // Remove query unwanted parameters if (Array.isArray(options.removeQueryParameters)) { - // eslint-disable-next-line unicorn/no-useless-spread -- We are intentionally spreading to get a copy. - for (const key of [...urlObject.searchParams.keys()]) { + for (const key of [...urlObj.searchParams.keys()]) { if (testParameter(key, options.removeQueryParameters)) { - urlObject.searchParams.delete(key); + urlObj.searchParams.delete(key); } } } - if (!Array.isArray(options.keepQueryParameters) && options.removeQueryParameters === true) { - urlObject.search = ''; - } - - // Keep wanted query parameters - if (Array.isArray(options.keepQueryParameters) && options.keepQueryParameters.length > 0) { - // eslint-disable-next-line unicorn/no-useless-spread -- We are intentionally spreading to get a copy. - for (const key of [...urlObject.searchParams.keys()]) { - if (!testParameter(key, options.keepQueryParameters)) { - urlObject.searchParams.delete(key); - } - } + if (options.removeQueryParameters === true) { + urlObj.search = ''; } // Sort query parameters if (options.sortQueryParameters) { - urlObject.searchParams.sort(); - - // Calling `.sort()` encodes the search parameters, so we need to decode them again. - try { - urlObject.search = decodeURIComponent(urlObject.search); - } catch {} + urlObj.searchParams.sort(); } if (options.removeTrailingSlash) { - urlObject.pathname = urlObject.pathname.replace(/\/$/, ''); - } - - // Remove an explicit port number, excluding a default port number, if applicable - if (options.removeExplicitPort && urlObject.port) { - urlObject.port = ''; + urlObj.pathname = urlObj.pathname.replace(/\/$/, ''); } const oldUrlString = urlString; // Take advantage of many of the Node `url` normalizations - urlString = urlObject.toString(); + urlString = urlObj.toString(); - if (!options.removeSingleSlash && urlObject.pathname === '/' && !oldUrlString.endsWith('/') && urlObject.hash === '') { + if (!options.removeSingleSlash && urlObj.pathname === '/' && !oldUrlString.endsWith('/') && urlObj.hash === '') { urlString = urlString.replace(/\/$/, ''); } // Remove ending `/` unless removeSingleSlash is false - if ((options.removeTrailingSlash || urlObject.pathname === '/') && urlObject.hash === '' && options.removeSingleSlash) { + if ((options.removeTrailingSlash || urlObj.pathname === '/') && urlObj.hash === '' && options.removeSingleSlash) { urlString = urlString.replace(/\/$/, ''); } @@ -279,4 +211,6 @@ export default function normalizeUrl(urlString, options) { } return urlString; -} +}; + +module.exports = normalizeUrl; diff --git a/setup-pandoc/node_modules/normalize-url/license b/setup-pandoc/node_modules/normalize-url/license index fa7ceba3e..e7af2f771 100644 --- a/setup-pandoc/node_modules/normalize-url/license +++ b/setup-pandoc/node_modules/normalize-url/license @@ -1,6 +1,6 @@ MIT License -Copyright (c) Sindre Sorhus (https://sindresorhus.com) +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: diff --git a/setup-pandoc/node_modules/normalize-url/package.json b/setup-pandoc/node_modules/normalize-url/package.json index 623991bbf..2670e4aa5 100644 --- a/setup-pandoc/node_modules/normalize-url/package.json +++ b/setup-pandoc/node_modules/normalize-url/package.json @@ -1,6 +1,6 @@ { "name": "normalize-url", - "version": "8.0.0", + "version": "6.1.0", "description": "Normalize a URL", "license": "MIT", "repository": "sindresorhus/normalize-url", @@ -10,16 +10,11 @@ "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, - "type": "module", - "exports": { - "types": "./index.d.ts", - "default": "./index.js" - }, "engines": { - "node": ">=14.16" + "node": ">=10" }, "scripts": { - "test": "xo && c8 ava && tsd" + "test": "xo && nyc ava && tsd" }, "files": [ "index.js", @@ -41,12 +36,12 @@ "canonical" ], "devDependencies": { - "ava": "^5.0.1", - "c8": "^7.12.0", - "tsd": "^0.24.1", - "xo": "^0.52.4" + "ava": "^2.4.0", + "nyc": "^15.0.0", + "tsd": "^0.11.0", + "xo": "^0.25.3" }, - "c8": { + "nyc": { "reporter": [ "text", "lcov" diff --git a/setup-pandoc/node_modules/normalize-url/readme.md b/setup-pandoc/node_modules/normalize-url/readme.md index a04c8b64b..4b29b2919 100644 --- a/setup-pandoc/node_modules/normalize-url/readme.md +++ b/setup-pandoc/node_modules/normalize-url/readme.md @@ -4,20 +4,18 @@ Useful when you need to display, store, deduplicate, sort, compare, etc, URLs. -**Note:** This package does **not** do URL sanitization. [Garbage in, garbage out.](https://en.wikipedia.org/wiki/Garbage_in,_garbage_out) If you use this in a server context and accept URLs as user input, it's up to you to protect against invalid URLs, [path traversal attacks](https://owasp.org/www-community/attacks/Path_Traversal), etc. - ## Install -```sh -npm install normalize-url +``` +$ npm install normalize-url ``` -*If you need Safari support, use version 4: `npm i normalize-url@4`* +*If you need to use this in the browser, use version 4: `npm i normalize-url@4`* ## Usage ```js -import normalizeUrl from 'normalize-url'; +const normalizeUrl = require('normalize-url'); normalizeUrl('sindresorhus.com'); //=> 'http://sindresorhus.com' @@ -30,8 +28,6 @@ normalizeUrl('//www.sindresorhus.com:80/../baz?b=bar&a=foo'); ### normalizeUrl(url, options?) -URLs with custom protocols are not normalized and just passed through by default. Supported protocols are: `https`, `http`, `file`, and `data`. - #### url Type: `string` @@ -45,8 +41,7 @@ Type: `object` ##### defaultProtocol Type: `string`\ -Default: `'http'`\ -Values: `'https' | 'http'` +Default: `http:` ##### normalizeProtocol @@ -56,10 +51,10 @@ Default: `true` Prepend `defaultProtocol` to the URL if it's protocol-relative. ```js -normalizeUrl('//sindresorhus.com'); +normalizeUrl('//sindresorhus.com:80/'); //=> 'http://sindresorhus.com' -normalizeUrl('//sindresorhus.com', {normalizeProtocol: false}); +normalizeUrl('//sindresorhus.com:80/', {normalizeProtocol: false}); //=> '//sindresorhus.com' ``` @@ -68,13 +63,13 @@ normalizeUrl('//sindresorhus.com', {normalizeProtocol: false}); Type: `boolean`\ Default: `false` -Normalize HTTPS to HTTP. +Normalize `https:` to `http:`. ```js -normalizeUrl('https://sindresorhus.com'); +normalizeUrl('https://sindresorhus.com:80/'); //=> 'https://sindresorhus.com' -normalizeUrl('https://sindresorhus.com', {forceHttp: true}); +normalizeUrl('https://sindresorhus.com:80/', {forceHttp: true}); //=> 'http://sindresorhus.com' ``` @@ -83,17 +78,17 @@ normalizeUrl('https://sindresorhus.com', {forceHttp: true}); Type: `boolean`\ Default: `false` -Normalize HTTP to HTTPS. +Normalize `http:` to `https:`. ```js -normalizeUrl('http://sindresorhus.com'); -//=> 'http://sindresorhus.com' +normalizeUrl('https://sindresorhus.com:80/'); +//=> 'https://sindresorhus.com' -normalizeUrl('http://sindresorhus.com', {forceHttps: true}); +normalizeUrl('http://sindresorhus.com:80/', {forceHttps: true}); //=> 'https://sindresorhus.com' ``` -This option cannot be used with the `forceHttp` option at the same time. +This option can't be used with the `forceHttp` option at the same time. ##### stripAuthentication @@ -130,9 +125,7 @@ normalizeUrl('sindresorhus.com/about.html#contact', {stripHash: true}); Type: `boolean`\ Default: `false` -Remove the protocol from the URL: `http://sindresorhus.com` → `sindresorhus.com`. - -It will only remove `https://` and `http://` protocols. +Remove HTTP(S) protocol from the URL: `http://sindresorhus.com` → `sindresorhus.com`. ```js normalizeUrl('https://sindresorhus.com'); @@ -212,22 +205,6 @@ normalizeUrl('www.sindresorhus.com?foo=bar&utm_medium=test&ref=test_ref', { //=> 'http://www.sindresorhus.com/?foo=bar&ref=test_ref&utm_medium=test' ``` -##### keepQueryParameters - -Type: `Array`\ -Default: `undefined` - -Keeps only query parameters that matches any of the provided strings or regexes. - -**Note:** It overrides the `removeQueryParameters` option. - -```js -normalizeUrl('https://sindresorhus.com?foo=bar&ref=unicorn', { - keepQueryParameters: ['ref'] -}); -//=> 'https://sindresorhus.com/?ref=unicorn' -``` - ##### removeTrailingSlash Type: `boolean`\ @@ -253,7 +230,7 @@ normalizeUrl('http://sindresorhus.com/', {removeTrailingSlash: false}); Type: `boolean`\ Default: `true` -Remove a sole `/` pathname in the output. This option is independent of `removeTrailingSlash`. +Remove a sole `/` pathname in the output. This option is independant of `removeTrailingSlash`. ```js normalizeUrl('https://sindresorhus.com/'); @@ -263,6 +240,7 @@ normalizeUrl('https://sindresorhus.com/', {removeSingleSlash: false}); //=> 'https://sindresorhus.com/' ``` + ##### removeDirectoryIndex Type: `boolean | Array`\ @@ -277,22 +255,6 @@ normalizeUrl('www.sindresorhus.com/foo/default.php', { //=> 'http://sindresorhus.com/foo' ``` -##### removeExplicitPort - -Type: `boolean`\ -Default: `false` - -Removes an explicit port number from the URL. - -Port 443 is always removed from HTTPS URLs and 80 is always removed from HTTP URLs regardless of this option. - -```js -normalizeUrl('sindresorhus.com:123', { - removeExplicitPort: true -}); -//=> 'http://sindresorhus.com' -``` - ##### sortQueryParameters Type: `boolean`\ diff --git a/setup-pandoc/node_modules/p-cancelable/index.d.ts b/setup-pandoc/node_modules/p-cancelable/index.d.ts index de1c916af..8e0c9efd6 100644 --- a/setup-pandoc/node_modules/p-cancelable/index.d.ts +++ b/setup-pandoc/node_modules/p-cancelable/index.d.ts @@ -1,27 +1,25 @@ -/** -The rejection reason when `.cancel()` is called. - -It includes a `.isCanceled` property for convenience. -*/ -export class CancelError extends Error { +declare class CancelErrorClass extends Error { readonly name: 'CancelError'; readonly isCanceled: true; constructor(reason?: string); } -/** -Accepts a function that is called when the promise is canceled. +declare namespace PCancelable { + /** + Accepts a function that is called when the promise is canceled. -You're not required to call this function. You can call this function multiple times to add multiple cancel handlers. -*/ -export interface OnCancelFunction { - (cancelHandler: () => void): void; - shouldReject: boolean; + You're not required to call this function. You can call this function multiple times to add multiple cancel handlers. + */ + interface OnCancelFunction { + (cancelHandler: () => void): void; + shouldReject: boolean; + } + + type CancelError = CancelErrorClass; } -// eslint-disable-next-line @typescript-eslint/naming-convention -export default class PCancelable extends Promise { +declare class PCancelable extends Promise { /** Convenience method to make your promise-returning or async function cancelable. @@ -29,7 +27,7 @@ export default class PCancelable extends Promise { @example ``` - import PCancelable from 'p-cancelable'; + import PCancelable = require('p-cancelable'); const fn = PCancelable.fn((input, onCancel) => { const job = new Job(); @@ -49,19 +47,19 @@ export default class PCancelable extends Promise { ``` */ static fn( - userFn: (onCancel: OnCancelFunction) => PromiseLike + userFn: (onCancel: PCancelable.OnCancelFunction) => PromiseLike ): () => PCancelable; static fn( userFn: ( argument1: Agument1Type, - onCancel: OnCancelFunction + onCancel: PCancelable.OnCancelFunction ) => PromiseLike ): (argument1: Agument1Type) => PCancelable; static fn( userFn: ( argument1: Agument1Type, argument2: Agument2Type, - onCancel: OnCancelFunction + onCancel: PCancelable.OnCancelFunction ) => PromiseLike ): ( argument1: Agument1Type, @@ -72,7 +70,7 @@ export default class PCancelable extends Promise { argument1: Agument1Type, argument2: Agument2Type, argument3: Agument3Type, - onCancel: OnCancelFunction + onCancel: PCancelable.OnCancelFunction ) => PromiseLike ): ( argument1: Agument1Type, @@ -85,7 +83,7 @@ export default class PCancelable extends Promise { argument2: Agument2Type, argument3: Agument3Type, argument4: Agument4Type, - onCancel: OnCancelFunction + onCancel: PCancelable.OnCancelFunction ) => PromiseLike ): ( argument1: Agument1Type, @@ -99,7 +97,7 @@ export default class PCancelable extends Promise { Agument3Type, Agument4Type, Agument5Type, - ReturnType, + ReturnType >( userFn: ( argument1: Agument1Type, @@ -107,7 +105,7 @@ export default class PCancelable extends Promise { argument3: Agument3Type, argument4: Agument4Type, argument5: Agument5Type, - onCancel: OnCancelFunction + onCancel: PCancelable.OnCancelFunction ) => PromiseLike ): ( argument1: Agument1Type, @@ -120,20 +118,6 @@ export default class PCancelable extends Promise { userFn: (...arguments: unknown[]) => PromiseLike ): (...arguments: unknown[]) => PCancelable; - /** - Whether the promise is canceled. - */ - readonly isCanceled: boolean; - - /** - Cancel the promise and optionally provide a reason. - - The cancellation is synchronous. Calling it after the promise has settled or multiple times does nothing. - - @param reason - The cancellation reason to reject the promise with. - */ - cancel: (reason?: string) => void; - /** Create a promise that can be canceled. @@ -143,7 +127,7 @@ export default class PCancelable extends Promise { @example ``` - import PCancelable from 'p-cancelable'; + import PCancelable = require('p-cancelable'); const cancelablePromise = new PCancelable((resolve, reject, onCancel) => { const job = new Job(); @@ -163,7 +147,30 @@ export default class PCancelable extends Promise { executor: ( resolve: (value?: ValueType | PromiseLike) => void, reject: (reason?: unknown) => void, - onCancel: OnCancelFunction + onCancel: PCancelable.OnCancelFunction ) => void ); + + /** + Whether the promise is canceled. + */ + readonly isCanceled: boolean; + + /** + Cancel the promise and optionally provide a reason. + + The cancellation is synchronous. Calling it after the promise has settled or multiple times does nothing. + + @param reason - The cancellation reason to reject the promise with. + */ + cancel: (reason?: string) => void; + + /** + Rejection reason when `.cancel()` is called. + + It includes a `.isCanceled` property for convenience. + */ + static CancelError: typeof CancelErrorClass; } + +export = PCancelable; diff --git a/setup-pandoc/node_modules/p-cancelable/index.js b/setup-pandoc/node_modules/p-cancelable/index.js index c48660ea0..186adcee5 100644 --- a/setup-pandoc/node_modules/p-cancelable/index.js +++ b/setup-pandoc/node_modules/p-cancelable/index.js @@ -1,4 +1,6 @@ -export class CancelError extends Error { +'use strict'; + +class CancelError extends Error { constructor(reason) { super(reason || 'Promise was canceled'); this.name = 'CancelError'; @@ -9,111 +11,101 @@ export class CancelError extends Error { } } -const promiseState = Object.freeze({ - pending: Symbol('pending'), - canceled: Symbol('canceled'), - resolved: Symbol('resolved'), - rejected: Symbol('rejected'), -}); - -export default class PCancelable { - static fn(userFunction) { - return (...arguments_) => new PCancelable((resolve, reject, onCancel) => { - arguments_.push(onCancel); - userFunction(...arguments_).then(resolve, reject); - }); +class PCancelable { + static fn(userFn) { + return (...arguments_) => { + return new PCancelable((resolve, reject, onCancel) => { + arguments_.push(onCancel); + // eslint-disable-next-line promise/prefer-await-to-then + userFn(...arguments_).then(resolve, reject); + }); + }; } - #cancelHandlers = []; - #rejectOnCancel = true; - #state = promiseState.pending; - #promise; - #reject; - constructor(executor) { - this.#promise = new Promise((resolve, reject) => { - this.#reject = reject; + this._cancelHandlers = []; + this._isPending = true; + this._isCanceled = false; + this._rejectOnCancel = true; + + this._promise = new Promise((resolve, reject) => { + this._reject = reject; const onResolve = value => { - if (this.#state !== promiseState.canceled || !onCancel.shouldReject) { + if (!this._isCanceled || !onCancel.shouldReject) { + this._isPending = false; resolve(value); - this.#setState(promiseState.resolved); } }; const onReject = error => { - if (this.#state !== promiseState.canceled || !onCancel.shouldReject) { - reject(error); - this.#setState(promiseState.rejected); - } + this._isPending = false; + reject(error); }; const onCancel = handler => { - if (this.#state !== promiseState.pending) { - throw new Error(`The \`onCancel\` handler was attached after the promise ${this.#state.description}.`); + if (!this._isPending) { + throw new Error('The `onCancel` handler was attached after the promise settled.'); } - this.#cancelHandlers.push(handler); + this._cancelHandlers.push(handler); }; Object.defineProperties(onCancel, { shouldReject: { - get: () => this.#rejectOnCancel, + get: () => this._rejectOnCancel, set: boolean => { - this.#rejectOnCancel = boolean; - }, - }, + this._rejectOnCancel = boolean; + } + } }); - executor(onResolve, onReject, onCancel); + return executor(onResolve, onReject, onCancel); }); } - // eslint-disable-next-line unicorn/no-thenable then(onFulfilled, onRejected) { - return this.#promise.then(onFulfilled, onRejected); + // eslint-disable-next-line promise/prefer-await-to-then + return this._promise.then(onFulfilled, onRejected); } catch(onRejected) { - return this.#promise.catch(onRejected); + return this._promise.catch(onRejected); } finally(onFinally) { - return this.#promise.finally(onFinally); + return this._promise.finally(onFinally); } cancel(reason) { - if (this.#state !== promiseState.pending) { + if (!this._isPending || this._isCanceled) { return; } - this.#setState(promiseState.canceled); + this._isCanceled = true; - if (this.#cancelHandlers.length > 0) { + if (this._cancelHandlers.length > 0) { try { - for (const handler of this.#cancelHandlers) { + for (const handler of this._cancelHandlers) { handler(); } } catch (error) { - this.#reject(error); + this._reject(error); return; } } - if (this.#rejectOnCancel) { - this.#reject(new CancelError(reason)); + if (this._rejectOnCancel) { + this._reject(new CancelError(reason)); } } get isCanceled() { - return this.#state === promiseState.canceled; - } - - #setState(state) { - if (this.#state === promiseState.pending) { - this.#state = state; - } + return this._isCanceled; } } Object.setPrototypeOf(PCancelable.prototype, Promise.prototype); + +module.exports = PCancelable; +module.exports.CancelError = CancelError; diff --git a/setup-pandoc/node_modules/p-cancelable/license b/setup-pandoc/node_modules/p-cancelable/license index fa7ceba3e..e7af2f771 100644 --- a/setup-pandoc/node_modules/p-cancelable/license +++ b/setup-pandoc/node_modules/p-cancelable/license @@ -1,6 +1,6 @@ MIT License -Copyright (c) Sindre Sorhus (https://sindresorhus.com) +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: diff --git a/setup-pandoc/node_modules/p-cancelable/package.json b/setup-pandoc/node_modules/p-cancelable/package.json index 1b630cb7f..aa6a00659 100644 --- a/setup-pandoc/node_modules/p-cancelable/package.json +++ b/setup-pandoc/node_modules/p-cancelable/package.json @@ -1,18 +1,16 @@ { "name": "p-cancelable", - "version": "4.0.1", + "version": "2.1.1", "description": "Create a promise that can be canceled", "license": "MIT", "repository": "sindresorhus/p-cancelable", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", - "url": "https://sindresorhus.com" + "url": "sindresorhus.com" }, - "type": "module", - "exports": "./index.js", "engines": { - "node": ">=14.16" + "node": ">=8" }, "scripts": { "test": "xo && ava && tsd" @@ -42,9 +40,10 @@ "bluebird" ], "devDependencies": { - "ava": "^4.2.0", - "delay": "^5.0.0", - "tsd": "^0.20.0", - "xo": "^0.48.0" + "ava": "^1.4.1", + "delay": "^4.1.0", + "promise.prototype.finally": "^3.1.0", + "tsd": "^0.7.1", + "xo": "^0.24.0" } } diff --git a/setup-pandoc/node_modules/p-cancelable/readme.md b/setup-pandoc/node_modules/p-cancelable/readme.md index b5f17512c..0690cfaec 100644 --- a/setup-pandoc/node_modules/p-cancelable/readme.md +++ b/setup-pandoc/node_modules/p-cancelable/readme.md @@ -4,18 +4,18 @@ Useful for animation, loading resources, long-running async computations, async iteration, etc. -*If you target [Node.js 16](https://medium.com/@nodejs/node-js-v15-0-0-is-here-deb00750f278) or later, this package is [less useful](https://github.com/sindresorhus/p-cancelable/issues/27) and you should probably use [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) instead.* +*If you target [Node.js 15](https://medium.com/@nodejs/node-js-v15-0-0-is-here-deb00750f278) or later, this package is [less useful](https://github.com/sindresorhus/p-cancelable/issues/27) and you should probably use [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) instead.* ## Install -```sh -npm install p-cancelable +``` +$ npm install p-cancelable ``` ## Usage ```js -import PCancelable from 'p-cancelable'; +const PCancelable = require('p-cancelable'); const cancelablePromise = new PCancelable((resolve, reject, onCancel) => { const worker = new SomeLongRunningOperation(); @@ -28,34 +28,35 @@ const cancelablePromise = new PCancelable((resolve, reject, onCancel) => { worker.on('error', reject); }); +(async () => { + try { + console.log('Operation finished successfully:', await cancelablePromise); + } catch (error) { + if (cancelablePromise.isCanceled) { + // Handle the cancelation here + console.log('Operation was canceled'); + return; + } + + throw error; + } +})(); + // Cancel the operation after 10 seconds setTimeout(() => { cancelablePromise.cancel('Unicorn has changed its color'); }, 10000); - -try { - console.log('Operation finished successfully:', await cancelablePromise); -} catch (error) { - if (cancelablePromise.isCanceled) { - // Handle the cancelation here - console.log('Operation was canceled'); - return; - } - - throw error; -} ``` ## API ### new PCancelable(executor) -Same as the [`Promise` constructor](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise), but with an appended `onCancel` parameter in `executor`. - -Cancelling will reject the promise with `CancelError`. To avoid that, set `onCancel.shouldReject` to `false`. +Same as the [`Promise` constructor](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise), but with an appended `onCancel` parameter in `executor`.
+Cancelling will reject the promise with `PCancelable.CancelError`. To avoid that, set `onCancel.shouldReject` to `false`. ```js -import PCancelable from 'p-cancelable'; +const PCancelable = require('p-cancelable'); const cancelablePromise = new PCancelable((resolve, reject, onCancel) => { const job = new Job(); @@ -95,6 +96,14 @@ Type: `boolean` Whether the promise is canceled. +### PCancelable.CancelError + +Type: `Error` + +Rejection reason when `.cancel()` is called. + +It includes a `.isCanceled` property for convenience. + ### PCancelable.fn(fn) Convenience method to make your promise-returning or async function cancelable. @@ -102,7 +111,7 @@ Convenience method to make your promise-returning or async function cancelable. The function you specify will have `onCancel` appended to its parameters. ```js -import PCancelable from 'p-cancelable'; +const PCancelable = require('p-cancelable'); const fn = PCancelable.fn((input, onCancel) => { const job = new Job(); @@ -121,19 +130,11 @@ const cancelablePromise = fn('input'); //=> PCancelable cancelablePromise.cancel(); ``` -### CancelError - -Type: `Error` - -Rejection reason when `.cancel()` is called. - -It includes a `.isCanceled` property for convenience. - ## FAQ ### Cancelable vs. Cancellable -[In American English, the verb cancel is usually inflected canceled and canceling—with one l.](http://grammarist.com/spelling/cancel/) Both a [browser API](https://developer.mozilla.org/en-US/docs/Web/API/Event/cancelable) and the [Cancelable Promises proposal](https://github.com/tc39/proposal-cancelable-promises) use this spelling. +[In American English, the verb cancel is usually inflected canceled and canceling—with one l.](http://grammarist.com/spelling/cancel/)
Both a [browser API](https://developer.mozilla.org/en-US/docs/Web/API/Event/cancelable) and the [Cancelable Promises proposal](https://github.com/tc39/proposal-cancelable-promises) use this spelling. ### What about the official [Cancelable Promises proposal](https://github.com/tc39/proposal-cancelable-promises)? diff --git a/setup-pandoc/node_modules/responselike/index.d.ts b/setup-pandoc/node_modules/responselike/index.d.ts deleted file mode 100644 index c99c4db2c..000000000 --- a/setup-pandoc/node_modules/responselike/index.d.ts +++ /dev/null @@ -1,86 +0,0 @@ -import {Buffer} from 'node:buffer'; -import {Readable as ReadableStream} from 'node:stream'; - -export type Options = { - /** - The HTTP response status code. - */ - readonly statusCode: number; - - /** - The HTTP headers object. - - Keys are in lowercase. - */ - readonly headers: Record; - - /** - The response body. - - The contents will be streamable but is also exposed directly as `response.body`. - */ - readonly body: Buffer; - - /** - The request URL string. - */ - readonly url: string; -}; - -/** -Returns a streamable response object similar to a [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage). - -@example -``` -import Response from 'responselike'; - -const response = new Response({ - statusCode: 200, - headers: { - foo: 'bar' - }, - body: Buffer.from('Hi!'), - url: 'https://example.com' -}); - -response.statusCode; -// 200 - -response.headers; -// {foo: 'bar'} - -response.body; -// - -response.url; -// 'https://example.com' - -response.pipe(process.stdout); -// 'Hi!' -``` -*/ -export default class Response extends ReadableStream { - /** - The HTTP response status code. - */ - readonly statusCode: number; - - /** - The HTTP headers. - - Keys will be automatically lowercased. - */ - readonly headers: Record; - - /** - The response body. - */ - readonly body: Buffer; - - /** - The request URL string. - */ - readonly url: string; - - constructor(options?: Options); -} diff --git a/setup-pandoc/node_modules/responselike/license b/setup-pandoc/node_modules/responselike/license index feeb70fa1..8829a001a 100644 --- a/setup-pandoc/node_modules/responselike/license +++ b/setup-pandoc/node_modules/responselike/license @@ -1,10 +1,19 @@ -MIT License +Copyright (c) 2017 Luke Childs -Copyright (c) Sindre Sorhus (https://sindresorhus.com) -Copyright (c) Luke Childs (https://lukechilds.co.uk) +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: -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 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. +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/setup-pandoc/node_modules/responselike/package.json b/setup-pandoc/node_modules/responselike/package.json index c9d873a89..ee885f0ba 100644 --- a/setup-pandoc/node_modules/responselike/package.json +++ b/setup-pandoc/node_modules/responselike/package.json @@ -1,39 +1,39 @@ { - "name": "responselike", - "version": "3.0.0", - "description": "A response-like object for mocking a Node.js HTTP response stream", - "license": "MIT", - "repository": "sindresorhus/responselike", - "funding": "https://github.com/sponsors/sindresorhus", - "author": "Luke Childs (https://lukechilds.co.uk)", - "type": "module", - "exports": "./index.js", - "engines": { - "node": ">=14.16" - }, - "scripts": { - "test": "xo && ava && tsd" - }, - "files": [ - "index.js", - "index.d.ts" - ], - "keywords": [ - "http", - "https", - "response", - "mock", - "test", - "request", - "responselike" - ], - "dependencies": { - "lowercase-keys": "^3.0.0" - }, - "devDependencies": { - "ava": "^4.3.1", - "get-stream": "^6.0.1", - "tsd": "^0.22.0", - "xo": "^0.50.0" - } + "name": "responselike", + "version": "2.0.1", + "description": "A response-like object for mocking a Node.js HTTP response stream", + "funding": "https://github.com/sponsors/sindresorhus", + "main": "src/index.js", + "scripts": { + "test": "xo && nyc ava", + "coverage": "nyc report --reporter=text-lcov | coveralls" + }, + "xo": { + "extends": "xo-lukechilds" + }, + "keywords": [ + "http", + "https", + "response", + "mock", + "request", + "responselike" + ], + "repository": { + "type": "git", + "url": "https://github.com/sindresorhus/responselike.git" + }, + "author": "lukechilds", + "license": "MIT", + "devDependencies": { + "ava": "^0.25.0", + "coveralls": "^3.0.0", + "eslint-config-xo-lukechilds": "^1.0.0", + "get-stream": "^3.0.0", + "nyc": "^11.8.0", + "xo": "^0.19.0" + }, + "dependencies": { + "lowercase-keys": "^2.0.0" + } } diff --git a/setup-pandoc/node_modules/responselike/readme.md b/setup-pandoc/node_modules/responselike/readme.md index 51b5ecd63..6361931c1 100644 --- a/setup-pandoc/node_modules/responselike/readme.md +++ b/setup-pandoc/node_modules/responselike/readme.md @@ -2,74 +2,76 @@ > A response-like object for mocking a Node.js HTTP response stream +[![Build Status](https://travis-ci.org/lukechilds/responselike.svg?branch=master)](https://travis-ci.org/lukechilds/responselike) +[![Coverage Status](https://coveralls.io/repos/github/lukechilds/responselike/badge.svg?branch=master)](https://coveralls.io/github/lukechilds/responselike?branch=master) +[![npm](https://img.shields.io/npm/dm/responselike.svg)](https://www.npmjs.com/package/responselike) +[![npm](https://img.shields.io/npm/v/responselike.svg)](https://www.npmjs.com/package/responselike) + Returns a streamable response object similar to a [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage). Useful for formatting cached responses so they can be consumed by code expecting a real response. ## Install -```sh -npm install responselike +```shell +npm install --save responselike +``` + +Or if you're just using for testing you'll want: + +```shell +npm install --save-dev responselike ``` ## Usage ```js -import Response from 'responselike'; +const Response = require('responselike'); -const response = new Response({ - statusCode: 200, - headers: { - foo: 'bar' - }, - body: Buffer.from('Hi!'), - url: 'https://example.com' -}); +const response = new Response(200, { foo: 'bar' }, Buffer.from('Hi!'), 'https://example.com'); response.statusCode; // 200 - response.headers; -// {foo: 'bar'} - +// { foo: 'bar' } response.body; // - response.url; // 'https://example.com' response.pipe(process.stdout); -// 'Hi!' +// Hi! ``` + ## API -### new Response(options?) +### new Response(statusCode, headers, body, url) Returns a streamable response object similar to a [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage). -#### options - -Type: `object` - -##### statusCode +#### statusCode Type: `number` -The HTTP response status code. +HTTP response status code. -##### headers +#### headers Type: `object` -The HTTP headers. Keys will be automatically lowercased. +HTTP headers object. Keys will be automatically lowercased. -##### body +#### body -Type: `Buffer` +Type: `buffer` -The response body. The Buffer contents will be streamable but is also exposed directly as `response.body`. +A Buffer containing the response body. The Buffer contents will be streamable but is also exposed directly as `response.body`. -##### url +#### url Type: `string` -The request URL string. +Request URL string. + +## License + +MIT © Luke Childs diff --git a/setup-pandoc/node_modules/responselike/index.js b/setup-pandoc/node_modules/responselike/src/index.js similarity index 58% rename from setup-pandoc/node_modules/responselike/index.js rename to setup-pandoc/node_modules/responselike/src/index.js index 6e2d40b67..b17b4813a 100644 --- a/setup-pandoc/node_modules/responselike/index.js +++ b/setup-pandoc/node_modules/responselike/src/index.js @@ -1,39 +1,34 @@ -import {Readable as ReadableStream} from 'node:stream'; -import lowercaseKeys from 'lowercase-keys'; +'use strict'; -export default class Response extends ReadableStream { - statusCode; - headers; - body; - url; +const Readable = require('stream').Readable; +const lowercaseKeys = require('lowercase-keys'); - constructor({statusCode, headers, body, url}) { +class Response extends Readable { + constructor(statusCode, headers, body, url) { if (typeof statusCode !== 'number') { throw new TypeError('Argument `statusCode` should be a number'); } - if (typeof headers !== 'object') { throw new TypeError('Argument `headers` should be an object'); } - - if (!(body instanceof Uint8Array)) { + if (!(body instanceof Buffer)) { throw new TypeError('Argument `body` should be a buffer'); } - if (typeof url !== 'string') { throw new TypeError('Argument `url` should be a string'); } - super({ - read() { - this.push(body); - this.push(null); - }, - }); - + super(); this.statusCode = statusCode; this.headers = lowercaseKeys(headers); this.body = body; this.url = url; } + + _read() { + this.push(this.body); + this.push(null); + } } + +module.exports = Response; diff --git a/setup-pandoc/package-lock.json b/setup-pandoc/package-lock.json index 7904e1419..3a82dd532 100644 --- a/setup-pandoc/package-lock.json +++ b/setup-pandoc/package-lock.json @@ -14,7 +14,7 @@ "@actions/io": "^1.1.3", "@actions/tool-cache": "^2.0.1", "compare-versions": "^4.0.1", - "got": "^14.2.0" + "got": "^11.8.3" }, "devDependencies": { "@types/jest": "^29.2.0", @@ -1322,11 +1322,11 @@ "dev": true }, "node_modules/@sindresorhus/is": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-6.1.0.tgz", - "integrity": "sha512-BuvU07zq3tQ/2SIgBsEuxKYDyDjC0n7Zir52bpHy2xnBbW81+po43aLFPLbeV3HRAheFbGud1qgcqSYfhtHMAg==", + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-4.6.0.tgz", + "integrity": "sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw==", "engines": { - "node": ">=16" + "node": ">=10" }, "funding": { "url": "https://github.com/sindresorhus/is?sponsor=1" @@ -1351,14 +1351,14 @@ } }, "node_modules/@szmarczak/http-timer": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/@szmarczak/http-timer/-/http-timer-5.0.1.tgz", - "integrity": "sha512-+PmQX0PiAYPMeVYe237LJAYvOMYW1j2rH5YROyS3b4CTVJum34HfRvKvAzozHAQG0TnHNdUfY9nCeUyRAs//cw==", + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/@szmarczak/http-timer/-/http-timer-4.0.6.tgz", + "integrity": "sha512-4BAffykYOgO+5nzBWYwE3W90sBgLJoUPRWWcL8wlyiM8IB8ipJz3UMJ9KXQd1RKQXpKp8Tutn80HZtWsu2u76w==", "dependencies": { - "defer-to-connect": "^2.0.1" + "defer-to-connect": "^2.0.0" }, "engines": { - "node": ">=14.16" + "node": ">=10" } }, "node_modules/@types/babel__core": { @@ -1402,6 +1402,17 @@ "@babel/types": "^7.20.7" } }, + "node_modules/@types/cacheable-request": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/@types/cacheable-request/-/cacheable-request-6.0.3.tgz", + "integrity": "sha512-IQ3EbTzGxIigb1I3qPZc1rWJnH0BmSKv5QYTalEwweFvyBDLSAe24zP0le/hyi7ecGfZVlIVAg4BZqb8WBwKqw==", + "dependencies": { + "@types/http-cache-semantics": "*", + "@types/keyv": "^3.1.4", + "@types/node": "*", + "@types/responselike": "^1.0.0" + } + }, "node_modules/@types/graceful-fs": { "version": "4.1.9", "resolved": "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.9.tgz", @@ -1450,11 +1461,18 @@ "pretty-format": "^29.0.0" } }, + "node_modules/@types/keyv": { + "version": "3.1.4", + "resolved": "https://registry.npmjs.org/@types/keyv/-/keyv-3.1.4.tgz", + "integrity": "sha512-BQ5aZNSCpj7D6K2ksrRCTmKRLEpnPvWDiLPfoGyhZ++8YtiK9d/3DBKPJgry359X/P1PfruyYwvnvwFjuEiEIg==", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/node": { "version": "16.18.76", "resolved": "https://registry.npmjs.org/@types/node/-/node-16.18.76.tgz", - "integrity": "sha512-/GsO2uv1Z6R42lBr59dtem56gVF/yHKQaScggwU+gLU6DXE25sDmOar4c4IfWb3h+X/7OYZznPOFk7oGF3jQSA==", - "dev": true + "integrity": "sha512-/GsO2uv1Z6R42lBr59dtem56gVF/yHKQaScggwU+gLU6DXE25sDmOar4c4IfWb3h+X/7OYZznPOFk7oGF3jQSA==" }, "node_modules/@types/normalize-package-data": { "version": "2.4.4", @@ -1462,6 +1480,14 @@ "integrity": "sha512-37i+OaWTh9qeK4LSHPsyRC7NahnGotNuZvjLSgcPzblpHB3rrCJxAOgI5gCdKm7coonsaX1Of0ILiTcnZjbfxA==", "dev": true }, + "node_modules/@types/responselike": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@types/responselike/-/responselike-1.0.3.tgz", + "integrity": "sha512-H/+L+UkTV33uf49PH5pCAUBVPNj2nDBXTN+qS1dOwyyg24l3CcicicCA7ca+HMvJBZcFgl5r8e+RR6elsb4Lyw==", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/stack-utils": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.3.tgz", @@ -1806,36 +1832,39 @@ "dev": true }, "node_modules/cacheable-lookup": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/cacheable-lookup/-/cacheable-lookup-7.0.0.tgz", - "integrity": "sha512-+qJyx4xiKra8mZrcwhjMRMUhD5NR1R8esPkzIYxX96JiecFoxAXFuz/GpR3+ev4PE1WamHip78wV0vcmPQtp8w==", + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/cacheable-lookup/-/cacheable-lookup-5.0.4.tgz", + "integrity": "sha512-2/kNscPhpcxrOigMZzbiWF7dz8ilhb/nIHU3EyZiXWXpeq/au8qJ8VhdftMkty3n7Gj6HIGalQG8oiBNB3AJgA==", "engines": { - "node": ">=14.16" + "node": ">=10.6.0" } }, "node_modules/cacheable-request": { - "version": "10.2.14", - "resolved": "https://registry.npmjs.org/cacheable-request/-/cacheable-request-10.2.14.tgz", - "integrity": "sha512-zkDT5WAF4hSSoUgyfg5tFIxz8XQK+25W/TLVojJTMKBaxevLBBtLxgqguAuVQB8PVW79FVjHcU+GJ9tVbDZ9mQ==", + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/cacheable-request/-/cacheable-request-7.0.4.tgz", + "integrity": "sha512-v+p6ongsrp0yTGbJXjgxPow2+DL93DASP4kXCDKb8/bwRtt9OEF3whggkkDkGNzgcWy2XaF4a8nZglC7uElscg==", "dependencies": { - "@types/http-cache-semantics": "^4.0.2", - "get-stream": "^6.0.1", - "http-cache-semantics": "^4.1.1", - "keyv": "^4.5.3", - "mimic-response": "^4.0.0", - "normalize-url": "^8.0.0", - "responselike": "^3.0.0" + "clone-response": "^1.0.2", + "get-stream": "^5.1.0", + "http-cache-semantics": "^4.0.0", + "keyv": "^4.0.0", + "lowercase-keys": "^2.0.0", + "normalize-url": "^6.0.1", + "responselike": "^2.0.0" }, "engines": { - "node": ">=14.16" + "node": ">=8" } }, "node_modules/cacheable-request/node_modules/get-stream": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", - "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz", + "integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==", + "dependencies": { + "pump": "^3.0.0" + }, "engines": { - "node": ">=10" + "node": ">=8" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" @@ -1952,6 +1981,17 @@ "node": ">=12" } }, + "node_modules/clone-response": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/clone-response/-/clone-response-1.0.3.tgz", + "integrity": "sha512-ROoL94jJH2dUVML2Y/5PEDNaSHgeOdSDicUyS7izcF63G6sTc/FTjLub4b8Il9S8S0beOfYt0TaA5qvFK+w0wA==", + "dependencies": { + "mimic-response": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/co": { "version": "4.6.0", "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", @@ -2250,7 +2290,6 @@ "version": "1.4.4", "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz", "integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==", - "dev": true, "dependencies": { "once": "^1.4.0" } @@ -2378,14 +2417,6 @@ "node": ">=8" } }, - "node_modules/form-data-encoder": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/form-data-encoder/-/form-data-encoder-4.0.2.tgz", - "integrity": "sha512-KQVhvhK8ZkWzxKxOr56CPulAhH3dobtuQ4+hNQ+HekH/Wp5gSOafqRAeTphQUJAIk0GBvHZgJ2ZGRWd5kphMuw==", - "engines": { - "node": ">= 18" - } - }, "node_modules/fs.realpath": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", @@ -2493,40 +2524,29 @@ } }, "node_modules/got": { - "version": "14.2.0", - "resolved": "https://registry.npmjs.org/got/-/got-14.2.0.tgz", - "integrity": "sha512-dBq2KkHcQl3AwPoIWsLsQScCPpUgRulz1qZVthjPYKYOPmYfBnekR3vxecjZbm91Vc3JUGnV9mqFX7B+Fe2quw==", - "dependencies": { - "@sindresorhus/is": "^6.1.0", - "@szmarczak/http-timer": "^5.0.1", - "cacheable-lookup": "^7.0.0", - "cacheable-request": "^10.2.14", + "version": "11.8.6", + "resolved": "https://registry.npmjs.org/got/-/got-11.8.6.tgz", + "integrity": "sha512-6tfZ91bOr7bOXnK7PRDCGBLa1H4U080YHNaAQ2KsMGlLEzRbk44nsZF2E1IeRc3vtJHPVbKCYgdFbaGO2ljd8g==", + "dependencies": { + "@sindresorhus/is": "^4.0.0", + "@szmarczak/http-timer": "^4.0.5", + "@types/cacheable-request": "^6.0.1", + "@types/responselike": "^1.0.0", + "cacheable-lookup": "^5.0.3", + "cacheable-request": "^7.0.2", "decompress-response": "^6.0.0", - "form-data-encoder": "^4.0.2", - "get-stream": "^8.0.1", - "http2-wrapper": "^2.2.1", - "lowercase-keys": "^3.0.0", - "p-cancelable": "^4.0.1", - "responselike": "^3.0.0" + "http2-wrapper": "^1.0.0-beta.5.2", + "lowercase-keys": "^2.0.0", + "p-cancelable": "^2.0.0", + "responselike": "^2.0.0" }, "engines": { - "node": ">=20" + "node": ">=10.19.0" }, "funding": { "url": "https://github.com/sindresorhus/got?sponsor=1" } }, - "node_modules/got/node_modules/get-stream": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-8.0.1.tgz", - "integrity": "sha512-VaUJspBffn/LMCJVoMvSAdmscJyS1auj5Zulnn5UoYcY531UWmdwhRWkcGKnGU93m5HSXP9LP2usOryrBtQowA==", - "engines": { - "node": ">=16" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/graceful-fs": { "version": "4.2.11", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", @@ -2572,12 +2592,12 @@ "integrity": "sha512-er295DKPVsV82j5kw1Gjt+ADA/XYHsajl82cGNQG2eyoPkvgUhX+nDIyelzhIWbbsXP39EHcI6l5tYs2FYqYXQ==" }, "node_modules/http2-wrapper": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/http2-wrapper/-/http2-wrapper-2.2.1.tgz", - "integrity": "sha512-V5nVw1PAOgfI3Lmeaj2Exmeg7fenjhRUgz1lPSezy1CuhPYbgQtbQj4jZfEAEMlaL+vupsvhjqCyjzob0yxsmQ==", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/http2-wrapper/-/http2-wrapper-1.0.3.tgz", + "integrity": "sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg==", "dependencies": { "quick-lru": "^5.1.1", - "resolve-alpn": "^1.2.0" + "resolve-alpn": "^1.0.0" }, "engines": { "node": ">=10.19.0" @@ -4723,14 +4743,11 @@ "dev": true }, "node_modules/lowercase-keys": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-3.0.0.tgz", - "integrity": "sha512-ozCC6gdQ+glXOQsveKD0YsDy8DSQFjDTz4zyzEHNV5+JP5D62LmfDZ6o1cycFx9ouG940M5dE8C8CTewdj2YWQ==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-2.0.0.tgz", + "integrity": "sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA==", "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "node": ">=8" } }, "node_modules/lru-cache": { @@ -4834,14 +4851,11 @@ } }, "node_modules/mimic-response": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-4.0.0.tgz", - "integrity": "sha512-e5ISH9xMYU0DzrT+jl8q2ze9D6eWBto+I8CNpe+VI+K2J/F/k3PdkdTdz4wvGVH4NTpo+NRYTVIuMQEMMcsLqg==", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-1.0.1.tgz", + "integrity": "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ==", "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "node": ">=4" } }, "node_modules/minimatch": { @@ -4917,11 +4931,11 @@ } }, "node_modules/normalize-url": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-8.0.0.tgz", - "integrity": "sha512-uVFpKhj5MheNBJRTiMZ9pE/7hD1QTeEvugSJW/OmLzAp78PB5O6adfMNTvmfKhXBkvCzC+rqifWcVYpGFwTjnw==", + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-6.1.0.tgz", + "integrity": "sha512-DlL+XwOy3NxAQ8xuC0okPgK46iuVNAK01YN7RueYBqqFeGsBjV9XmCAzAdgt+667bCl5kPh9EqKKDwnaPG1I7A==", "engines": { - "node": ">=14.16" + "node": ">=10" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" @@ -4943,7 +4957,6 @@ "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "dev": true, "dependencies": { "wrappy": "1" } @@ -4973,11 +4986,11 @@ } }, "node_modules/p-cancelable": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-4.0.1.tgz", - "integrity": "sha512-wBowNApzd45EIKdO1LaU+LrMBwAcjfPaYtVzV3lmfM3gf8Z4CHZsiIqlM8TZZ8okYvh5A1cP6gTfCRQtwUpaUg==", + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-2.1.1.tgz", + "integrity": "sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg==", "engines": { - "node": ">=14.16" + "node": ">=8" } }, "node_modules/p-finally": { @@ -5189,7 +5202,6 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz", "integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==", - "dev": true, "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" @@ -5341,14 +5353,11 @@ } }, "node_modules/responselike": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/responselike/-/responselike-3.0.0.tgz", - "integrity": "sha512-40yHxbNcl2+rzXvZuVkrYohathsSJlMTXKryG5y8uciHv1+xDLHQpgjG64JUO9nrEq2jGLH6IZ8BcZyw3wrweg==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/responselike/-/responselike-2.0.1.tgz", + "integrity": "sha512-4gl03wn3hj1HP3yzgdI7d3lCkF95F21Pz4BPGvKHinyQzALR5CapwC8yIi0Rh58DEMQ/SguC03wFj2k0M/mHhw==", "dependencies": { - "lowercase-keys": "^3.0.0" - }, - "engines": { - "node": ">=14.16" + "lowercase-keys": "^2.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" @@ -5908,8 +5917,7 @@ "node_modules/wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", - "dev": true + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==" }, "node_modules/write-file-atomic": { "version": "4.0.2", diff --git a/setup-pandoc/package.json b/setup-pandoc/package.json index 7a95b977c..80e10e68d 100644 --- a/setup-pandoc/package.json +++ b/setup-pandoc/package.json @@ -1,6 +1,5 @@ { "name": "setup-pandoc", - "type": "module", "version": "0.0.0", "private": true, "description": "pandoc setup action", @@ -31,7 +30,7 @@ "@actions/io": "^1.1.3", "@actions/tool-cache": "^2.0.1", "compare-versions": "^4.0.1", - "got": "^14.2.0" + "got": "^11.8.3" }, "devDependencies": { "@types/jest": "^29.2.0", diff --git a/setup-pandoc/tsconfig.json b/setup-pandoc/tsconfig.json index a90ee825f..960dc9fa6 100644 --- a/setup-pandoc/tsconfig.json +++ b/setup-pandoc/tsconfig.json @@ -38,7 +38,7 @@ // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ /* Module Resolution Options */ - "moduleResolution": "node16", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ + // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */