diff --git a/index.mjs b/index.mjs index 8d0fa41755af4e8488f78d64cdba186c1503475b..067c59468e24ced9ae41fba8c21bdc0a986ce217 100644 --- a/index.mjs +++ b/index.mjs @@ -1,8 +1,8 @@ import express from "express"; -import 'dotenv/config.js' +//import 'dotenv/config.js' import { createServer } from "http"; import { Server } from "socket.io"; -import { client } from "@gradio/client"; +import { Client } from "@gradio/client"; import { createRequire } from 'node:module' const require = createRequire(import.meta.url); global.EventSource = require('eventsource'); @@ -26,7 +26,7 @@ io.on("connection", (socket) => { async function asyncAPICall(data, socket) { - const grapi = await client.connect("fffiloni/mndrm-call"); + const grapi = await Client.connect("fffiloni/mndrm-call"); try{ const api_result = await grapi.predict("/infer", { image_string: data[0], // blob in 'image' Image component diff --git a/node_modules/.bin/mime b/node_modules/.bin/mime new file mode 120000 index 0000000000000000000000000000000000000000..fbb7ee0eed8d1dd0fe3b5a9d6ff41d1c4f044675 --- /dev/null +++ b/node_modules/.bin/mime @@ -0,0 +1 @@ +../mime/cli.js \ No newline at end of file diff --git a/node_modules/.bin/msw b/node_modules/.bin/msw new file mode 120000 index 0000000000000000000000000000000000000000..63485abf5a1cb580cc1cd462bc67eb4bfea388c4 --- /dev/null +++ b/node_modules/.bin/msw @@ -0,0 +1 @@ +../msw/cli/index.js \ No newline at end of file diff --git a/node_modules/.bin/node-gyp-build b/node_modules/.bin/node-gyp-build new file mode 120000 index 0000000000000000000000000000000000000000..671c6ebcea1d4e99e0367e96b313158ea9f9e1db --- /dev/null +++ b/node_modules/.bin/node-gyp-build @@ -0,0 +1 @@ +../node-gyp-build/bin.js \ No newline at end of file diff --git a/node_modules/.bin/node-gyp-build-optional b/node_modules/.bin/node-gyp-build-optional new file mode 120000 index 0000000000000000000000000000000000000000..46d347e6b1399b9bd08d727dbd1dd927b7086fd2 --- /dev/null +++ b/node_modules/.bin/node-gyp-build-optional @@ -0,0 +1 @@ +../node-gyp-build/optional.js \ No newline at end of file diff --git a/node_modules/.bin/node-gyp-build-test b/node_modules/.bin/node-gyp-build-test new file mode 120000 index 0000000000000000000000000000000000000000..d11de1becd5ee3b6a20f1e0ace8d64214eafeb15 --- /dev/null +++ b/node_modules/.bin/node-gyp-build-test @@ -0,0 +1 @@ +../node-gyp-build/build-test.js \ No newline at end of file diff --git a/node_modules/.bin/tsc b/node_modules/.bin/tsc new file mode 120000 index 0000000000000000000000000000000000000000..0863208a6a1fe7ba964993a1a398794c4021ae19 --- /dev/null +++ b/node_modules/.bin/tsc @@ -0,0 +1 @@ +../typescript/bin/tsc \ No newline at end of file diff --git a/node_modules/.bin/tsserver b/node_modules/.bin/tsserver new file mode 120000 index 0000000000000000000000000000000000000000..f8f8f1a0c33562942ab214430b7878ee378cfdd8 --- /dev/null +++ b/node_modules/.bin/tsserver @@ -0,0 +1 @@ +../typescript/bin/tsserver \ No newline at end of file diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json deleted file mode 100644 index 3391f2119265c8cbcfd8c870d95f6ca55ab3a3a8..0000000000000000000000000000000000000000 --- a/node_modules/.package-lock.json +++ /dev/null @@ -1,964 +0,0 @@ -{ - "name": "live-vision", - "version": "1.0.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "node_modules/@gradio/client": { - "version": "0.10.1", - "resolved": "https://registry.npmjs.org/@gradio/client/-/client-0.10.1.tgz", - "integrity": "sha512-C3uWIWEqlpTuG3sfPw3K3+26Fkr+jXPL8U2lC1u7DlBm25rHdGMVX17o8ApW7XcFtznfaLceVtpnDPkDpQTJlw==", - "dependencies": { - "bufferutil": "^4.0.7", - "semiver": "^1.1.0", - "ws": "^8.13.0" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@socket.io/component-emitter": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.0.tgz", - "integrity": "sha512-+9jVqKhRSpsc591z5vX+X5Yyw+he/HCB4iQ/RYxw35CEPaY1gnsNE43nf9n9AaYjAQrTiI/mOwKUKdUs9vf7Xg==" - }, - "node_modules/@types/cookie": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.4.1.tgz", - "integrity": "sha512-XW/Aa8APYr6jSVVA1y/DEIZX0/GMKLEVekNG727R8cs56ahETkRAy/3DR7+fJyh7oUgGwNQaRfXCun0+KbWY7Q==" - }, - "node_modules/@types/cors": { - "version": "2.8.17", - "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.17.tgz", - "integrity": "sha512-8CGDvrBj1zgo2qE+oS3pOCyYNqCPryMWY2bGfwA0dcfopWGgxs+78df0Rs3rc9THP4JkOhLsAa+15VdpAqkcUA==", - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@types/node": { - "version": "20.11.6", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.6.tgz", - "integrity": "sha512-+EOokTnksGVgip2PbYbr3xnR7kZigh4LbybAfBAw5BpnQ+FqBYUsvCEjYd70IXKlbohQ64mzEYmMtlWUY8q//Q==", - "dependencies": { - "undici-types": "~5.26.4" - } - }, - "node_modules/accepts": { - "version": "1.3.8", - "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", - "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", - "dependencies": { - "mime-types": "~2.1.34", - "negotiator": "0.6.3" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/array-flatten": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", - "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==" - }, - "node_modules/base64id": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/base64id/-/base64id-2.0.0.tgz", - "integrity": "sha512-lGe34o6EHj9y3Kts9R4ZYs/Gr+6N7MCaMlIFA3F1R2O5/m7K06AxfSeO5530PEERE6/WyEg3lsuyw4GHlPZHog==", - "engines": { - "node": "^4.5.0 || >= 5.9" - } - }, - "node_modules/body-parser": { - "version": "1.20.1", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.1.tgz", - "integrity": "sha512-jWi7abTbYwajOytWCQc37VulmWiRae5RyTpaCyDcS5/lMdtwSz5lOpDE67srw/HYe35f1z3fDQw+3txg7gNtWw==", - "dependencies": { - "bytes": "3.1.2", - "content-type": "~1.0.4", - "debug": "2.6.9", - "depd": "2.0.0", - "destroy": "1.2.0", - "http-errors": "2.0.0", - "iconv-lite": "0.4.24", - "on-finished": "2.4.1", - "qs": "6.11.0", - "raw-body": "2.5.1", - "type-is": "~1.6.18", - "unpipe": "1.0.0" - }, - "engines": { - "node": ">= 0.8", - "npm": "1.2.8000 || >= 1.4.16" - } - }, - "node_modules/bufferutil": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/bufferutil/-/bufferutil-4.0.8.tgz", - "integrity": "sha512-4T53u4PdgsXqKaIctwF8ifXlRTTmEPJ8iEPWFdGZvcf7sbwYo6FKFEX9eNNAnzFZ7EzJAQ3CJeOtCRA4rDp7Pw==", - "hasInstallScript": true, - "dependencies": { - "node-gyp-build": "^4.3.0" - }, - "engines": { - "node": ">=6.14.2" - } - }, - "node_modules/bytes": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", - "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/call-bind": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.5.tgz", - "integrity": "sha512-C3nQxfFZxFRVoJoGKKI8y3MOEo129NQ+FgQ08iye+Mk4zNZZGdjfs06bVTr+DBSlA66Q2VEcMki/cUCP4SercQ==", - "dependencies": { - "function-bind": "^1.1.2", - "get-intrinsic": "^1.2.1", - "set-function-length": "^1.1.1" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/content-disposition": { - "version": "0.5.4", - "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", - "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", - "dependencies": { - "safe-buffer": "5.2.1" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/content-type": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", - "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/cookie": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.5.0.tgz", - "integrity": "sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/cookie-signature": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", - "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==" - }, - "node_modules/cors": { - "version": "2.8.5", - "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", - "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", - "dependencies": { - "object-assign": "^4", - "vary": "^1" - }, - "engines": { - "node": ">= 0.10" - } - }, - "node_modules/debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "dependencies": { - "ms": "2.0.0" - } - }, - "node_modules/define-data-property": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.1.tgz", - "integrity": "sha512-E7uGkTzkk1d0ByLeSc6ZsFS79Axg+m1P/VsgYsxHgiuc3tFSj+MjMIwe90FC4lOAZzNBdY7kkO2P2wKdsQ1vgQ==", - "dependencies": { - "get-intrinsic": "^1.2.1", - "gopd": "^1.0.1", - "has-property-descriptors": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/depd": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", - "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/destroy": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", - "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", - "engines": { - "node": ">= 0.8", - "npm": "1.2.8000 || >= 1.4.16" - } - }, - "node_modules/dotenv": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-4.0.0.tgz", - "integrity": "sha512-XcaMACOr3JMVcEv0Y/iUM2XaOsATRZ3U1In41/1jjK6vJZ2PZbQ1bzCG8uvaByfaBpl9gqc9QWJovpUGBXLLYQ==", - "engines": { - "node": ">=4.6.0" - } - }, - "node_modules/ee-first": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", - "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==" - }, - "node_modules/encodeurl": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", - "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/engine.io": { - "version": "6.5.4", - "resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.5.4.tgz", - "integrity": "sha512-KdVSDKhVKyOi+r5uEabrDLZw2qXStVvCsEB/LN3mw4WFi6Gx50jTyuxYVCwAAC0U46FdnzP/ScKRBTXb/NiEOg==", - "dependencies": { - "@types/cookie": "^0.4.1", - "@types/cors": "^2.8.12", - "@types/node": ">=10.0.0", - "accepts": "~1.3.4", - "base64id": "2.0.0", - "cookie": "~0.4.1", - "cors": "~2.8.5", - "debug": "~4.3.1", - "engine.io-parser": "~5.2.1", - "ws": "~8.11.0" - }, - "engines": { - "node": ">=10.2.0" - } - }, - "node_modules/engine.io-parser": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.2.1.tgz", - "integrity": "sha512-9JktcM3u18nU9N2Lz3bWeBgxVgOKpw7yhRaoxQA3FUDZzzw+9WlA6p4G4u0RixNkg14fH7EfEc/RhpurtiROTQ==", - "engines": { - "node": ">=10.0.0" - } - }, - "node_modules/engine.io/node_modules/cookie": { - "version": "0.4.2", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.2.tgz", - "integrity": "sha512-aSWTXFzaKWkvHO1Ny/s+ePFpvKsPnjc551iI41v3ny/ow6tBG5Vd+FuqGNhh1LxOmVzOlGUriIlOaokOvhaStA==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/engine.io/node_modules/debug": { - "version": "4.3.4", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", - "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", - "dependencies": { - "ms": "2.1.2" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/engine.io/node_modules/ms": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" - }, - "node_modules/engine.io/node_modules/ws": { - "version": "8.11.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.11.0.tgz", - "integrity": "sha512-HPG3wQd9sNQoT9xHyNCXoDUa+Xw/VevmY9FoHyQ+g+rrMn4j6FB4np7Z0OhdTgjx6MgQLK7jwSy1YecU1+4Asg==", - "engines": { - "node": ">=10.0.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": "^5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - }, - "node_modules/escape-html": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", - "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==" - }, - "node_modules/etag": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", - "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/eventsource": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-2.0.2.tgz", - "integrity": "sha512-IzUmBGPR3+oUG9dUeXynyNmf91/3zUSJg1lCktzKw47OXuhco54U3r9B7O4XX+Rb1Itm9OZ2b0RkTs10bICOxA==", - "engines": { - "node": ">=12.0.0" - } - }, - "node_modules/express": { - "version": "4.18.2", - "resolved": "https://registry.npmjs.org/express/-/express-4.18.2.tgz", - "integrity": "sha512-5/PsL6iGPdfQ/lKM1UuielYgv3BUoJfz1aUwU9vHZ+J7gyvwdQXFEBIEIaxeGf0GIcreATNyBExtalisDbuMqQ==", - "dependencies": { - "accepts": "~1.3.8", - "array-flatten": "1.1.1", - "body-parser": "1.20.1", - "content-disposition": "0.5.4", - "content-type": "~1.0.4", - "cookie": "0.5.0", - "cookie-signature": "1.0.6", - "debug": "2.6.9", - "depd": "2.0.0", - "encodeurl": "~1.0.2", - "escape-html": "~1.0.3", - "etag": "~1.8.1", - "finalhandler": "1.2.0", - "fresh": "0.5.2", - "http-errors": "2.0.0", - "merge-descriptors": "1.0.1", - "methods": "~1.1.2", - "on-finished": "2.4.1", - "parseurl": "~1.3.3", - "path-to-regexp": "0.1.7", - "proxy-addr": "~2.0.7", - "qs": "6.11.0", - "range-parser": "~1.2.1", - "safe-buffer": "5.2.1", - "send": "0.18.0", - "serve-static": "1.15.0", - "setprototypeof": "1.2.0", - "statuses": "2.0.1", - "type-is": "~1.6.18", - "utils-merge": "1.0.1", - "vary": "~1.1.2" - }, - "engines": { - "node": ">= 0.10.0" - } - }, - "node_modules/finalhandler": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.2.0.tgz", - "integrity": "sha512-5uXcUVftlQMFnWC9qu/svkWv3GTd2PfUhK/3PLkYNAe7FbqJMt3515HaxE6eRL74GdsriiwujiawdaB1BpEISg==", - "dependencies": { - "debug": "2.6.9", - "encodeurl": "~1.0.2", - "escape-html": "~1.0.3", - "on-finished": "2.4.1", - "parseurl": "~1.3.3", - "statuses": "2.0.1", - "unpipe": "~1.0.0" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/forwarded": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", - "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/fresh": { - "version": "0.5.2", - "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", - "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/function-bind": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", - "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/get-intrinsic": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.2.tgz", - "integrity": "sha512-0gSo4ml/0j98Y3lngkFEot/zhiCeWsbYIlZ+uZOVgzLyLaUw7wxUL+nCTP0XJvJg1AXulJRI3UJi8GsbDuxdGA==", - "dependencies": { - "function-bind": "^1.1.2", - "has-proto": "^1.0.1", - "has-symbols": "^1.0.3", - "hasown": "^2.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/gopd": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", - "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==", - "dependencies": { - "get-intrinsic": "^1.1.3" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/has-property-descriptors": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.1.tgz", - "integrity": "sha512-VsX8eaIewvas0xnvinAe9bw4WfIeODpGYikiWYLH+dma0Jw6KHYqWiWfhQlgOVK8D6PvjubK5Uc4P0iIhIcNVg==", - "dependencies": { - "get-intrinsic": "^1.2.2" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/has-proto": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.0.1.tgz", - "integrity": "sha512-7qE+iP+O+bgF9clE5+UoBFzE65mlBiVj3tKCrlNQ0Ogwm0BjpT/gK4SlLYDMybDh5I3TCTKnPPa0oMG7JDYrhg==", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/has-symbols": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", - "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/hasown": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.0.tgz", - "integrity": "sha512-vUptKVTpIJhcczKBbgnS+RtcuYMB8+oNzPK2/Hp3hanz8JmpATdmmgLgSaadVREkDm+e2giHwY3ZRkyjSIDDFA==", - "dependencies": { - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/http-errors": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", - "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", - "dependencies": { - "depd": "2.0.0", - "inherits": "2.0.4", - "setprototypeof": "1.2.0", - "statuses": "2.0.1", - "toidentifier": "1.0.1" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/iconv-lite": { - "version": "0.4.24", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", - "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" - }, - "node_modules/ipaddr.js": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", - "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", - "engines": { - "node": ">= 0.10" - } - }, - "node_modules/media-typer": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", - "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/merge-descriptors": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", - "integrity": "sha512-cCi6g3/Zr1iqQi6ySbseM1Xvooa98N0w31jzUYrXPX2xqObmFGHJ0tQ5u74H3mVh7wLouTseZyYIq39g8cNp1w==" - }, - "node_modules/methods": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", - "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mime": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", - "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", - "bin": { - "mime": "cli.js" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/mime-db": { - "version": "1.52.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", - "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mime-types": { - "version": "2.1.35", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", - "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", - "dependencies": { - "mime-db": "1.52.0" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" - }, - "node_modules/negotiator": { - "version": "0.6.3", - "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", - "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/node-gyp-build": { - "version": "4.8.0", - "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.0.tgz", - "integrity": "sha512-u6fs2AEUljNho3EYTJNBfImO5QTo/J/1Etd+NVdCj7qWKUSN/bSLkZwhDv7I+w/MSC6qJ4cknepkAYykDdK8og==", - "bin": { - "node-gyp-build": "bin.js", - "node-gyp-build-optional": "optional.js", - "node-gyp-build-test": "build-test.js" - } - }, - "node_modules/object-assign": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", - "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/object-inspect": { - "version": "1.13.1", - "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.1.tgz", - "integrity": "sha512-5qoj1RUiKOMsCCNLV1CBiPYE10sziTsnmNxkAI/rZhiD63CF7IqdFGC/XzjWjpSgLf0LxXX3bDFIh0E18f6UhQ==", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/on-finished": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", - "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", - "dependencies": { - "ee-first": "1.1.1" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/parseurl": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", - "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/path-to-regexp": { - "version": "0.1.7", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", - "integrity": "sha512-5DFkuoqlv1uYQKxy8omFBeJPQcdoE07Kv2sferDCrAq1ohOU+MSDswDIbnx3YAM60qIOnYa53wBhXW0EbMonrQ==" - }, - "node_modules/proxy-addr": { - "version": "2.0.7", - "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", - "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", - "dependencies": { - "forwarded": "0.2.0", - "ipaddr.js": "1.9.1" - }, - "engines": { - "node": ">= 0.10" - } - }, - "node_modules/qs": { - "version": "6.11.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.11.0.tgz", - "integrity": "sha512-MvjoMCJwEarSbUYk5O+nmoSzSutSsTwF85zcHPQ9OrlFoZOYIjaqBAJIqIXjptyD5vThxGq52Xu/MaJzRkIk4Q==", - "dependencies": { - "side-channel": "^1.0.4" - }, - "engines": { - "node": ">=0.6" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/range-parser": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", - "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/raw-body": { - "version": "2.5.1", - "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.1.tgz", - "integrity": "sha512-qqJBtEyVgS0ZmPGdCFPWJ3FreoqvG4MVQln/kCgF7Olq95IbOp0/BWyMwbdtn4VTvkM8Y7khCQ2Xgk/tcrCXig==", - "dependencies": { - "bytes": "3.1.2", - "http-errors": "2.0.0", - "iconv-lite": "0.4.24", - "unpipe": "1.0.0" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ] - }, - "node_modules/safer-buffer": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" - }, - "node_modules/semiver": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/semiver/-/semiver-1.1.0.tgz", - "integrity": "sha512-QNI2ChmuioGC1/xjyYwyZYADILWyW6AmS1UH6gDj/SFUUUS4MBAWs/7mxnkRPc/F4iHezDP+O8t0dO8WHiEOdg==", - "engines": { - "node": ">=6" - } - }, - "node_modules/send": { - "version": "0.18.0", - "resolved": "https://registry.npmjs.org/send/-/send-0.18.0.tgz", - "integrity": "sha512-qqWzuOjSFOuqPjFe4NOsMLafToQQwBSOEpS+FwEt3A2V3vKubTquT3vmLTQpFgMXp8AlFWFuP1qKaJZOtPpVXg==", - "dependencies": { - "debug": "2.6.9", - "depd": "2.0.0", - "destroy": "1.2.0", - "encodeurl": "~1.0.2", - "escape-html": "~1.0.3", - "etag": "~1.8.1", - "fresh": "0.5.2", - "http-errors": "2.0.0", - "mime": "1.6.0", - "ms": "2.1.3", - "on-finished": "2.4.1", - "range-parser": "~1.2.1", - "statuses": "2.0.1" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/send/node_modules/ms": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" - }, - "node_modules/serve-static": { - "version": "1.15.0", - "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.15.0.tgz", - "integrity": "sha512-XGuRDNjXUijsUL0vl6nSD7cwURuzEgglbOaFuZM9g3kwDXOWVTck0jLzjPzGD+TazWbboZYu52/9/XPdUgne9g==", - "dependencies": { - "encodeurl": "~1.0.2", - "escape-html": "~1.0.3", - "parseurl": "~1.3.3", - "send": "0.18.0" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/set-function-length": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.0.tgz", - "integrity": "sha512-4DBHDoyHlM1IRPGYcoxexgh67y4ueR53FKV1yyxwFMY7aCqcN/38M1+SwZ/qJQ8iLv7+ck385ot4CcisOAPT9w==", - "dependencies": { - "define-data-property": "^1.1.1", - "function-bind": "^1.1.2", - "get-intrinsic": "^1.2.2", - "gopd": "^1.0.1", - "has-property-descriptors": "^1.0.1" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/setprototypeof": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", - "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" - }, - "node_modules/side-channel": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz", - "integrity": "sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==", - "dependencies": { - "call-bind": "^1.0.0", - "get-intrinsic": "^1.0.2", - "object-inspect": "^1.9.0" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/socket.io": { - "version": "4.7.4", - "resolved": "https://registry.npmjs.org/socket.io/-/socket.io-4.7.4.tgz", - "integrity": "sha512-DcotgfP1Zg9iP/dH9zvAQcWrE0TtbMVwXmlV4T4mqsvY+gw+LqUGPfx2AoVyRk0FLME+GQhufDMyacFmw7ksqw==", - "dependencies": { - "accepts": "~1.3.4", - "base64id": "~2.0.0", - "cors": "~2.8.5", - "debug": "~4.3.2", - "engine.io": "~6.5.2", - "socket.io-adapter": "~2.5.2", - "socket.io-parser": "~4.2.4" - }, - "engines": { - "node": ">=10.2.0" - } - }, - "node_modules/socket.io-adapter": { - "version": "2.5.2", - "resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-2.5.2.tgz", - "integrity": "sha512-87C3LO/NOMc+eMcpcxUBebGjkpMDkNBS9tf7KJqcDsmL936EChtVva71Dw2q4tQcuVC+hAUy4an2NO/sYXmwRA==", - "dependencies": { - "ws": "~8.11.0" - } - }, - "node_modules/socket.io-adapter/node_modules/ws": { - "version": "8.11.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.11.0.tgz", - "integrity": "sha512-HPG3wQd9sNQoT9xHyNCXoDUa+Xw/VevmY9FoHyQ+g+rrMn4j6FB4np7Z0OhdTgjx6MgQLK7jwSy1YecU1+4Asg==", - "engines": { - "node": ">=10.0.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": "^5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - }, - "node_modules/socket.io-parser": { - "version": "4.2.4", - "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.4.tgz", - "integrity": "sha512-/GbIKmo8ioc+NIWIhwdecY0ge+qVBSMdgxGygevmdHj24bsfgtCmcUUcQ5ZzcylGFHsN3k4HB4Cgkl96KVnuew==", - "dependencies": { - "@socket.io/component-emitter": "~3.1.0", - "debug": "~4.3.1" - }, - "engines": { - "node": ">=10.0.0" - } - }, - "node_modules/socket.io-parser/node_modules/debug": { - "version": "4.3.4", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", - "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", - "dependencies": { - "ms": "2.1.2" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/socket.io-parser/node_modules/ms": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" - }, - "node_modules/socket.io/node_modules/debug": { - "version": "4.3.4", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", - "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", - "dependencies": { - "ms": "2.1.2" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/socket.io/node_modules/ms": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" - }, - "node_modules/statuses": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", - "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/toidentifier": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", - "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", - "engines": { - "node": ">=0.6" - } - }, - "node_modules/type-is": { - "version": "1.6.18", - "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", - "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", - "dependencies": { - "media-typer": "0.3.0", - "mime-types": "~2.1.24" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/undici-types": { - "version": "5.26.5", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", - "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==" - }, - "node_modules/unpipe": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", - "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/utils-merge": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", - "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", - "engines": { - "node": ">= 0.4.0" - } - }, - "node_modules/vary": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", - "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/ws": { - "version": "8.16.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.16.0.tgz", - "integrity": "sha512-HS0c//TP7Ina87TfiPUz1rQzMhHrl/SG2guqRcTOIUYD2q8uhUdNHZYJUaQ8aTGPzCh+c6oawMKW35nFl1dxyQ==", - "engines": { - "node": ">=10.0.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": ">=5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - } - } -} diff --git a/node_modules/@bundled-es-modules/cookie/README.md b/node_modules/@bundled-es-modules/cookie/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ce9e73f92a90fbb2257a4bb88ab0d833ba418644 --- /dev/null +++ b/node_modules/@bundled-es-modules/cookie/README.md @@ -0,0 +1,18 @@ +# cookie + +This is a mirror of [cookie](https://www.npmjs.com/package/cookie), bundled and exposed as ES module. + +## Install + +``` +npm install @bundled-es-modules/cookie +``` + +## Use + +```html + +``` \ No newline at end of file diff --git a/node_modules/@bundled-es-modules/cookie/index-cjs.cjs b/node_modules/@bundled-es-modules/cookie/index-cjs.cjs new file mode 100644 index 0000000000000000000000000000000000000000..2faa2bc9d1d061bc9f9b93052e0145fc3aec16b9 --- /dev/null +++ b/node_modules/@bundled-es-modules/cookie/index-cjs.cjs @@ -0,0 +1,2 @@ +const cookie = require('cookie'); +module.exports = cookie; \ No newline at end of file diff --git a/node_modules/@bundled-es-modules/cookie/index-esm.js b/node_modules/@bundled-es-modules/cookie/index-esm.js new file mode 100644 index 0000000000000000000000000000000000000000..d0da62ee27180290b9ee445f3cfb1791c46f78e7 --- /dev/null +++ b/node_modules/@bundled-es-modules/cookie/index-esm.js @@ -0,0 +1,184 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); + +// node_modules/cookie/index.js +var require_cookie = __commonJS({ + "node_modules/cookie/index.js"(exports) { + "use strict"; + exports.parse = parse; + exports.serialize = serialize; + var __toString = Object.prototype.toString; + var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; + function parse(str, options) { + if (typeof str !== "string") { + throw new TypeError("argument str must be a string"); + } + var obj = {}; + var opt = options || {}; + var dec = opt.decode || decode; + var index = 0; + while (index < str.length) { + var eqIdx = str.indexOf("=", index); + if (eqIdx === -1) { + break; + } + var endIdx = str.indexOf(";", index); + if (endIdx === -1) { + endIdx = str.length; + } else if (endIdx < eqIdx) { + index = str.lastIndexOf(";", eqIdx - 1) + 1; + continue; + } + var key = str.slice(index, eqIdx).trim(); + if (void 0 === obj[key]) { + var val = str.slice(eqIdx + 1, endIdx).trim(); + if (val.charCodeAt(0) === 34) { + val = val.slice(1, -1); + } + obj[key] = tryDecode(val, dec); + } + index = endIdx + 1; + } + return obj; + } + function serialize(name, val, options) { + var opt = options || {}; + var enc = opt.encode || encode; + if (typeof enc !== "function") { + throw new TypeError("option encode is invalid"); + } + if (!fieldContentRegExp.test(name)) { + throw new TypeError("argument name is invalid"); + } + var value = enc(val); + if (value && !fieldContentRegExp.test(value)) { + throw new TypeError("argument val is invalid"); + } + var str = name + "=" + value; + if (null != opt.maxAge) { + var maxAge = opt.maxAge - 0; + if (isNaN(maxAge) || !isFinite(maxAge)) { + throw new TypeError("option maxAge is invalid"); + } + str += "; Max-Age=" + Math.floor(maxAge); + } + if (opt.domain) { + if (!fieldContentRegExp.test(opt.domain)) { + throw new TypeError("option domain is invalid"); + } + str += "; Domain=" + opt.domain; + } + if (opt.path) { + if (!fieldContentRegExp.test(opt.path)) { + throw new TypeError("option path is invalid"); + } + str += "; Path=" + opt.path; + } + if (opt.expires) { + var expires = opt.expires; + if (!isDate(expires) || isNaN(expires.valueOf())) { + throw new TypeError("option expires is invalid"); + } + str += "; Expires=" + expires.toUTCString(); + } + if (opt.httpOnly) { + str += "; HttpOnly"; + } + if (opt.secure) { + str += "; Secure"; + } + if (opt.priority) { + var priority = typeof opt.priority === "string" ? opt.priority.toLowerCase() : opt.priority; + switch (priority) { + case "low": + str += "; Priority=Low"; + break; + case "medium": + str += "; Priority=Medium"; + break; + case "high": + str += "; Priority=High"; + break; + default: + throw new TypeError("option priority is invalid"); + } + } + if (opt.sameSite) { + var sameSite = typeof opt.sameSite === "string" ? opt.sameSite.toLowerCase() : opt.sameSite; + switch (sameSite) { + case true: + str += "; SameSite=Strict"; + break; + case "lax": + str += "; SameSite=Lax"; + break; + case "strict": + str += "; SameSite=Strict"; + break; + case "none": + str += "; SameSite=None"; + break; + default: + throw new TypeError("option sameSite is invalid"); + } + } + return str; + } + function decode(str) { + return str.indexOf("%") !== -1 ? decodeURIComponent(str) : str; + } + function encode(val) { + return encodeURIComponent(val); + } + function isDate(val) { + return __toString.call(val) === "[object Date]" || val instanceof Date; + } + function tryDecode(str, decode2) { + try { + return decode2(str); + } catch (e) { + return str; + } + } + } +}); + +// source.js +var import_cookie = __toESM(require_cookie(), 1); +var source_default = import_cookie.default; +export { + source_default as default +}; +/*! Bundled license information: + +cookie/index.js: + (*! + * cookie + * Copyright(c) 2012-2014 Roman Shtylman + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + *) +*/ diff --git a/node_modules/@bundled-es-modules/cookie/node_modules/cookie/HISTORY.md b/node_modules/@bundled-es-modules/cookie/node_modules/cookie/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..ae9b995b42630df67a8333aca075b086c48d432c --- /dev/null +++ b/node_modules/@bundled-es-modules/cookie/node_modules/cookie/HISTORY.md @@ -0,0 +1,142 @@ +0.5.0 / 2022-04-11 +================== + + * Add `priority` option + * Fix `expires` option to reject invalid dates + * pref: improve default decode speed + * pref: remove slow string split in parse + +0.4.2 / 2022-02-02 +================== + + * pref: read value only when assigning in parse + * pref: remove unnecessary regexp in parse + +0.4.1 / 2020-04-21 +================== + + * Fix `maxAge` option to reject invalid values + +0.4.0 / 2019-05-15 +================== + + * Add `SameSite=None` support + +0.3.1 / 2016-05-26 +================== + + * Fix `sameSite: true` to work with draft-7 clients + - `true` now sends `SameSite=Strict` instead of `SameSite` + +0.3.0 / 2016-05-26 +================== + + * Add `sameSite` option + - Replaces `firstPartyOnly` option, never implemented by browsers + * Improve error message when `encode` is not a function + * Improve error message when `expires` is not a `Date` + +0.2.4 / 2016-05-20 +================== + + * perf: enable strict mode + * perf: use for loop in parse + * perf: use string concatination for serialization + +0.2.3 / 2015-10-25 +================== + + * Fix cookie `Max-Age` to never be a floating point number + +0.2.2 / 2015-09-17 +================== + + * Fix regression when setting empty cookie value + - Ease the new restriction, which is just basic header-level validation + * Fix typo in invalid value errors + +0.2.1 / 2015-09-17 +================== + + * Throw on invalid values provided to `serialize` + - Ensures the resulting string is a valid HTTP header value + +0.2.0 / 2015-08-13 +================== + + * Add `firstPartyOnly` option + * Throw better error for invalid argument to parse + * perf: hoist regular expression + +0.1.5 / 2015-09-17 +================== + + * Fix regression when setting empty cookie value + - Ease the new restriction, which is just basic header-level validation + * Fix typo in invalid value errors + +0.1.4 / 2015-09-17 +================== + + * Throw better error for invalid argument to parse + * Throw on invalid values provided to `serialize` + - Ensures the resulting string is a valid HTTP header value + +0.1.3 / 2015-05-19 +================== + + * Reduce the scope of try-catch deopt + * Remove argument reassignments + +0.1.2 / 2014-04-16 +================== + + * Remove unnecessary files from npm package + +0.1.1 / 2014-02-23 +================== + + * Fix bad parse when cookie value contained a comma + * Fix support for `maxAge` of `0` + +0.1.0 / 2013-05-01 +================== + + * Add `decode` option + * Add `encode` option + +0.0.6 / 2013-04-08 +================== + + * Ignore cookie parts missing `=` + +0.0.5 / 2012-10-29 +================== + + * Return raw cookie value if value unescape errors + +0.0.4 / 2012-06-21 +================== + + * Use encode/decodeURIComponent for cookie encoding/decoding + - Improve server/client interoperability + +0.0.3 / 2012-06-06 +================== + + * Only escape special characters per the cookie RFC + +0.0.2 / 2012-06-01 +================== + + * Fix `maxAge` option to not throw error + +0.0.1 / 2012-05-28 +================== + + * Add more tests + +0.0.0 / 2012-05-28 +================== + + * Initial release diff --git a/node_modules/@bundled-es-modules/cookie/node_modules/cookie/LICENSE b/node_modules/@bundled-es-modules/cookie/node_modules/cookie/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..058b6b4efa3f45896ae691f2558a2a1aca05bebd --- /dev/null +++ b/node_modules/@bundled-es-modules/cookie/node_modules/cookie/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2012-2014 Roman Shtylman +Copyright (c) 2015 Douglas Christopher Wilson + +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/node_modules/@bundled-es-modules/cookie/node_modules/cookie/README.md b/node_modules/@bundled-es-modules/cookie/node_modules/cookie/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5449c3a2587996d44b242281692c01ad2d2a3cf3 --- /dev/null +++ b/node_modules/@bundled-es-modules/cookie/node_modules/cookie/README.md @@ -0,0 +1,302 @@ +# cookie + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][github-actions-ci-image]][github-actions-ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Basic HTTP cookie parser and serializer for HTTP servers. + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install cookie +``` + +## API + +```js +var cookie = require('cookie'); +``` + +### cookie.parse(str, options) + +Parse an HTTP `Cookie` header string and returning an object of all cookie name-value pairs. +The `str` argument is the string representing a `Cookie` header value and `options` is an +optional object containing additional parsing options. + +```js +var cookies = cookie.parse('foo=bar; equation=E%3Dmc%5E2'); +// { foo: 'bar', equation: 'E=mc^2' } +``` + +#### Options + +`cookie.parse` accepts these properties in the options object. + +##### decode + +Specifies a function that will be used to decode a cookie's value. Since the value of a cookie +has a limited character set (and must be a simple string), this function can be used to decode +a previously-encoded cookie value into a JavaScript string or other object. + +The default function is the global `decodeURIComponent`, which will decode any URL-encoded +sequences into their byte representations. + +**note** if an error is thrown from this function, the original, non-decoded cookie value will +be returned as the cookie's value. + +### cookie.serialize(name, value, options) + +Serialize a cookie name-value pair into a `Set-Cookie` header string. The `name` argument is the +name for the cookie, the `value` argument is the value to set the cookie to, and the `options` +argument is an optional object containing additional serialization options. + +```js +var setCookie = cookie.serialize('foo', 'bar'); +// foo=bar +``` + +#### Options + +`cookie.serialize` accepts these properties in the options object. + +##### domain + +Specifies the value for the [`Domain` `Set-Cookie` attribute][rfc-6265-5.2.3]. By default, no +domain is set, and most clients will consider the cookie to apply to only the current domain. + +##### encode + +Specifies a function that will be used to encode a cookie's value. Since value of a cookie +has a limited character set (and must be a simple string), this function can be used to encode +a value into a string suited for a cookie's value. + +The default function is the global `encodeURIComponent`, which will encode a JavaScript string +into UTF-8 byte sequences and then URL-encode any that fall outside of the cookie range. + +##### expires + +Specifies the `Date` object to be the value for the [`Expires` `Set-Cookie` attribute][rfc-6265-5.2.1]. +By default, no expiration is set, and most clients will consider this a "non-persistent cookie" and +will delete it on a condition like exiting a web browser application. + +**note** the [cookie storage model specification][rfc-6265-5.3] states that if both `expires` and +`maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this, +so if both are set, they should point to the same date and time. + +##### httpOnly + +Specifies the `boolean` value for the [`HttpOnly` `Set-Cookie` attribute][rfc-6265-5.2.6]. When truthy, +the `HttpOnly` attribute is set, otherwise it is not. By default, the `HttpOnly` attribute is not set. + +**note** be careful when setting this to `true`, as compliant clients will not allow client-side +JavaScript to see the cookie in `document.cookie`. + +##### maxAge + +Specifies the `number` (in seconds) to be the value for the [`Max-Age` `Set-Cookie` attribute][rfc-6265-5.2.2]. +The given number will be converted to an integer by rounding down. By default, no maximum age is set. + +**note** the [cookie storage model specification][rfc-6265-5.3] states that if both `expires` and +`maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this, +so if both are set, they should point to the same date and time. + +##### path + +Specifies the value for the [`Path` `Set-Cookie` attribute][rfc-6265-5.2.4]. By default, the path +is considered the ["default path"][rfc-6265-5.1.4]. + +##### priority + +Specifies the `string` to be the value for the [`Priority` `Set-Cookie` attribute][rfc-west-cookie-priority-00-4.1]. + + - `'low'` will set the `Priority` attribute to `Low`. + - `'medium'` will set the `Priority` attribute to `Medium`, the default priority when not set. + - `'high'` will set the `Priority` attribute to `High`. + +More information about the different priority levels can be found in +[the specification][rfc-west-cookie-priority-00-4.1]. + +**note** This is an attribute that has not yet been fully standardized, and may change in the future. +This also means many clients may ignore this attribute until they understand it. + +##### sameSite + +Specifies the `boolean` or `string` to be the value for the [`SameSite` `Set-Cookie` attribute][rfc-6265bis-09-5.4.7]. + + - `true` will set the `SameSite` attribute to `Strict` for strict same site enforcement. + - `false` will not set the `SameSite` attribute. + - `'lax'` will set the `SameSite` attribute to `Lax` for lax same site enforcement. + - `'none'` will set the `SameSite` attribute to `None` for an explicit cross-site cookie. + - `'strict'` will set the `SameSite` attribute to `Strict` for strict same site enforcement. + +More information about the different enforcement levels can be found in +[the specification][rfc-6265bis-09-5.4.7]. + +**note** This is an attribute that has not yet been fully standardized, and may change in the future. +This also means many clients may ignore this attribute until they understand it. + +##### secure + +Specifies the `boolean` value for the [`Secure` `Set-Cookie` attribute][rfc-6265-5.2.5]. When truthy, +the `Secure` attribute is set, otherwise it is not. By default, the `Secure` attribute is not set. + +**note** be careful when setting this to `true`, as compliant clients will not send the cookie back to +the server in the future if the browser does not have an HTTPS connection. + +## Example + +The following example uses this module in conjunction with the Node.js core HTTP server +to prompt a user for their name and display it back on future visits. + +```js +var cookie = require('cookie'); +var escapeHtml = require('escape-html'); +var http = require('http'); +var url = require('url'); + +function onRequest(req, res) { + // Parse the query string + var query = url.parse(req.url, true, true).query; + + if (query && query.name) { + // Set a new cookie with the name + res.setHeader('Set-Cookie', cookie.serialize('name', String(query.name), { + httpOnly: true, + maxAge: 60 * 60 * 24 * 7 // 1 week + })); + + // Redirect back after setting cookie + res.statusCode = 302; + res.setHeader('Location', req.headers.referer || '/'); + res.end(); + return; + } + + // Parse the cookies on the request + var cookies = cookie.parse(req.headers.cookie || ''); + + // Get the visitor name set in the cookie + var name = cookies.name; + + res.setHeader('Content-Type', 'text/html; charset=UTF-8'); + + if (name) { + res.write('

Welcome back, ' + escapeHtml(name) + '!

'); + } else { + res.write('

Hello, new visitor!

'); + } + + res.write('
'); + res.write(' '); + res.end('
'); +} + +http.createServer(onRequest).listen(3000); +``` + +## Testing + +```sh +$ npm test +``` + +## Benchmark + +``` +$ npm run bench + +> cookie@0.4.2 bench +> node benchmark/index.js + + node@16.14.0 + v8@9.4.146.24-node.20 + uv@1.43.0 + zlib@1.2.11 + brotli@1.0.9 + ares@1.18.1 + modules@93 + nghttp2@1.45.1 + napi@8 + llhttp@6.0.4 + openssl@1.1.1m+quic + cldr@40.0 + icu@70.1 + tz@2021a3 + unicode@14.0 + ngtcp2@0.1.0-DEV + nghttp3@0.1.0-DEV + +> node benchmark/parse-top.js + + cookie.parse - top sites + + 15 tests completed. + + parse accounts.google.com x 2,421,245 ops/sec ±0.80% (188 runs sampled) + parse apple.com x 2,684,710 ops/sec ±0.59% (189 runs sampled) + parse cloudflare.com x 2,231,418 ops/sec ±0.76% (186 runs sampled) + parse docs.google.com x 2,316,357 ops/sec ±1.28% (187 runs sampled) + parse drive.google.com x 2,363,543 ops/sec ±0.49% (189 runs sampled) + parse en.wikipedia.org x 839,414 ops/sec ±0.53% (189 runs sampled) + parse linkedin.com x 553,797 ops/sec ±0.63% (190 runs sampled) + parse maps.google.com x 1,314,779 ops/sec ±0.72% (189 runs sampled) + parse microsoft.com x 153,783 ops/sec ±0.53% (190 runs sampled) + parse play.google.com x 2,249,574 ops/sec ±0.59% (187 runs sampled) + parse plus.google.com x 2,258,682 ops/sec ±0.60% (188 runs sampled) + parse sites.google.com x 2,247,069 ops/sec ±0.68% (189 runs sampled) + parse support.google.com x 1,456,840 ops/sec ±0.70% (187 runs sampled) + parse www.google.com x 1,046,028 ops/sec ±0.58% (188 runs sampled) + parse youtu.be x 937,428 ops/sec ±1.47% (190 runs sampled) + parse youtube.com x 963,878 ops/sec ±0.59% (190 runs sampled) + +> node benchmark/parse.js + + cookie.parse - generic + + 6 tests completed. + + simple x 2,745,604 ops/sec ±0.77% (185 runs sampled) + decode x 557,287 ops/sec ±0.60% (188 runs sampled) + unquote x 2,498,475 ops/sec ±0.55% (189 runs sampled) + duplicates x 868,591 ops/sec ±0.89% (187 runs sampled) + 10 cookies x 306,745 ops/sec ±0.49% (190 runs sampled) + 100 cookies x 22,414 ops/sec ±2.38% (182 runs sampled) +``` + +## References + +- [RFC 6265: HTTP State Management Mechanism][rfc-6265] +- [Same-site Cookies][rfc-6265bis-09-5.4.7] + +[rfc-west-cookie-priority-00-4.1]: https://tools.ietf.org/html/draft-west-cookie-priority-00#section-4.1 +[rfc-6265bis-09-5.4.7]: https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-09#section-5.4.7 +[rfc-6265]: https://tools.ietf.org/html/rfc6265 +[rfc-6265-5.1.4]: https://tools.ietf.org/html/rfc6265#section-5.1.4 +[rfc-6265-5.2.1]: https://tools.ietf.org/html/rfc6265#section-5.2.1 +[rfc-6265-5.2.2]: https://tools.ietf.org/html/rfc6265#section-5.2.2 +[rfc-6265-5.2.3]: https://tools.ietf.org/html/rfc6265#section-5.2.3 +[rfc-6265-5.2.4]: https://tools.ietf.org/html/rfc6265#section-5.2.4 +[rfc-6265-5.2.5]: https://tools.ietf.org/html/rfc6265#section-5.2.5 +[rfc-6265-5.2.6]: https://tools.ietf.org/html/rfc6265#section-5.2.6 +[rfc-6265-5.3]: https://tools.ietf.org/html/rfc6265#section-5.3 + +## License + +[MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/cookie/master +[coveralls-url]: https://coveralls.io/r/jshttp/cookie?branch=master +[github-actions-ci-image]: https://img.shields.io/github/workflow/status/jshttp/cookie/ci/master?label=ci +[github-actions-ci-url]: https://github.com/jshttp/cookie/actions/workflows/ci.yml +[node-version-image]: https://badgen.net/npm/node/cookie +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/cookie +[npm-url]: https://npmjs.org/package/cookie +[npm-version-image]: https://badgen.net/npm/v/cookie diff --git a/node_modules/@bundled-es-modules/cookie/node_modules/cookie/SECURITY.md b/node_modules/@bundled-es-modules/cookie/node_modules/cookie/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..fd4a6c53a9cd1abacf91125dab3fde3163b4c412 --- /dev/null +++ b/node_modules/@bundled-es-modules/cookie/node_modules/cookie/SECURITY.md @@ -0,0 +1,25 @@ +# Security Policies and Procedures + +## Reporting a Bug + +The `cookie` team and community take all security bugs seriously. Thank +you for improving the security of the project. We appreciate your efforts and +responsible disclosure and will make every effort to acknowledge your +contributions. + +Report security bugs by emailing the current owner(s) of `cookie`. This +information can be found in the npm registry using the command +`npm owner ls cookie`. +If unsure or unable to get the information from the above, open an issue +in the [project issue tracker](https://github.com/jshttp/cookie/issues) +asking for the current contact information. + +To ensure the timely response to your report, please ensure that the entirety +of the report is contained within the email body and not solely behind a web +link or an attachment. + +At least one owner will acknowledge your email within 48 hours, and will send a +more detailed response within 48 hours indicating the next steps in handling +your report. After the initial reply to your report, the owners will +endeavor to keep you informed of the progress towards a fix and full +announcement, and may ask for additional information or guidance. diff --git a/node_modules/@bundled-es-modules/cookie/node_modules/cookie/index.js b/node_modules/@bundled-es-modules/cookie/node_modules/cookie/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9c3d07d890de51262462fd80b2e13b7bd37d401d --- /dev/null +++ b/node_modules/@bundled-es-modules/cookie/node_modules/cookie/index.js @@ -0,0 +1,270 @@ +/*! + * cookie + * Copyright(c) 2012-2014 Roman Shtylman + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +exports.parse = parse; +exports.serialize = serialize; + +/** + * Module variables. + * @private + */ + +var __toString = Object.prototype.toString + +/** + * RegExp to match field-content in RFC 7230 sec 3.2 + * + * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + * field-vchar = VCHAR / obs-text + * obs-text = %x80-FF + */ + +var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; + +/** + * Parse a cookie header. + * + * Parse the given cookie header string into an object + * The object has the various cookies as keys(names) => values + * + * @param {string} str + * @param {object} [options] + * @return {object} + * @public + */ + +function parse(str, options) { + if (typeof str !== 'string') { + throw new TypeError('argument str must be a string'); + } + + var obj = {} + var opt = options || {}; + var dec = opt.decode || decode; + + var index = 0 + while (index < str.length) { + var eqIdx = str.indexOf('=', index) + + // no more cookie pairs + if (eqIdx === -1) { + break + } + + var endIdx = str.indexOf(';', index) + + if (endIdx === -1) { + endIdx = str.length + } else if (endIdx < eqIdx) { + // backtrack on prior semicolon + index = str.lastIndexOf(';', eqIdx - 1) + 1 + continue + } + + var key = str.slice(index, eqIdx).trim() + + // only assign once + if (undefined === obj[key]) { + var val = str.slice(eqIdx + 1, endIdx).trim() + + // quoted values + if (val.charCodeAt(0) === 0x22) { + val = val.slice(1, -1) + } + + obj[key] = tryDecode(val, dec); + } + + index = endIdx + 1 + } + + return obj; +} + +/** + * Serialize data into a cookie header. + * + * Serialize the a name value pair into a cookie string suitable for + * http headers. An optional options object specified cookie parameters. + * + * serialize('foo', 'bar', { httpOnly: true }) + * => "foo=bar; httpOnly" + * + * @param {string} name + * @param {string} val + * @param {object} [options] + * @return {string} + * @public + */ + +function serialize(name, val, options) { + var opt = options || {}; + var enc = opt.encode || encode; + + if (typeof enc !== 'function') { + throw new TypeError('option encode is invalid'); + } + + if (!fieldContentRegExp.test(name)) { + throw new TypeError('argument name is invalid'); + } + + var value = enc(val); + + if (value && !fieldContentRegExp.test(value)) { + throw new TypeError('argument val is invalid'); + } + + var str = name + '=' + value; + + if (null != opt.maxAge) { + var maxAge = opt.maxAge - 0; + + if (isNaN(maxAge) || !isFinite(maxAge)) { + throw new TypeError('option maxAge is invalid') + } + + str += '; Max-Age=' + Math.floor(maxAge); + } + + if (opt.domain) { + if (!fieldContentRegExp.test(opt.domain)) { + throw new TypeError('option domain is invalid'); + } + + str += '; Domain=' + opt.domain; + } + + if (opt.path) { + if (!fieldContentRegExp.test(opt.path)) { + throw new TypeError('option path is invalid'); + } + + str += '; Path=' + opt.path; + } + + if (opt.expires) { + var expires = opt.expires + + if (!isDate(expires) || isNaN(expires.valueOf())) { + throw new TypeError('option expires is invalid'); + } + + str += '; Expires=' + expires.toUTCString() + } + + if (opt.httpOnly) { + str += '; HttpOnly'; + } + + if (opt.secure) { + str += '; Secure'; + } + + if (opt.priority) { + var priority = typeof opt.priority === 'string' + ? opt.priority.toLowerCase() + : opt.priority + + switch (priority) { + case 'low': + str += '; Priority=Low' + break + case 'medium': + str += '; Priority=Medium' + break + case 'high': + str += '; Priority=High' + break + default: + throw new TypeError('option priority is invalid') + } + } + + if (opt.sameSite) { + var sameSite = typeof opt.sameSite === 'string' + ? opt.sameSite.toLowerCase() : opt.sameSite; + + switch (sameSite) { + case true: + str += '; SameSite=Strict'; + break; + case 'lax': + str += '; SameSite=Lax'; + break; + case 'strict': + str += '; SameSite=Strict'; + break; + case 'none': + str += '; SameSite=None'; + break; + default: + throw new TypeError('option sameSite is invalid'); + } + } + + return str; +} + +/** + * URL-decode string value. Optimized to skip native call when no %. + * + * @param {string} str + * @returns {string} + */ + +function decode (str) { + return str.indexOf('%') !== -1 + ? decodeURIComponent(str) + : str +} + +/** + * URL-encode value. + * + * @param {string} str + * @returns {string} + */ + +function encode (val) { + return encodeURIComponent(val) +} + +/** + * Determine if value is a Date. + * + * @param {*} val + * @private + */ + +function isDate (val) { + return __toString.call(val) === '[object Date]' || + val instanceof Date +} + +/** + * Try decoding a string using a decoding function. + * + * @param {string} str + * @param {function} decode + * @private + */ + +function tryDecode(str, decode) { + try { + return decode(str); + } catch (e) { + return str; + } +} diff --git a/node_modules/@bundled-es-modules/cookie/node_modules/cookie/package.json b/node_modules/@bundled-es-modules/cookie/node_modules/cookie/package.json new file mode 100644 index 0000000000000000000000000000000000000000..40cca5da923d5f8c80c8dfdec175d458b086cd77 --- /dev/null +++ b/node_modules/@bundled-es-modules/cookie/node_modules/cookie/package.json @@ -0,0 +1,82 @@ +{ + "_from": "cookie@^0.5.0", + "_id": "cookie@0.5.0", + "_inBundle": false, + "_integrity": "sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw==", + "_location": "/@bundled-es-modules/cookie/cookie", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "cookie@^0.5.0", + "name": "cookie", + "escapedName": "cookie", + "rawSpec": "^0.5.0", + "saveSpec": null, + "fetchSpec": "^0.5.0" + }, + "_requiredBy": [ + "/@bundled-es-modules/cookie" + ], + "_resolved": "https://registry.npmjs.org/cookie/-/cookie-0.5.0.tgz", + "_shasum": "d1f5d71adec6558c58f389987c366aa47e994f8b", + "_spec": "cookie@^0.5.0", + "_where": "/Users/sylvainfiloni/Documents/HuggingFace_Projects/live-vision/node_modules/@bundled-es-modules/cookie", + "author": { + "name": "Roman Shtylman", + "email": "shtylman@gmail.com" + }, + "bugs": { + "url": "https://github.com/jshttp/cookie/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "deprecated": false, + "description": "HTTP server cookie parsing and serialization", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "eslint": "7.32.0", + "eslint-plugin-markdown": "2.2.1", + "mocha": "9.2.2", + "nyc": "15.1.0", + "safe-buffer": "5.2.1", + "top-sites": "1.1.97" + }, + "engines": { + "node": ">= 0.6" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "SECURITY.md", + "index.js" + ], + "homepage": "https://github.com/jshttp/cookie#readme", + "keywords": [ + "cookie", + "cookies" + ], + "license": "MIT", + "name": "cookie", + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/cookie.git" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "update-bench": "node scripts/update-benchmark.js", + "version": "node scripts/version-history.js && git add HISTORY.md" + }, + "version": "0.5.0" +} diff --git a/node_modules/@bundled-es-modules/cookie/package.json b/node_modules/@bundled-es-modules/cookie/package.json new file mode 100644 index 0000000000000000000000000000000000000000..30cf9d75aa755e26c938bea312b95cd854690f57 --- /dev/null +++ b/node_modules/@bundled-es-modules/cookie/package.json @@ -0,0 +1,59 @@ +{ + "_from": "@bundled-es-modules/cookie@^2.0.0", + "_id": "@bundled-es-modules/cookie@2.0.0", + "_inBundle": false, + "_integrity": "sha512-Or6YHg/kamKHpxULAdSqhGqnWFneIXu1NKvvfBBzKGwpVsYuFIQ5aBPHDnnoR3ghW1nvSkALd+EF9iMtY7Vjxw==", + "_location": "/@bundled-es-modules/cookie", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@bundled-es-modules/cookie@^2.0.0", + "name": "@bundled-es-modules/cookie", + "escapedName": "@bundled-es-modules%2fcookie", + "scope": "@bundled-es-modules", + "rawSpec": "^2.0.0", + "saveSpec": null, + "fetchSpec": "^2.0.0" + }, + "_requiredBy": [ + "/msw" + ], + "_resolved": "https://registry.npmjs.org/@bundled-es-modules/cookie/-/cookie-2.0.0.tgz", + "_shasum": "c3b82703969a61cf6a46e959a012b2c257f6b164", + "_spec": "@bundled-es-modules/cookie@^2.0.0", + "_where": "/Users/sylvainfiloni/Documents/HuggingFace_Projects/live-vision/node_modules/msw", + "author": { + "name": "Pascal Schilp", + "email": "pascalschilp@gmail.com" + }, + "bundleDependencies": false, + "dependencies": { + "cookie": "^0.5.0" + }, + "deprecated": false, + "description": "mirror of cookie, bundled and exposed as ES module", + "devDependencies": { + "esbuild": "^0.17.17" + }, + "exports": { + ".": { + "import": "./index-esm.js", + "require": "./index-cjs.cjs" + } + }, + "files": [ + "index-esm.js", + "index-cjs.cjs" + ], + "keywords": [], + "license": "ISC", + "main": "index-esm.js", + "name": "@bundled-es-modules/cookie", + "scripts": { + "build": "esbuild source.js --bundle --format=esm --outfile=index.js", + "dev": "node --watch dev.js" + }, + "type": "module", + "version": "2.0.0" +} diff --git a/node_modules/@bundled-es-modules/statuses/README.md b/node_modules/@bundled-es-modules/statuses/README.md new file mode 100644 index 0000000000000000000000000000000000000000..dac56919fc8f94b8e6df2918da9b3b65dd981c30 --- /dev/null +++ b/node_modules/@bundled-es-modules/statuses/README.md @@ -0,0 +1,17 @@ +# statuses + +This is a mirror of [statuses](https://www.npmjs.com/package/statuses), bundled and exposed as ES module. + +## Install + +``` +npm install @bundled-es-modules/statuses +``` + +## Use + +```html + +``` \ No newline at end of file diff --git a/node_modules/@bundled-es-modules/statuses/index-cjs.cjs b/node_modules/@bundled-es-modules/statuses/index-cjs.cjs new file mode 100644 index 0000000000000000000000000000000000000000..274452e87289edc1f2dfb43638ded397893e7d6f --- /dev/null +++ b/node_modules/@bundled-es-modules/statuses/index-cjs.cjs @@ -0,0 +1,2 @@ +const status = require('statuses'); +module.exports = status; \ No newline at end of file diff --git a/node_modules/@bundled-es-modules/statuses/index-esm.js b/node_modules/@bundled-es-modules/statuses/index-esm.js new file mode 100644 index 0000000000000000000000000000000000000000..872044aeb0872b7e46105f21ec32f1cd76521ede --- /dev/null +++ b/node_modules/@bundled-es-modules/statuses/index-esm.js @@ -0,0 +1,184 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); + +// node_modules/statuses/codes.json +var require_codes = __commonJS({ + "node_modules/statuses/codes.json"(exports, module) { + module.exports = { + "100": "Continue", + "101": "Switching Protocols", + "102": "Processing", + "103": "Early Hints", + "200": "OK", + "201": "Created", + "202": "Accepted", + "203": "Non-Authoritative Information", + "204": "No Content", + "205": "Reset Content", + "206": "Partial Content", + "207": "Multi-Status", + "208": "Already Reported", + "226": "IM Used", + "300": "Multiple Choices", + "301": "Moved Permanently", + "302": "Found", + "303": "See Other", + "304": "Not Modified", + "305": "Use Proxy", + "307": "Temporary Redirect", + "308": "Permanent Redirect", + "400": "Bad Request", + "401": "Unauthorized", + "402": "Payment Required", + "403": "Forbidden", + "404": "Not Found", + "405": "Method Not Allowed", + "406": "Not Acceptable", + "407": "Proxy Authentication Required", + "408": "Request Timeout", + "409": "Conflict", + "410": "Gone", + "411": "Length Required", + "412": "Precondition Failed", + "413": "Payload Too Large", + "414": "URI Too Long", + "415": "Unsupported Media Type", + "416": "Range Not Satisfiable", + "417": "Expectation Failed", + "418": "I'm a Teapot", + "421": "Misdirected Request", + "422": "Unprocessable Entity", + "423": "Locked", + "424": "Failed Dependency", + "425": "Too Early", + "426": "Upgrade Required", + "428": "Precondition Required", + "429": "Too Many Requests", + "431": "Request Header Fields Too Large", + "451": "Unavailable For Legal Reasons", + "500": "Internal Server Error", + "501": "Not Implemented", + "502": "Bad Gateway", + "503": "Service Unavailable", + "504": "Gateway Timeout", + "505": "HTTP Version Not Supported", + "506": "Variant Also Negotiates", + "507": "Insufficient Storage", + "508": "Loop Detected", + "509": "Bandwidth Limit Exceeded", + "510": "Not Extended", + "511": "Network Authentication Required" + }; + } +}); + +// node_modules/statuses/index.js +var require_statuses = __commonJS({ + "node_modules/statuses/index.js"(exports, module) { + "use strict"; + var codes = require_codes(); + module.exports = status2; + status2.message = codes; + status2.code = createMessageToStatusCodeMap(codes); + status2.codes = createStatusCodeList(codes); + status2.redirect = { + 300: true, + 301: true, + 302: true, + 303: true, + 305: true, + 307: true, + 308: true + }; + status2.empty = { + 204: true, + 205: true, + 304: true + }; + status2.retry = { + 502: true, + 503: true, + 504: true + }; + function createMessageToStatusCodeMap(codes2) { + var map = {}; + Object.keys(codes2).forEach(function forEachCode(code) { + var message = codes2[code]; + var status3 = Number(code); + map[message.toLowerCase()] = status3; + }); + return map; + } + function createStatusCodeList(codes2) { + return Object.keys(codes2).map(function mapCode(code) { + return Number(code); + }); + } + function getStatusCode(message) { + var msg = message.toLowerCase(); + if (!Object.prototype.hasOwnProperty.call(status2.code, msg)) { + throw new Error('invalid status message: "' + message + '"'); + } + return status2.code[msg]; + } + function getStatusMessage(code) { + if (!Object.prototype.hasOwnProperty.call(status2.message, code)) { + throw new Error("invalid status code: " + code); + } + return status2.message[code]; + } + function status2(code) { + if (typeof code === "number") { + return getStatusMessage(code); + } + if (typeof code !== "string") { + throw new TypeError("code must be a number or string"); + } + var n = parseInt(code, 10); + if (!isNaN(n)) { + return getStatusMessage(n); + } + return getStatusCode(code); + } + } +}); + +// source.js +var import_statuses = __toESM(require_statuses(), 1); +var source_default = import_statuses.default; +export { + source_default as default +}; +/*! Bundled license information: + +statuses/index.js: + (*! + * statuses + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + *) +*/ diff --git a/node_modules/@bundled-es-modules/statuses/package.json b/node_modules/@bundled-es-modules/statuses/package.json new file mode 100644 index 0000000000000000000000000000000000000000..e41d7a7e04091499b49ceb2d5f264a01c32d38b0 --- /dev/null +++ b/node_modules/@bundled-es-modules/statuses/package.json @@ -0,0 +1,59 @@ +{ + "_from": "@bundled-es-modules/statuses@^1.0.1", + "_id": "@bundled-es-modules/statuses@1.0.1", + "_inBundle": false, + "_integrity": "sha512-yn7BklA5acgcBr+7w064fGV+SGIFySjCKpqjcWgBAIfrAkY+4GQTJJHQMeT3V/sgz23VTEVV8TtOmkvJAhFVfg==", + "_location": "/@bundled-es-modules/statuses", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@bundled-es-modules/statuses@^1.0.1", + "name": "@bundled-es-modules/statuses", + "escapedName": "@bundled-es-modules%2fstatuses", + "scope": "@bundled-es-modules", + "rawSpec": "^1.0.1", + "saveSpec": null, + "fetchSpec": "^1.0.1" + }, + "_requiredBy": [ + "/msw" + ], + "_resolved": "https://registry.npmjs.org/@bundled-es-modules/statuses/-/statuses-1.0.1.tgz", + "_shasum": "761d10f44e51a94902c4da48675b71a76cc98872", + "_spec": "@bundled-es-modules/statuses@^1.0.1", + "_where": "/Users/sylvainfiloni/Documents/HuggingFace_Projects/live-vision/node_modules/msw", + "author": { + "name": "Pascal Schilp", + "email": "pascalschilp@gmail.com" + }, + "bundleDependencies": false, + "dependencies": { + "statuses": "^2.0.1" + }, + "deprecated": false, + "description": "mirror of statuses, bundled and exposed as ES module", + "devDependencies": { + "esbuild": "^0.17.17" + }, + "exports": { + ".": { + "import": "./index-esm.js", + "require": "./index-cjs.cjs" + } + }, + "files": [ + "index-esm.js", + "index-cjs.cjs" + ], + "keywords": [], + "license": "ISC", + "main": "index-esm.js", + "name": "@bundled-es-modules/statuses", + "scripts": { + "build": "esbuild source.js --bundle --format=esm --outfile=index-esm.js", + "dev": "node dev.js" + }, + "type": "module", + "version": "1.0.1" +} diff --git a/node_modules/@gradio/.DS_Store b/node_modules/@gradio/.DS_Store deleted file mode 100644 index 89794c5909f890382306a25db7deb50054724627..0000000000000000000000000000000000000000 Binary files a/node_modules/@gradio/.DS_Store and /dev/null differ diff --git a/node_modules/@gradio/client/.DS_Store b/node_modules/@gradio/client/.DS_Store deleted file mode 100644 index feca8613504bcd7430524202412f605a970dd548..0000000000000000000000000000000000000000 Binary files a/node_modules/@gradio/client/.DS_Store and /dev/null differ diff --git a/node_modules/@gradio/client/CHANGELOG.md b/node_modules/@gradio/client/CHANGELOG.md index 7c0b67c8e3baf5b3e1c6289f1ffdb6149ce1fc43..e9e66289889c3b3611de41e97de84a8afd51bfec 100644 --- a/node_modules/@gradio/client/CHANGELOG.md +++ b/node_modules/@gradio/client/CHANGELOG.md @@ -1,5 +1,420 @@ # @gradio/client +## 1.1.1 + +### Features + +- [#8499](https://github.com/gradio-app/gradio/pull/8499) [`c5f6e77`](https://github.com/gradio-app/gradio/commit/c5f6e7722a197d4706419ade14276ddecf3196f8) - Cache break themes on change. Thanks @aliabid94! + +## 1.1.0 + +### Features + +- [#8483](https://github.com/gradio-app/gradio/pull/8483) [`e2271e2`](https://github.com/gradio-app/gradio/commit/e2271e207d98074bf39b02ae3c5443b2f097627d) - documentation for @gradio/client. Thanks @pngwn! +- [#8485](https://github.com/gradio-app/gradio/pull/8485) [`f8ebace`](https://github.com/gradio-app/gradio/commit/f8ebaceccef60a112603d290d10072ef4e938a6a) - Ensure all status are reported internally when calling `predict`. Thanks @pngwn! + +## 1.0.0 + +### Highlights + +#### Clients 1.0 Launch! ([#8468](https://github.com/gradio-app/gradio/pull/8468) [`7cc0a0c`](https://github.com/gradio-app/gradio/commit/7cc0a0c1abea585c3f50ffb1ff78d2b08ddbdd92)) + +We're excited to unveil the first major release of the Gradio clients. +We've made it even easier to turn any Gradio application into a production endpoint thanks to the clients' **ergonomic**, **transparent**, and **portable** design. + +#### Ergonomic API 💆 + +**Stream From a Gradio app in 5 lines** + +Use the `submit` method to get a job you can iterate over: + +```python +from gradio_client import Client + +client = Client("gradio/llm_stream") + +for result in client.submit("What's the best UI framework in Python?"): + print(result) +``` + +```ts +import { Client } from "@gradio/client"; + +const client = await Client.connect("gradio/llm_stream") +const job = client.submit("/predict", {"text": "What's the best UI framework in Python?"}) + +for await (const msg of job) console.log(msg.data) +``` + +**Use the same keyword arguments as the app** + + +```python +from gradio_client import Client + +client = Client("http://127.0.0.1:7860/") +result = client.predict( + message="Hello!!", + system_prompt="You are helpful AI.", + tokens=10, + api_name="/chat" +) +print(result) +``` + +```ts +import { Client } from "@gradio/client"; + +const client = await Client.connect("http://127.0.0.1:7860/"); +const result = await client.predict("/chat", { + message: "Hello!!", + system_prompt: "Hello!!", + tokens: 10, +}); + +console.log(result.data); +``` + +**Better Error Messages** + +If something goes wrong in the upstream app, the client will raise the same exception as the app provided that `show_error=True` in the original app's `launch()` function, or it's a `gr.Error` exception. + +#### Transparent Design 🪟 + +Anything you can do in the UI, you can do with the client: +* 🔒 Authentication +* 🛑 Job Cancelling +* ℹ️ Access Queue Position and API +* 📕 View the API information + +Here's an example showing how to display the queue position of a pending job: + +```python +from gradio_client import Client + +client = Client("gradio/diffusion_model") + +job = client.submit("A cute cat") +while not job.done(): + status = job.status() + print(f"Current in position {status.rank} out of {status.queue_size}") +``` + +#### Portable Design ⛺️ + +The client can run from pretty much any python and javascript environment (node, deno, the browser, Service Workers). + +Here's an example using the client from a Flask server using gevent: + +```python +from gevent import monkey +monkey.patch_all() + +from gradio_client import Client +from flask import Flask, send_file +import time + +app = Flask(__name__) + +imageclient = Client("gradio/diffusion_model") + +@app.route("/gen") +def gen(): + result = imageclient.predict( + "A cute cat", + api_name="/predict" + ) + return send_file(result) + +if __name__ == "__main__": + app.run(host="0.0.0.0", port=5000) +``` + +#### 1.0 Migration Guide and Breaking Changes + +**Python** +- The `serialize` argument of the `Client` class was removed. Has no effect. +- The `upload_files` argument of the `Client` was removed. +- All filepaths must be wrapped in the `handle_file` method. Example: +```python +from gradio_client import Client, handle_file + +client = Client("gradio/image_captioner") +client.predict(handle_file("cute_cat.jpg")) +``` +- The `output_dir` argument was removed. It is not specified in the `download_files` argument. + + +**Javascript** +The client has been redesigned entirely. It was refactored from a function into a class. An instance can now be constructed by awaiting the `connect` method. + +```js +const app = await Client.connect("gradio/whisper") +``` +The app variable has the same methods as the python class (`submit`, `predict`, `view_api`, `duplicate`). + + + +#### Additional Changes + +- [#8243](https://github.com/gradio-app/gradio/pull/8243) - Set orig_name in python client file uploads. +- [#8264](https://github.com/gradio-app/gradio/pull/8264) - Make exceptions in the Client more specific. +- [#8247](https://github.com/gradio-app/gradio/pull/8247) - Fix api recorder. +- [#8276](https://github.com/gradio-app/gradio/pull/8276) - Fix bug where client could not connect to apps that had self signed certificates. +- [#8245](https://github.com/gradio-app/gradio/pull/8245) - Cancel server progress from the python client. +- [#8200](https://github.com/gradio-app/gradio/pull/8200) - Support custom components in gr.load +- [#8182](https://github.com/gradio-app/gradio/pull/8182) - Convert sse calls in client from async to sync. +- [#7732](https://github.com/gradio-app/gradio/pull/7732) - Adds support for kwargs and default arguments in the python client, and improves how parameter information is displayed in the "view API" page. +- [#7888](https://github.com/gradio-app/gradio/pull/7888) - Cache view_api info in server and python client. +- [#7575](https://github.com/gradio-app/gradio/pull/7575) - Files should now be supplied as `file(...)` in the Client, and some fixes to `gr.load()` as well. +- [#8401](https://github.com/gradio-app/gradio/pull/8401) - Add CDN installation to JS docs. +- [#8299](https://github.com/gradio-app/gradio/pull/8299) - Allow JS Client to work with authenticated spaces 🍪. +- [#8408](https://github.com/gradio-app/gradio/pull/8408) - Connect heartbeat if state created in render. Also fix config cleanup bug #8407. +- [#8258](https://github.com/gradio-app/gradio/pull/8258) - Improve URL handling in JS Client. +- [#8322](https://github.com/gradio-app/gradio/pull/8322) - ensure the client correctly handles all binary data. +- [#8296](https://github.com/gradio-app/gradio/pull/8296) - always create a jwt when connecting to a space if a hf_token is present. +- [#8285](https://github.com/gradio-app/gradio/pull/8285) - use the correct query param to pass the jwt to the heartbeat event. +- [#8272](https://github.com/gradio-app/gradio/pull/8272) - ensure client works for private spaces. +- [#8197](https://github.com/gradio-app/gradio/pull/8197) - Add support for passing keyword args to `data` in JS client. +- [#8252](https://github.com/gradio-app/gradio/pull/8252) - Client node fix. +- [#8209](https://github.com/gradio-app/gradio/pull/8209) - Rename `eventSource_Factory` and `fetch_implementation`. +- [#8109](https://github.com/gradio-app/gradio/pull/8109) - Implement JS Client tests. +- [#8211](https://github.com/gradio-app/gradio/pull/8211) - remove redundant event source logic. +- [#8179](https://github.com/gradio-app/gradio/pull/8179) - rework upload to be a class method + pass client into each component. +- [#8181](https://github.com/gradio-app/gradio/pull/8181) - Ensure connectivity to private HF spaces with SSE protocol. +- [#8169](https://github.com/gradio-app/gradio/pull/8169) - Only connect to heartbeat if needed. +- [#8118](https://github.com/gradio-app/gradio/pull/8118) - Add eventsource polyfill for Node.js and browser environments. +- [#7646](https://github.com/gradio-app/gradio/pull/7646) - Refactor JS Client. +- [#7974](https://github.com/gradio-app/gradio/pull/7974) - Fix heartbeat in the js client to be Lite compatible. +- [#7926](https://github.com/gradio-app/gradio/pull/7926) - Fixes streaming event race condition. + + Thanks @freddyaboulton! + +### Features + +- [#8370](https://github.com/gradio-app/gradio/pull/8370) [`48eeea4`](https://github.com/gradio-app/gradio/commit/48eeea4eaab7e24168688e3c3fbafb30e4e78d51) - Refactor Cancelling Logic To Use /cancel. Thanks @freddyaboulton! + +### Fixes + +- [#8477](https://github.com/gradio-app/gradio/pull/8477) [`d5a9604`](https://github.com/gradio-app/gradio/commit/d5a960493017a4890685af61d78ce7d3b3b12e6b) - Fix js client bundle. Thanks @pngwn! +- [#8451](https://github.com/gradio-app/gradio/pull/8451) [`9d2d605`](https://github.com/gradio-app/gradio/commit/9d2d6051caed5c8749a26a6fa7480a5ae6e6c4f3) - Change client submit API to be an AsyncIterable and support more platforms. Thanks @pngwn! +- [#8462](https://github.com/gradio-app/gradio/pull/8462) [`6447dfa`](https://github.com/gradio-app/gradio/commit/6447dface4d46db1c69460e8325a1928d0476a46) - Improve file handling in JS Client. Thanks @hannahblair! +- [#8439](https://github.com/gradio-app/gradio/pull/8439) [`63d36fb`](https://github.com/gradio-app/gradio/commit/63d36fbbf4bf6dc909be9a0ffc7b6bf6621d83e8) - Handle gradio apps using `state` in the JS Client. Thanks @hannahblair! + +## 0.20.1 + +### Features + +- [#8415](https://github.com/gradio-app/gradio/pull/8415) [`227de35`](https://github.com/gradio-app/gradio/commit/227de352982b3dcdf9384eaa28b7e9cf09afb6e8) - Fix spaces load error. Thanks @aliabid94! + +## 0.20.0 + +### Features + +- [#8401](https://github.com/gradio-app/gradio/pull/8401) [`d078621`](https://github.com/gradio-app/gradio/commit/d078621928136c09ca902d2f37594ed887c67d2e) - Add CDN installation to JS docs. Thanks @hannahblair! +- [#8243](https://github.com/gradio-app/gradio/pull/8243) [`55f664f`](https://github.com/gradio-app/gradio/commit/55f664f2979a49acc29a73cde16c6ebdfcc91db2) - Add event listener support to render blocks. Thanks @aliabid94! +- [#8398](https://github.com/gradio-app/gradio/pull/8398) [`945ac83`](https://github.com/gradio-app/gradio/commit/945ac837e779b120790814ea6f6f81bd2712f5f8) - Improve rendering. Thanks @aliabid94! +- [#8299](https://github.com/gradio-app/gradio/pull/8299) [`ab65360`](https://github.com/gradio-app/gradio/commit/ab653608045ff9462db7ad9fe63e1c60bf20e773) - Allow JS Client to work with authenticated spaces 🍪. Thanks @hannahblair! + +### Fixes + +- [#8408](https://github.com/gradio-app/gradio/pull/8408) [`e86dd01`](https://github.com/gradio-app/gradio/commit/e86dd01b6e8f7bab3d3c25b84f2ad33129138af4) - Connect heartbeat if state created in render. Also fix config cleanup bug #8407. Thanks @freddyaboulton! +- [#8258](https://github.com/gradio-app/gradio/pull/8258) [`1f8e5c4`](https://github.com/gradio-app/gradio/commit/1f8e5c44e054b943052d8f24d044696ddfd01a54) - Improve URL handling in JS Client. Thanks @hannahblair! + +## 0.19.4 + +### Fixes + +- [#8322](https://github.com/gradio-app/gradio/pull/8322) [`47012a0`](https://github.com/gradio-app/gradio/commit/47012a0c4e3e8a80fcae620aaf08b16ceb343cde) - ensure the client correctly handles all binary data. Thanks @Saghen! + +## 0.19.3 + +### Features + +- [#8229](https://github.com/gradio-app/gradio/pull/8229) [`7c81897`](https://github.com/gradio-app/gradio/commit/7c81897076ddcd0bb05e0e4ffec35bb9a986d330) - chore(deps): update dependency esbuild to ^0.21.0. Thanks @renovate! + +### Fixes + +- [#8296](https://github.com/gradio-app/gradio/pull/8296) [`929d216`](https://github.com/gradio-app/gradio/commit/929d216d49aa05614bc83f0761cf7b1cd803d8fe) - always create a jwt when connecting to a space if a hf_token is present. Thanks @pngwn! + +## 0.19.2 + +### Fixes + +- [#8285](https://github.com/gradio-app/gradio/pull/8285) [`7d9d8ea`](https://github.com/gradio-app/gradio/commit/7d9d8eab50d36cbecbb84c6a0f3cc1bca7215604) - use the correct query param to pass the jwt to the heartbeat event. Thanks @pngwn! + +## 0.19.1 + +### Fixes + +- [#8272](https://github.com/gradio-app/gradio/pull/8272) [`fbf4edd`](https://github.com/gradio-app/gradio/commit/fbf4edde7c896cdf4c903463e44c31ed96111b3c) - ensure client works for private spaces. Thanks @pngwn! + +## 0.19.0 + +### Features + +- [#8110](https://github.com/gradio-app/gradio/pull/8110) [`5436031`](https://github.com/gradio-app/gradio/commit/5436031f92c1596282eb64e1e74d555f279e9697) - Render decorator 2. Thanks @aliabid94! +- [#8197](https://github.com/gradio-app/gradio/pull/8197) [`e09b4e8`](https://github.com/gradio-app/gradio/commit/e09b4e8216b970bc1b142a0f08e7d190b954eb35) - Add support for passing keyword args to `data` in JS client. Thanks @hannahblair! + +### Fixes + +- [#8252](https://github.com/gradio-app/gradio/pull/8252) [`22df61a`](https://github.com/gradio-app/gradio/commit/22df61a26adf8023f6dd49c051979990e8d3879a) - Client node fix. Thanks @pngwn! + +## 0.18.0 + +### Features + +- [#8121](https://github.com/gradio-app/gradio/pull/8121) [`f5b710c`](https://github.com/gradio-app/gradio/commit/f5b710c919b0ce604ea955f0d5f4faa91095ca4a) - chore(deps): update dependency eslint to v9. Thanks @renovate! +- [#8209](https://github.com/gradio-app/gradio/pull/8209) [`b9afe93`](https://github.com/gradio-app/gradio/commit/b9afe93915401df5bd6737c89395c2477acfa585) - Rename `eventSource_Factory` and `fetch_implementation`. Thanks @hannahblair! +- [#8109](https://github.com/gradio-app/gradio/pull/8109) [`bed2f82`](https://github.com/gradio-app/gradio/commit/bed2f82e2297b50f7b59423a3de05af0b9910724) - Implement JS Client tests. Thanks @hannahblair! +- [#8211](https://github.com/gradio-app/gradio/pull/8211) [`91b5cd6`](https://github.com/gradio-app/gradio/commit/91b5cd6132fb8903c92f70fce0800324836a1fc3) - remove redundant event source logic. Thanks @hannahblair! + +### Fixes + +- [#8179](https://github.com/gradio-app/gradio/pull/8179) [`6a218b4`](https://github.com/gradio-app/gradio/commit/6a218b4148095aaa0c58d8c20973ba01c8764fc2) - rework upload to be a class method + pass client into each component. Thanks @pngwn! +- [#8181](https://github.com/gradio-app/gradio/pull/8181) [`cf52ca6`](https://github.com/gradio-app/gradio/commit/cf52ca6a51320ece97f009a177792840b5fbc785) - Ensure connectivity to private HF spaces with SSE protocol. Thanks @hannahblair! +- [#8169](https://github.com/gradio-app/gradio/pull/8169) [`3a6f1a5`](https://github.com/gradio-app/gradio/commit/3a6f1a50b263e0a733f609a08019fc4d05480e1a) - Only connect to heartbeat if needed. Thanks @freddyaboulton! +- [#8118](https://github.com/gradio-app/gradio/pull/8118) [`7aca673`](https://github.com/gradio-app/gradio/commit/7aca673b38a087533524b2fd8dd3a03e0e4bacfe) - Add eventsource polyfill for Node.js and browser environments. Thanks @hannahblair! + +## 0.17.0 + +### Highlights + +#### Setting File Upload Limits ([#7909](https://github.com/gradio-app/gradio/pull/7909) [`2afca65`](https://github.com/gradio-app/gradio/commit/2afca6541912b37dc84f447c7ad4af21607d7c72)) + +We have added a `max_file_size` size parameter to `launch()` that limits to size of files uploaded to the server. This limit applies to each individual file. This parameter can be specified as a string or an integer (corresponding to the size in bytes). + +The following code snippet sets a max file size of 5 megabytes. + +```python +import gradio as gr + +demo = gr.Interface(lambda x: x, "image", "image") + +demo.launch(max_file_size="5mb") +# or +demo.launch(max_file_size=5 * gr.FileSize.MB) +``` + +![max_file_size_upload](https://github.com/gradio-app/gradio/assets/41651716/7547330c-a082-4901-a291-3f150a197e45) + + +#### Error states can now be cleared + +When a component encounters an error, the error state shown in the UI can now be cleared by clicking on the `x` icon in the top right of the component. This applies to all types of errors, whether it's raised in the UI or the server. + +![error_modal_calculator](https://github.com/gradio-app/gradio/assets/41651716/16cb071c-accd-45a6-9c18-0dea27d4bd98) + + Thanks @freddyaboulton! + +### Features + +- [#8056](https://github.com/gradio-app/gradio/pull/8056) [`2e469a5`](https://github.com/gradio-app/gradio/commit/2e469a5f99e52a5011a010f46e47dde7bb0c7140) - Using keys to preserve values between reloads. Thanks @aliabid94! +- [#7646](https://github.com/gradio-app/gradio/pull/7646) [`450b8cc`](https://github.com/gradio-app/gradio/commit/450b8cc898f130f15caa3742f65c17b9f7a8f398) - Refactor JS Client. Thanks @hannahblair! +- [#8061](https://github.com/gradio-app/gradio/pull/8061) [`17e83c9`](https://github.com/gradio-app/gradio/commit/17e83c958ebb35b3e122ca486067d1bd5ce33a22) - Docs Reorg and Intro Page. Thanks @aliabd! + +### Fixes + +- [#8066](https://github.com/gradio-app/gradio/pull/8066) [`624f9b9`](https://github.com/gradio-app/gradio/commit/624f9b9477f74a581a6c14119234f9efdfcda398) - make gradio dev tools a local dependency rather than bundling. Thanks @pngwn! + +## 0.16.0 + +### Features + +- [#7845](https://github.com/gradio-app/gradio/pull/7845) [`dbb7373`](https://github.com/gradio-app/gradio/commit/dbb7373dde69d4ed2741942b5a1898f8620cec24) - ensure `ImageEditor` events work as expected. Thanks @pngwn! + +### Fixes + +- [#7974](https://github.com/gradio-app/gradio/pull/7974) [`79e0aa8`](https://github.com/gradio-app/gradio/commit/79e0aa81c94e755faa6e85d76ac5d5a666313e6a) - Fix heartbeat in the js client to be Lite compatible. Thanks @whitphx! + +## 0.15.1 + +### Fixes + +- [#7926](https://github.com/gradio-app/gradio/pull/7926) [`9666854`](https://github.com/gradio-app/gradio/commit/966685479078f59430b3bced7e6068eb8157c003) - Fixes streaming event race condition. Thanks @aliabid94! + +## 0.15.0 + +### Highlights + +#### Automatically delete state after user has disconnected from the webpage ([#7829](https://github.com/gradio-app/gradio/pull/7829) [`6a4bf7a`](https://github.com/gradio-app/gradio/commit/6a4bf7abe29059dbdc6a342e0366fdaa2e4120ee)) + +Gradio now automatically deletes `gr.State` variables stored in the server's RAM when users close their browser tab. +The deletion will happen 60 minutes after the server detected a disconnect from the user's browser. +If the user connects again in that timeframe, their state will not be deleted. + +Additionally, Gradio now includes a `Blocks.unload()` event, allowing you to run arbitrary cleanup functions when users disconnect (this does not have a 60 minute delay). +You can think of the `unload` event as the opposite of the `load` event. + + +```python +with gr.Blocks() as demo: + gr.Markdown( +"""# State Cleanup Demo +🖼️ Images are saved in a user-specific directory and deleted when the users closes the page via demo.unload. +""") + with gr.Row(): + with gr.Column(scale=1): + with gr.Row(): + img = gr.Image(label="Generated Image", height=300, width=300) + with gr.Row(): + gen = gr.Button(value="Generate") + with gr.Row(): + history = gr.Gallery(label="Previous Generations", height=500, columns=10) + state = gr.State(value=[], delete_callback=lambda v: print("STATE DELETED")) + + demo.load(generate_random_img, [state], [img, state, history]) + gen.click(generate_random_img, [state], [img, state, history]) + demo.unload(delete_directory) + + +demo.launch(auth=lambda user,pwd: True, + auth_message="Enter any username and password to continue") +``` + + Thanks @freddyaboulton! + +## 0.14.0 + +### Features + +- [#7691](https://github.com/gradio-app/gradio/pull/7691) [`84f81fe`](https://github.com/gradio-app/gradio/commit/84f81fec9287b041203a141bbf2852720f7d199c) - Closing stream from the backend. Thanks @aliabid94! + +### Fixes + +- [#7564](https://github.com/gradio-app/gradio/pull/7564) [`5d1e8da`](https://github.com/gradio-app/gradio/commit/5d1e8dae5ac23f605c3b5f41dbe18751dff380a0) - batch UI updates on a per frame basis. Thanks @pngwn! + +## 0.13.0 + +### Fixes + +- [#7575](https://github.com/gradio-app/gradio/pull/7575) [`d0688b3`](https://github.com/gradio-app/gradio/commit/d0688b3c25feabb4fc7dfa0ab86086b3af7eb337) - Files should now be supplied as `file(...)` in the Client, and some fixes to `gr.load()` as well. Thanks @abidlabs! + +## 0.12.2 + +### Features + +- [#7528](https://github.com/gradio-app/gradio/pull/7528) [`eda33b3`](https://github.com/gradio-app/gradio/commit/eda33b3763897a542acf298e523fa493dc655aee) - Refactors `get_fetchable_url_or_file()` to remove it from the frontend. Thanks [@abidlabs](https://github.com/abidlabs)! +- [#7340](https://github.com/gradio-app/gradio/pull/7340) [`4b0d589`](https://github.com/gradio-app/gradio/commit/4b0d58933057432758a54169a360eb352903d6b4) - chore(deps): update all non-major dependencies. Thanks [@renovate](https://github.com/apps/renovate)! + +## 0.12.1 + +### Fixes + +- [#7411](https://github.com/gradio-app/gradio/pull/7411) [`32b317f`](https://github.com/gradio-app/gradio/commit/32b317f24e3d43f26684bb9f3964f31efd0ea556) - Set `root` correctly for Gradio apps that are deployed behind reverse proxies. Thanks [@abidlabs](https://github.com/abidlabs)! + +## 0.12.0 + +### Features + +- [#7183](https://github.com/gradio-app/gradio/pull/7183) [`49d9c48`](https://github.com/gradio-app/gradio/commit/49d9c48537aa706bf72628e3640389470138bdc6) - [WIP] Refactor file normalization to be in the backend and remove it from the frontend of each component. Thanks [@abidlabs](https://github.com/abidlabs)! + +## 0.11.0 + +### Features + +- [#7102](https://github.com/gradio-app/gradio/pull/7102) [`68a54a7`](https://github.com/gradio-app/gradio/commit/68a54a7a310d8d7072fdae930bf1cfdf12c45a7f) - Improve chatbot streaming performance with diffs. Thanks [@aliabid94](https://github.com/aliabid94)!/n Note that this PR changes the API format for generator functions, which would be a breaking change for any clients reading the EventStream directly + ## 0.10.1 ### Fixes diff --git a/node_modules/@gradio/client/README.md b/node_modules/@gradio/client/README.md index ddf80eb862ad5d36ec53cdef0f470d2aa67c41da..0da7a166c2e8105c41f8bca5575d658df4a2083f 100644 --- a/node_modules/@gradio/client/README.md +++ b/node_modules/@gradio/client/README.md @@ -1,29 +1,36 @@ ## JavaScript Client Library -A javascript (and typescript) client to call Gradio APIs. +Interact with Gradio APIs using our JavaScript (and TypeScript) client. + ## Installation -The Gradio JavaScript client is available on npm as `@gradio/client`. You can install it as below: +The Gradio JavaScript Client is available on npm as `@gradio/client`. You can install it as below: -```sh +```shell npm i @gradio/client ``` +Or, you can include it directly in your HTML via the jsDelivr CDN: + +```shell + +``` + ## Usage -The JavaScript Gradio Client exposes two named imports, `client` and `duplicate`. +The JavaScript Gradio Client exposes the Client class, `Client`, along with various other utility functions. `Client` is used to initialise and establish a connection to, or duplicate, a Gradio app. -### `client` +### `Client` -The client function connects to the API of a hosted Gradio space and returns an object that allows you to make calls to that API. +The Client function connects to the API of a hosted Gradio space and returns an object that allows you to make calls to that API. The simplest example looks like this: ```ts -import { client } from "@gradio/client"; +import { Client } from "@gradio/client"; -const app = await client("user/space-name"); +const app = await Client.connect("user/space-name"); const result = await app.predict("/predict"); ``` @@ -34,7 +41,7 @@ This function accepts two arguments: `source` and `options`: This is the url or name of the gradio app whose API you wish to connect to. This parameter is required and should always be a string. For example: ```ts -client("user/space-name"); +Client.connect("user/space-name"); ``` #### `options` @@ -48,23 +55,23 @@ This should be a Hugging Face personal access token and is required if you wish Example: ```ts -import { client } from "@gradio/client"; +import { Client } from "@gradio/client"; -const app = await client("user/space-name", { hf_token: "hf_..." }); +const app = await Client.connect("user/space-name", { hf_token: "hf_..." }); ``` ##### `status_callback` -This should be a function which will notify your of the status of a space if it is not running. If the gradio API you are connecting to is awake and running or is not hosted on Hugging Face space then this function will do nothing. +This should be a function which will notify you of the status of a space if it is not running. If the gradio API you are connecting to is not awake and running or is not hosted on Hugging Face space then this function will do nothing. **Additional context** Applications hosted on Hugging Face spaces can be in a number of different states. As spaces are a GitOps tool and will rebuild when new changes are pushed to the repository, they have various building, running and error states. If a space is not 'running' then the function passed as the `status_callback` will notify you of the current state of the space and the status of the space as it changes. Spaces that are building or sleeping can take longer than usual to respond, so you can use this information to give users feedback about the progress of their action. ```ts -import { client, type SpaceStatus } from "@gradio/client"; +import { Client, type SpaceStatus } from "@gradio/client"; -const app = await client("user/space-name", { +const app = await Client.connect("user/space-name", { // The space_status parameter does not need to be manually annotated, this is just for illustration. space_status: (space_status: SpaceStatus) => console.log(space_status) }); @@ -100,9 +107,9 @@ The gradio client returns an object with a number of methods and properties: The `predict` method allows you to call an api endpoint and get a prediction result: ```ts -import { client } from "@gradio/client"; +import { Client } from "@gradio/client"; -const app = await client("user/space-name"); +const app = await Client.connect("user/space-name"); const result = await app.predict("/predict"); ``` @@ -113,21 +120,25 @@ const result = await app.predict("/predict"); This is the endpoint for an api request and is required. The default endpoint for a `gradio.Interface` is `"/predict"`. Explicitly named endpoints have a custom name. The endpoint names can be found on the "View API" page of a space. ```ts -import { client } from "@gradio/client"; +import { Client } from "@gradio/client"; -const app = await client("user/space-name"); +const app = await Client.connect("user/space-name"); const result = await app.predict("/predict"); ``` ##### `payload` -The `payload` argument is generally optional but this depends on the API itself. If the API endpoint depends on values being passed in then it is required for the API request to succeed. The data that should be passed in is detailed on the "View API" page of a space, or accessible via the `view_api()` method of the client. +The `payload` argument is generally required but this depends on the API itself. If the API endpoint depends on values being passed in then the argument is required for the API request to succeed. The data that should be passed in is detailed on the "View API" page of a space, or accessible via the `view_api()` method of the client. ```ts -import { client } from "@gradio/client"; +import { Client } from "@gradio/client"; -const app = await client("user/space-name"); -const result = await app.predict("/predict", [1, "Hello", "friends"]); +const app = await Client.connect("user/space-name"); +const result = await app.predict("/predict", { + input: 1, + word_1: "Hello", + word_2: "friends" +}); ``` #### `submit` @@ -135,19 +146,27 @@ const result = await app.predict("/predict", [1, "Hello", "friends"]); The `submit` method provides a more flexible way to call an API endpoint, providing you with status updates about the current progress of the prediction as well as supporting more complex endpoint types. ```ts -import { client } from "@gradio/client"; +import { Client } from "@gradio/client"; -const app = await client("user/space-name"); -const submission = app.submit("/predict", payload); +const app = await Client.connect("user/space-name"); +const submission = app.submit("/predict", { name: "Chewbacca" }); ``` The `submit` method accepts the same [`endpoint`](#endpoint) and [`payload`](#payload) arguments as `predict`. -The `submit` method does not return a promise and should not be awaited, instead it returns an object with a `on`, `off`, and `cancel` methods. +The `submit` method does not return a promise and should not be awaited, instead it returns an async iterator with a `cancel` method. + +##### Accessing values -##### `on` +Iterating the submission allows you to access the events related to the submitted API request. There are two types of events that can be listened for: `"data"` updates and `"status"` updates. By default only the `"data"` event is reported, but you can listen for the `"status"` event by manually passing the events you care about when instantiating the client: -The `on` method allows you to subscribe to events related to the submitted API request. There are two types of event that can be subscribed to: `"data"` updates and `"status"` updates. +```ts +import { Client } from "@gradio/client"; + +const app = await Client.connect("user/space-name", { + events: ["data", "status"] +}); +``` `"data"` updates are issued when the API computes a value, the callback provided as the second argument will be called when such a value is sent to the client. The shape of the data depends on the way the API itself is constructed. This event may fire more than once if that endpoint supports emmitting new values over time. @@ -176,61 +195,38 @@ interface Status { } ``` -Usage of these subscribe callback looks like this: +Usage looks like this: ```ts -import { client } from "@gradio/client"; +import { Client } from "@gradio/client"; -const app = await client("user/space-name"); +const app = await Client.connect("user/space-name"); const submission = app - .submit("/predict", payload) - .on("data", (data) => console.log(data)) - .on("status", (status: Status) => console.log(status)); -``` - -##### `off` + .submit("/predict", { name: "Chewbacca" }) -The `off` method unsubscribes from a specific event of the submitted job and works similarly to `document.removeEventListener`; both the event name and the original callback must be passed in to successfully unsubscribe: + for await (const msg of submission) { + if (msg.type === "data") { + console.log(msg.data); + } -```ts -import { client } from "@gradio/client"; - -const app = await client("user/space-name"); -const handle_data = (data) => console.log(data); - -const submission = app.submit("/predict", payload).on("data", handle_data); - -// later -submission.off("/predict", handle_data); + if (msg.type === "status") { + console.log(msg); + } + } ``` -##### `destroy` - -The `destroy` method will remove all subscriptions to a job, regardless of whether or not they are `"data"` or `"status"` events. This is a convenience method for when you do not want to unsubscribe use the `off` method. - -```js -import { client } from "@gradio/client"; - -const app = await client("user/space-name"); -const handle_data = (data) => console.log(data); - -const submission = app.submit("/predict", payload).on("data", handle_data); - -// later -submission.destroy(); -``` ##### `cancel` Certain types of gradio function can run repeatedly and in some cases indefinitely. the `cancel` method will stop such an endpoints and prevent the API from issuing additional updates. ```ts -import { client } from "@gradio/client"; +import { Client } from "@gradio/client"; -const app = await client("user/space-name"); +const app = await Client.connect("user/space-name"); const submission = app - .submit("/predict", payload) - .on("data", (data) => console.log(data)); + .submit("/predict", { name: "Chewbacca" }) + // later @@ -242,9 +238,9 @@ submission.cancel(); The `view_api` method provides details about the API you are connected to. It returns a JavaScript object of all named endpoints, unnamed endpoints and what values they accept and return. This method does not accept arguments. ```ts -import { client } from "@gradio/client"; +import { Client } from "@gradio/client"; -const app = await client("user/space-name"); +const app = await Client.connect("user/space-name"); const api_info = await app.view_api(); console.log(api_info); @@ -255,9 +251,9 @@ console.log(api_info); The `config` property contains the configuration for the gradio application you are connected to. This object may contain useful meta information about the application. ```ts -import { client } from "@gradio/client"; +import { Client } from "@gradio/client"; -const app = await client("user/space-name"); +const app = await Client.connect("user/space-name"); console.log(app.config); ``` @@ -268,9 +264,9 @@ The duplicate function will attempt to duplicate the space that is referenced an `duplicate` accepts the same arguments as `client` with the addition of a `private` options property dictating whether the duplicated space should be private or public. A huggingface token is required for duplication to work. ```ts -import { duplicate } from "@gradio/client"; +import { Client } from "@gradio/client"; -const app = await duplicate("user/space-name", { +const app = await Client.duplicate("user/space-name", { hf_token: "hf_..." }); ``` @@ -292,9 +288,9 @@ Accepts all options that `client` accepts, except `hf_token` is required. [See ` This is an optional property specific to `duplicate`'s options object and will determine whether the space should be public or private. Spaces duplicated via the `duplicate` method are public by default. ```ts -import { duplicate } from "@gradio/client"; +import { Client } from "@gradio/client"; -const app = await duplicate("user/space-name", { +const app = await Client.duplicate("user/space-name", { hf_token: "hf_...", private: true }); @@ -305,9 +301,9 @@ const app = await duplicate("user/space-name", { This is an optional property specific to `duplicate`'s options object and will set the timeout in minutes before the duplicated space will go to sleep. ```ts -import { duplicate } from "@gradio/client"; +import { Client } from "@gradio/client"; -const app = await duplicate("user/space-name", { +const app = await Client.duplicate("user/space-name", { hf_token: "hf_...", private: true, timeout: 5 @@ -322,16 +318,22 @@ Possible hardware options are: - `"cpu-basic"` - `"cpu-upgrade"` +- `"cpu-xl"` - `"t4-small"` - `"t4-medium"` - `"a10g-small"` - `"a10g-large"` +- `"a10g-largex2"` +- `"a10g-largex4"` - `"a100-large"` +- `"zero-a10g"` +- `"h100"` +- `"h100x8"` ```ts -import { duplicate } from "@gradio/client"; +import { Client } from "@gradio/client"; -const app = await duplicate("user/space-name", { +const app = await Client.duplicate("user/space-name", { hf_token: "hf_...", private: true, hardware: "a10g-small" diff --git a/node_modules/@gradio/client/dist/client.d.ts b/node_modules/@gradio/client/dist/client.d.ts index 238887c0f3432b0a910f31a72ce1da5ba06d4686..69c0c70e718f2c68cdedd2923db55f46171d20f2 100644 --- a/node_modules/@gradio/client/dist/client.d.ts +++ b/node_modules/@gradio/client/dist/client.d.ts @@ -1,76 +1,70 @@ -import { hardware_types } from "./utils.js"; -import type { EventType, EventListener, PostResponse, UploadResponse, SpaceStatusCallback } from "./types.js"; -import type { Config } from "./types.js"; -type event = (eventType: K, listener: EventListener) => SubmitReturn; -type predict = (endpoint: string | number, data?: unknown[], event_data?: unknown) => Promise; -type client_return = { - predict: predict; - config: Config; - submit: (endpoint: string | number, data?: unknown[], event_data?: unknown, trigger_id?: number | null) => SubmitReturn; - component_server: (component_id: number, fn_name: string, data: unknown[]) => any; - view_api: (c?: Config) => Promise>; -}; -type SubmitReturn = { - on: event; - off: event; - cancel: () => Promise; - destroy: () => void; -}; -export declare let NodeBlob: any; -export declare function duplicate(app_reference: string, options: { - hf_token: `hf_${string}`; - private?: boolean; - status_callback: SpaceStatusCallback; - hardware?: (typeof hardware_types)[number]; - timeout?: number; -}): Promise; -interface Client { - post_data: (url: string, body: unknown, token?: `hf_${string}`) => Promise<[PostResponse, number]>; - upload_files: (root: string, files: File[], token?: `hf_${string}`, upload_id?: string) => Promise; - client: (app_reference: string, options: { - hf_token?: `hf_${string}`; - status_callback?: SpaceStatusCallback; - normalise_files?: boolean; - }) => Promise; - handle_blob: (endpoint: string, data: unknown[], api_info: ApiInfo, token?: `hf_${string}`) => Promise; -} -export declare function api_factory(fetch_implementation: typeof fetch, EventSource_factory: (url: URL) => EventSource): Client; -export declare const post_data: (url: string, body: unknown, token?: `hf_${string}`) => Promise<[PostResponse, number]>, upload_files: (root: string, files: File[], token?: `hf_${string}`, upload_id?: string) => Promise, client: (app_reference: string, options: { - hf_token?: `hf_${string}`; - status_callback?: SpaceStatusCallback; - normalise_files?: boolean; -}) => Promise, handle_blob: (endpoint: string, data: unknown[], api_info: ApiInfo, token?: `hf_${string}`) => Promise; -interface ApiData { - label: string; - type: { - type: any; - description: string; - }; - component: string; - example_input?: any; -} -interface JsApiData { - label: string; - type: string; - component: string; - example_input: any; -} -interface EndpointInfo { - parameters: T[]; - returns: T[]; -} -interface ApiInfo { - named_endpoints: { - [key: string]: EndpointInfo; - }; - unnamed_endpoints: { - [key: string]: EndpointInfo; +import type { ApiData, ApiInfo, ClientOptions, Config, DuplicateOptions, EndpointInfo, JsApiData, PredictReturn, SpaceStatus, Status, UploadResponse, SubmitIterable, GradioEvent } from "./types"; +import { FileData } from "./upload"; +export declare class Client { + app_reference: string; + options: ClientOptions; + config: Config | undefined; + api_info: ApiInfo | undefined; + api_map: Record; + session_hash: string; + jwt: string | false; + last_status: Record; + private cookies; + stream_status: { + open: boolean; }; + pending_stream_messages: Record; + pending_diff_streams: Record; + event_callbacks: Record Promise>; + unclosed_events: Set; + heartbeat_event: EventSource | null; + abort_controller: AbortController | null; + stream_instance: EventSource | null; + fetch(input: RequestInfo | URL, init?: RequestInit): Promise; + stream(url: URL): EventSource; + view_api: () => Promise>; + upload_files: (root_url: string, files: (Blob | File)[], upload_id?: string) => Promise; + upload: (file_data: FileData[], root_url: string, upload_id?: string, max_file_size?: number) => Promise<(FileData | null)[] | null>; + handle_blob: (endpoint: string, data: unknown[], endpoint_info: EndpointInfo) => Promise; + post_data: (url: string, body: unknown, additional_headers?: any) => Promise; + submit: (endpoint: string | number, data: unknown[] | Record, event_data?: unknown, trigger_id?: number | null, all_events?: boolean) => SubmitIterable; + predict: (endpoint: string | number, data: unknown[] | Record, event_data?: unknown) => Promise; + open_stream: () => Promise; + private resolve_config; + private resolve_cookies; + constructor(app_reference: string, options?: ClientOptions); + private init; + _resolve_hearbeat(_config: Config): Promise; + static connect(app_reference: string, options?: ClientOptions): Promise; + close(): void; + static duplicate(app_reference: string, options?: DuplicateOptions): Promise; + private _resolve_config; + private config_success; + handle_space_success(status: SpaceStatus): Promise; + component_server(component_id: number, fn_name: string, data: unknown[] | { + binary: boolean; + data: Record; + }): Promise; + set_cookies(raw_cookies: string): void; + private prepare_return_obj; } -export declare function walk_and_store_blobs(param: any, type?: any, path?: any[], root?: boolean, api_info?: any): Promise<{ - path: string[]; - type: string; - blob: Blob | false; -}[]>; -export {}; +/** + * @deprecated This method will be removed in v1.0. Use `Client.connect()` instead. + * Creates a client instance for interacting with Gradio apps. + * + * @param {string} app_reference - The reference or URL to a Gradio space or app. + * @param {ClientOptions} options - Configuration options for the client. + * @returns {Promise} A promise that resolves to a `Client` instance. + */ +export declare function client(app_reference: string, options?: ClientOptions): Promise; +/** + * @deprecated This method will be removed in v1.0. Use `Client.duplicate()` instead. + * Creates a duplicate of a space and returns a client instance for the duplicated space. + * + * @param {string} app_reference - The reference or URL to a Gradio space or app to duplicate. + * @param {DuplicateOptions} options - Configuration options for the client. + * @returns {Promise} A promise that resolves to a `Client` instance. + */ +export declare function duplicate_space(app_reference: string, options: DuplicateOptions): Promise; +export type ClientInstance = Client; //# sourceMappingURL=client.d.ts.map \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/client.d.ts.map b/node_modules/@gradio/client/dist/client.d.ts.map index 2dada055520b489bc4595e6afa9fcbf15ac9c668..bb1ba310c0cce5b3fab83c864cb774f4f0b98839 100644 --- a/node_modules/@gradio/client/dist/client.d.ts.map +++ b/node_modules/@gradio/client/dist/client.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"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"} \ No newline at end of file +{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"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"} \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/constants.d.ts b/node_modules/@gradio/client/dist/constants.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3acacf2404339fc177718be4bcd1e398756dd4a2 --- /dev/null +++ b/node_modules/@gradio/client/dist/constants.d.ts @@ -0,0 +1,30 @@ +export declare const HOST_URL = "host"; +export declare const API_URL = "api/predict/"; +export declare const SSE_URL_V0 = "queue/join"; +export declare const SSE_DATA_URL_V0 = "queue/data"; +export declare const SSE_URL = "queue/data"; +export declare const SSE_DATA_URL = "queue/join"; +export declare const UPLOAD_URL = "upload"; +export declare const LOGIN_URL = "login"; +export declare const CONFIG_URL = "config"; +export declare const API_INFO_URL = "info"; +export declare const RUNTIME_URL = "runtime"; +export declare const SLEEPTIME_URL = "sleeptime"; +export declare const RAW_API_INFO_URL = "info?serialize=False"; +export declare const SPACE_FETCHER_URL = "https://gradio-space-api-fetcher-v2.hf.space/api"; +export declare const RESET_URL = "reset"; +export declare const SPACE_URL = "https://hf.space/{}"; +export declare const QUEUE_FULL_MSG = "This application is currently busy. Please try again. "; +export declare const BROKEN_CONNECTION_MSG = "Connection errored out. "; +export declare const CONFIG_ERROR_MSG = "Could not resolve app config. "; +export declare const SPACE_STATUS_ERROR_MSG = "Could not get space status. "; +export declare const API_INFO_ERROR_MSG = "Could not get API info. "; +export declare const SPACE_METADATA_ERROR_MSG = "Space metadata could not be loaded. "; +export declare const INVALID_URL_MSG = "Invalid URL. A full URL path is required."; +export declare const UNAUTHORIZED_MSG = "Not authorized to access this space. "; +export declare const INVALID_CREDENTIALS_MSG = "Invalid credentials. Could not login. "; +export declare const MISSING_CREDENTIALS_MSG = "Login credentials are required to access this space."; +export declare const NODEJS_FS_ERROR_MSG = "File system access is only available in Node.js environments"; +export declare const ROOT_URL_ERROR_MSG = "Root URL not found in client config"; +export declare const FILE_PROCESSING_ERROR_MSG = "Error uploading file"; +//# sourceMappingURL=constants.d.ts.map \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/constants.d.ts.map b/node_modules/@gradio/client/dist/constants.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..90e5b5fedce4824f829cfc1ffa3fc63f1d07ff3c --- /dev/null +++ b/node_modules/@gradio/client/dist/constants.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,QAAQ,SAAS,CAAC;AAC/B,eAAO,MAAM,OAAO,iBAAiB,CAAC;AACtC,eAAO,MAAM,UAAU,eAAe,CAAC;AACvC,eAAO,MAAM,eAAe,eAAe,CAAC;AAC5C,eAAO,MAAM,OAAO,eAAe,CAAC;AACpC,eAAO,MAAM,YAAY,eAAe,CAAC;AACzC,eAAO,MAAM,UAAU,WAAW,CAAC;AACnC,eAAO,MAAM,SAAS,UAAU,CAAC;AACjC,eAAO,MAAM,UAAU,WAAW,CAAC;AACnC,eAAO,MAAM,YAAY,SAAS,CAAC;AACnC,eAAO,MAAM,WAAW,YAAY,CAAC;AACrC,eAAO,MAAM,aAAa,cAAc,CAAC;AACzC,eAAO,MAAM,gBAAgB,yBAAyB,CAAC;AACvD,eAAO,MAAM,iBAAiB,qDACqB,CAAC;AACpD,eAAO,MAAM,SAAS,UAAU,CAAC;AACjC,eAAO,MAAM,SAAS,wBAAwB,CAAC;AAG/C,eAAO,MAAM,cAAc,2DAC8B,CAAC;AAC1D,eAAO,MAAM,qBAAqB,6BAA6B,CAAC;AAChE,eAAO,MAAM,gBAAgB,mCAAmC,CAAC;AACjE,eAAO,MAAM,sBAAsB,iCAAiC,CAAC;AACrE,eAAO,MAAM,kBAAkB,6BAA6B,CAAC;AAC7D,eAAO,MAAM,wBAAwB,yCAAyC,CAAC;AAC/E,eAAO,MAAM,eAAe,8CAA8C,CAAC;AAC3E,eAAO,MAAM,gBAAgB,0CAA0C,CAAC;AACxE,eAAO,MAAM,uBAAuB,2CAA2C,CAAC;AAChF,eAAO,MAAM,uBAAuB,yDACmB,CAAC;AACxD,eAAO,MAAM,mBAAmB,iEAC+B,CAAC;AAChE,eAAO,MAAM,kBAAkB,wCAAwC,CAAC;AACxE,eAAO,MAAM,yBAAyB,yBAAyB,CAAC"} \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/helpers/api_info.d.ts b/node_modules/@gradio/client/dist/helpers/api_info.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3b869c24f5d891aad144e6e87f784456710adcda --- /dev/null +++ b/node_modules/@gradio/client/dist/helpers/api_info.d.ts @@ -0,0 +1,48 @@ +import type { Status } from "../types"; +import type { ApiData, ApiInfo, Config, JsApiData } from "../types"; +export declare const RE_SPACE_NAME: RegExp; +export declare const RE_SPACE_DOMAIN: RegExp; +export declare function process_endpoint(app_reference: string, hf_token?: `hf_${string}`): Promise<{ + space_id: string | false; + host: string; + ws_protocol: "ws" | "wss"; + http_protocol: "http:" | "https:"; +}>; +export declare const join_urls: (...urls: string[]) => string; +export declare function transform_api_info(api_info: ApiInfo, config: Config, api_map: Record): ApiInfo; +export declare function get_type(type: { + type: any; + description: string; +}, component: string, serializer: string, signature_type: "return" | "parameter"): string | undefined; +export declare function get_description(type: { + type: any; + description: string; +}, serializer: string): string; +export declare function handle_message(data: any, last_status: Status["stage"]): { + type: "hash" | "data" | "update" | "complete" | "generating" | "log" | "none" | "heartbeat" | "unexpected_error"; + data?: any; + status?: Status; +}; +/** + * Maps the provided `data` to the parameters defined by the `/info` endpoint response. + * This allows us to support both positional and keyword arguments passed to the client + * and ensures that all parameters are either directly provided or have default values assigned. + * + * @param {unknown[] | Record} data - The input data for the function, + * which can be either an array of values for positional arguments or an object + * with key-value pairs for keyword arguments. + * @param {JsApiData[]} parameters - Array of parameter descriptions retrieved from the + * `/info` endpoint. + * + * @returns {unknown[]} - Returns an array of resolved data where each element corresponds + * to the expected parameter from the API. The `parameter_default` value is used where + * a value is not provided for a parameter, and optional parameters without defaults are + * set to `undefined`. + * + * @throws {Error} - Throws an error: + * - If more arguments are provided than are defined in the parameters. + * * - If no parameter value is provided for a required parameter and no default value is defined. + * - If an argument is provided that does not match any defined parameter. + */ +export declare const map_data_to_params: (data: unknown[] | Record, api_info: ApiInfo) => unknown[]; +//# sourceMappingURL=api_info.d.ts.map \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/helpers/api_info.d.ts.map b/node_modules/@gradio/client/dist/helpers/api_info.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..e3cffc06764ffc854a568ff9de42cf859b699320 --- /dev/null +++ b/node_modules/@gradio/client/dist/helpers/api_info.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"api_info.d.ts","sourceRoot":"","sources":["../../src/helpers/api_info.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAOvC,OAAO,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAGpE,eAAO,MAAM,aAAa,QAA2C,CAAC;AACtE,eAAO,MAAM,eAAe,QAAwB,CAAC;AAErD,wBAAsB,gBAAgB,CACrC,aAAa,EAAE,MAAM,EACrB,QAAQ,CAAC,EAAE,MAAM,MAAM,EAAE,GACvB,OAAO,CAAC;IACV,QAAQ,EAAE,MAAM,GAAG,KAAK,CAAC;IACzB,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,IAAI,GAAG,KAAK,CAAC;IAC1B,aAAa,EAAE,OAAO,GAAG,QAAQ,CAAC;CAClC,CAAC,CA4CD;AAED,eAAO,MAAM,SAAS,YAAa,MAAM,EAAE,KAAG,MAU7C,CAAC;AAEF,wBAAgB,kBAAkB,CACjC,QAAQ,EAAE,OAAO,CAAC,OAAO,CAAC,EAC1B,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAC7B,OAAO,CAAC,SAAS,CAAC,CAsFpB;AAED,wBAAgB,QAAQ,CACvB,IAAI,EAAE;IAAE,IAAI,EAAE,GAAG,CAAC;IAAC,WAAW,EAAE,MAAM,CAAA;CAAE,EACxC,SAAS,EAAE,MAAM,EACjB,UAAU,EAAE,MAAM,EAClB,cAAc,EAAE,QAAQ,GAAG,WAAW,GACpC,MAAM,GAAG,SAAS,CAiCpB;AAED,wBAAgB,eAAe,CAC9B,IAAI,EAAE;IAAE,IAAI,EAAE,GAAG,CAAC;IAAC,WAAW,EAAE,MAAM,CAAA;CAAE,EACxC,UAAU,EAAE,MAAM,GAChB,MAAM,CASR;AAGD,wBAAgB,cAAc,CAC7B,IAAI,EAAE,GAAG,EACT,WAAW,EAAE,MAAM,CAAC,OAAO,CAAC,GAC1B;IACF,IAAI,EACD,MAAM,GACN,MAAM,GACN,QAAQ,GACR,UAAU,GACV,YAAY,GACZ,KAAK,GACL,MAAM,GACN,WAAW,GACX,kBAAkB,CAAC;IACtB,IAAI,CAAC,EAAE,GAAG,CAAC;IACX,MAAM,CAAC,EAAE,MAAM,CAAC;CAChB,CAmHA;AAGD;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,eAAO,MAAM,kBAAkB,SACxB,OAAO,EAAE,GAAG,OAAO,MAAM,EAAE,OAAO,CAAC,YAC/B,QAAQ,SAAS,GAAG,OAAO,CAAC,KACpC,OAAO,EA4CT,CAAC"} \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/helpers/data.d.ts b/node_modules/@gradio/client/dist/helpers/data.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..21650e191082bbb85d3574f70acc5d0e756c37d5 --- /dev/null +++ b/node_modules/@gradio/client/dist/helpers/data.d.ts @@ -0,0 +1,22 @@ +/// +import { type ApiData, type BlobRef, type Config, type EndpointInfo, type JsApiData, type DataType, Command, type Dependency, type ComponentMeta } from "../types"; +import { FileData } from "../upload"; +export declare function update_object(object: { + [x: string]: any; +}, newValue: any, stack: (string | number)[]): void; +export declare function walk_and_store_blobs(data: DataType, type?: string | undefined, path?: string[], root?: boolean, endpoint_info?: EndpointInfo | undefined): Promise; +export declare function skip_queue(id: number, config: Config): boolean; +export declare function post_message(message: any, origin: string): Promise; +export declare function handle_file(file_or_url: File | string | Blob | Buffer): FileData | Blob | Command; +/** + * Handles the payload by filtering out state inputs and returning an array of resolved payload values. + * We send null values for state inputs to the server, but we don't want to include them in the resolved payload. + * + * @param resolved_payload - The resolved payload values received from the client or the server + * @param dependency - The dependency object. + * @param components - The array of component metadata. + * @param with_null_state - Optional. Specifies whether to include null values for state inputs. Default is false. + * @returns An array of resolved payload values, filtered based on the dependency and component metadata. + */ +export declare function handle_payload(resolved_payload: unknown[], dependency: Dependency, components: ComponentMeta[], type: "input" | "output", with_null_state?: boolean): unknown[]; +//# sourceMappingURL=data.d.ts.map \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/helpers/data.d.ts.map b/node_modules/@gradio/client/dist/helpers/data.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..5209e6d3d161898e264b0a87b17d8339f2a382d1 --- /dev/null +++ b/node_modules/@gradio/client/dist/helpers/data.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"data.d.ts","sourceRoot":"","sources":["../../src/helpers/data.ts"],"names":[],"mappings":";AAAA,OAAO,EACN,KAAK,OAAO,EACZ,KAAK,OAAO,EACZ,KAAK,MAAM,EACX,KAAK,YAAY,EACjB,KAAK,SAAS,EACd,KAAK,QAAQ,EACb,OAAO,EACP,KAAK,UAAU,EACf,KAAK,aAAa,EAClB,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAKrC,wBAAgB,aAAa,CAC5B,MAAM,EAAE;IAAE,CAAC,CAAC,EAAE,MAAM,GAAG,GAAG,CAAA;CAAE,EAC5B,QAAQ,EAAE,GAAG,EACb,KAAK,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,GACxB,IAAI,CAgBN;AAED,wBAAsB,oBAAoB,CACzC,IAAI,EAAE,QAAQ,EACd,IAAI,GAAE,MAAM,GAAG,SAAqB,EACpC,IAAI,GAAE,MAAM,EAAO,EACnB,IAAI,UAAQ,EACZ,aAAa,GAAE,YAAY,CAAC,OAAO,GAAG,SAAS,CAAC,GAAG,SAAqB,GACtE,OAAO,CAAC,OAAO,EAAE,CAAC,CAwDpB;AAED,wBAAgB,UAAU,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAM9D;AAID,wBAAgB,YAAY,CAAC,GAAG,GAAG,GAAG,EACrC,OAAO,EAAE,GAAG,EACZ,MAAM,EAAE,MAAM,GACZ,OAAO,CAAC,GAAG,CAAC,CASd;AAED,wBAAgB,WAAW,CAC1B,WAAW,EAAE,IAAI,GAAG,MAAM,GAAG,IAAI,GAAG,MAAM,GACxC,QAAQ,GAAG,IAAI,GAAG,OAAO,CA8C3B;AAED;;;;;;;;;GASG;AACH,wBAAgB,cAAc,CAC7B,gBAAgB,EAAE,OAAO,EAAE,EAC3B,UAAU,EAAE,UAAU,EACtB,UAAU,EAAE,aAAa,EAAE,EAC3B,IAAI,EAAE,OAAO,GAAG,QAAQ,EACxB,eAAe,UAAQ,GACrB,OAAO,EAAE,CAyCX"} \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/utils.d.ts b/node_modules/@gradio/client/dist/helpers/init_helpers.d.ts similarity index 55% rename from node_modules/@gradio/client/dist/utils.d.ts rename to node_modules/@gradio/client/dist/helpers/init_helpers.d.ts index c648475f8a1c1536686c70e53cba048d2548e17f..01057464325f0a88855cd3e6746e8dd81189c703 100644 --- a/node_modules/@gradio/client/dist/utils.d.ts +++ b/node_modules/@gradio/client/dist/helpers/init_helpers.d.ts @@ -1,4 +1,5 @@ -import type { Config } from "./types.js"; +import type { Config } from "../types"; +import { Client } from ".."; /** * This function is used to resolve the URL for making requests when the app has a root path. * The root path could be a path suffix like "/app" which is appended to the end of the base URL. Or @@ -10,23 +11,15 @@ import type { Config } from "./types.js"; * @returns {string} the resolved URL */ export declare function resolve_root(base_url: string, root_path: string, prioritize_base: boolean): string; +export declare function get_jwt(space: string, token: `hf_${string}`, cookies?: string | null): Promise; +export declare function map_names_to_ids(fns: Config["dependencies"]): Record; +export declare function resolve_config(this: Client, endpoint: string): Promise; +export declare function resolve_cookies(this: Client): Promise; +export declare function get_cookie_header(http_protocol: string, host: string, auth: [string, string], _fetch: typeof fetch, hf_token?: `hf_${string}`): Promise; export declare function determine_protocol(endpoint: string): { ws_protocol: "ws" | "wss"; http_protocol: "http:" | "https:"; host: string; }; -export declare const RE_SPACE_NAME: RegExp; -export declare const RE_SPACE_DOMAIN: RegExp; -export declare function process_endpoint(app_reference: string, token?: `hf_${string}`): Promise<{ - space_id: string | false; - host: string; - ws_protocol: "ws" | "wss"; - http_protocol: "http:" | "https:"; -}>; -export declare function map_names_to_ids(fns: Config["dependencies"]): Record; -export declare function discussions_enabled(space_id: string): Promise; -export declare function get_space_hardware(space_id: string, token: `hf_${string}`): Promise<(typeof hardware_types)[number]>; -export declare function set_space_hardware(space_id: string, new_hardware: (typeof hardware_types)[number], token: `hf_${string}`): Promise<(typeof hardware_types)[number]>; -export declare function set_space_timeout(space_id: string, timeout: number, token: `hf_${string}`): Promise; -export declare const hardware_types: readonly ["cpu-basic", "cpu-upgrade", "t4-small", "t4-medium", "a10g-small", "a10g-large", "a100-large"]; -//# sourceMappingURL=utils.d.ts.map \ No newline at end of file +export declare const parse_and_set_cookies: (cookie_header: string) => string[]; +//# sourceMappingURL=init_helpers.d.ts.map \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/helpers/init_helpers.d.ts.map b/node_modules/@gradio/client/dist/helpers/init_helpers.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..ef3bbba16762ff68e88d498f715eb8f4e4f995ea --- /dev/null +++ b/node_modules/@gradio/client/dist/helpers/init_helpers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"init_helpers.d.ts","sourceRoot":"","sources":["../../src/helpers/init_helpers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAUvC,OAAO,EAAE,MAAM,EAAE,MAAM,IAAI,CAAC;AAG5B;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAC3B,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,MAAM,EACjB,eAAe,EAAE,OAAO,GACtB,MAAM,CAKR;AAED,wBAAsB,OAAO,CAC5B,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,MAAM,MAAM,EAAE,EACrB,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,GACrB,OAAO,CAAC,MAAM,GAAG,KAAK,CAAC,CAezB;AAED,wBAAgB,gBAAgB,CAC/B,GAAG,EAAE,MAAM,CAAC,cAAc,CAAC,GACzB,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAOxB;AAED,wBAAsB,cAAc,CACnC,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,MAAM,GACd,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CA+C7B;AAED,wBAAsB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAqBjE;AAGD,wBAAsB,iBAAiB,CACtC,aAAa,EAAE,MAAM,EACrB,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,EACtB,MAAM,EAAE,OAAO,KAAK,EACpB,QAAQ,CAAC,EAAE,MAAM,MAAM,EAAE,GACvB,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAyBxB;AAED,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,GAAG;IACrD,WAAW,EAAE,IAAI,GAAG,KAAK,CAAC;IAC1B,aAAa,EAAE,OAAO,GAAG,QAAQ,CAAC;IAClC,IAAI,EAAE,MAAM,CAAC;CACb,CAgCA;AAED,eAAO,MAAM,qBAAqB,kBAAmB,MAAM,KAAG,MAAM,EAUnE,CAAC"} \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/helpers/spaces.d.ts b/node_modules/@gradio/client/dist/helpers/spaces.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c6efab4c905018c4529b329a18a3adc02f624e06 --- /dev/null +++ b/node_modules/@gradio/client/dist/helpers/spaces.d.ts @@ -0,0 +1,7 @@ +import type { SpaceStatusCallback } from "../types"; +export declare function check_space_status(id: string, type: "subdomain" | "space_name", status_callback: SpaceStatusCallback): Promise; +export declare function discussions_enabled(space_id: string): Promise; +export declare function get_space_hardware(space_id: string, hf_token?: `hf_${string}` | undefined): Promise<(typeof hardware_types)[number]>; +export declare function set_space_timeout(space_id: string, timeout: number, hf_token?: `hf_${string}`): Promise; +export declare const hardware_types: readonly ["cpu-basic", "cpu-upgrade", "cpu-xl", "t4-small", "t4-medium", "a10g-small", "a10g-large", "a10g-largex2", "a10g-largex4", "a100-large", "zero-a10g", "h100", "h100x8"]; +//# sourceMappingURL=spaces.d.ts.map \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/helpers/spaces.d.ts.map b/node_modules/@gradio/client/dist/helpers/spaces.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..68cc6df3df177851b85292a10c538275c5463f03 --- /dev/null +++ b/node_modules/@gradio/client/dist/helpers/spaces.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"spaces.d.ts","sourceRoot":"","sources":["../../src/helpers/spaces.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,UAAU,CAAC;AAEpD,wBAAsB,kBAAkB,CACvC,EAAE,EAAE,MAAM,EACV,IAAI,EAAE,WAAW,GAAG,YAAY,EAChC,eAAe,EAAE,mBAAmB,GAClC,OAAO,CAAC,IAAI,CAAC,CAqFf;AAID,wBAAsB,mBAAmB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAgB5E;AAED,wBAAsB,kBAAkB,CACvC,QAAQ,EAAE,MAAM,EAChB,QAAQ,CAAC,EAAE,MAAM,MAAM,EAAE,GAAG,SAAS,GACnC,OAAO,CAAC,CAAC,OAAO,cAAc,CAAC,CAAC,MAAM,CAAC,CAAC,CAqB1C;AAED,wBAAsB,iBAAiB,CACtC,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,EACf,QAAQ,CAAC,EAAE,MAAM,MAAM,EAAE,GACvB,OAAO,CAAC,GAAG,CAAC,CAiCd;AAED,eAAO,MAAM,cAAc,mLAcjB,CAAC"} \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/index.d.ts b/node_modules/@gradio/client/dist/index.d.ts index 0c21b54f2297fb5301cfbdcf9b557ba72d5e601e..f299d40746c097942325de20fa7068c992834ccc 100644 --- a/node_modules/@gradio/client/dist/index.d.ts +++ b/node_modules/@gradio/client/dist/index.d.ts @@ -1,4 +1,10 @@ -export { client, post_data, upload_files, duplicate, api_factory } from "./client.js"; -export type { SpaceStatus } from "./types.js"; -export { normalise_file, FileData, upload, get_fetchable_url_or_file, prepare_files } from "./upload.js"; +export { Client } from "./client"; +export { predict } from "./utils/predict"; +export { submit } from "./utils/submit"; +export { upload_files } from "./utils/upload_files"; +export { FileData, upload, prepare_files } from "./upload"; +export { handle_file } from "./helpers/data"; +export type { SpaceStatus, StatusMessage, Status, client_return, UploadResponse, RenderMessage, LogMessage, Payload } from "./types"; +export { client } from "./client"; +export { duplicate_space as duplicate } from "./client"; //# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/index.d.ts.map b/node_modules/@gradio/client/dist/index.d.ts.map index a40541d0bf5b1dd20e19902fce17bb739086cf2d..14065ed2bcc7f3c01134ccd29160ff2f5ea9cf92 100644 --- a/node_modules/@gradio/client/dist/index.d.ts.map +++ b/node_modules/@gradio/client/dist/index.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,MAAM,EACN,SAAS,EACT,YAAY,EACZ,SAAS,EACT,WAAW,EACX,MAAM,aAAa,CAAC;AACrB,YAAY,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,EACN,cAAc,EACd,QAAQ,EACR,MAAM,EACN,yBAAyB,EACzB,aAAa,EACb,MAAM,aAAa,CAAC"} \ No newline at end of file +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAElC,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC1C,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACxC,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAC3D,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAE7C,YAAY,EACX,WAAW,EACX,aAAa,EACb,MAAM,EACN,aAAa,EACb,cAAc,EACd,aAAa,EACb,UAAU,EACV,OAAO,EACP,MAAM,SAAS,CAAC;AAGjB,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,OAAO,EAAE,eAAe,IAAI,SAAS,EAAE,MAAM,UAAU,CAAC"} \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/index.js b/node_modules/@gradio/client/dist/index.js index 34ef1d61a45c279ea9cc057f52a6ce19b9418389..d83cd4ea31fea624eae86fa286cc0d9e878c2f04 100644 --- a/node_modules/@gradio/client/dist/index.js +++ b/node_modules/@gradio/client/dist/index.js @@ -1,18 +1,167 @@ +var __defProp = Object.defineProperty; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; +}; +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 _currentLine; var fn = new Intl.Collator(0, { numeric: 1 }).compare; function semiver(a, b, bool) { a = a.split("."); b = b.split("."); return fn(a[0], b[0]) || fn(a[1], b[1]) || (b[2] = b.slice(2).join("."), bool = /[.-]/.test(a[2] = a.slice(2).join(".")), bool == /[.-]/.test(b[2]) ? fn(a[2], b[2]) : bool ? -1 : 1); } +const HOST_URL = "host"; +const UPLOAD_URL = "upload"; +const LOGIN_URL = "login"; +const CONFIG_URL = "config"; +const API_INFO_URL = "info"; +const RUNTIME_URL = "runtime"; +const SLEEPTIME_URL = "sleeptime"; +const SPACE_FETCHER_URL = "https://gradio-space-api-fetcher-v2.hf.space/api"; +const QUEUE_FULL_MSG = "This application is currently busy. Please try again. "; +const BROKEN_CONNECTION_MSG = "Connection errored out. "; +const CONFIG_ERROR_MSG = "Could not resolve app config. "; +const SPACE_STATUS_ERROR_MSG = "Could not get space status. "; +const API_INFO_ERROR_MSG = "Could not get API info. "; +const SPACE_METADATA_ERROR_MSG = "Space metadata could not be loaded. "; +const INVALID_URL_MSG = "Invalid URL. A full URL path is required."; +const UNAUTHORIZED_MSG = "Not authorized to access this space. "; +const INVALID_CREDENTIALS_MSG = "Invalid credentials. Could not login. "; +const MISSING_CREDENTIALS_MSG = "Login credentials are required to access this space."; +const NODEJS_FS_ERROR_MSG = "File system access is only available in Node.js environments"; +const ROOT_URL_ERROR_MSG = "Root URL not found in client config"; +const FILE_PROCESSING_ERROR_MSG = "Error uploading file"; function resolve_root(base_url, root_path, prioritize_base) { if (root_path.startsWith("http://") || root_path.startsWith("https://")) { return prioritize_base ? base_url : root_path; } return base_url + root_path; } +async function get_jwt(space, token, cookies) { + try { + const r = await fetch(`https://huggingface.co/api/spaces/${space}/jwt`, { + headers: { + Authorization: `Bearer ${token}`, + ...cookies ? { Cookie: cookies } : {} + } + }); + const jwt = (await r.json()).token; + return jwt || false; + } catch (e) { + return false; + } +} +function map_names_to_ids(fns) { + let apis = {}; + fns.forEach(({ api_name, id }) => { + if (api_name) + apis[api_name] = id; + }); + return apis; +} +async function resolve_config(endpoint) { + var _a; + const headers = this.options.hf_token ? { Authorization: `Bearer ${this.options.hf_token}` } : {}; + headers["Content-Type"] = "application/json"; + if (typeof window !== "undefined" && window.gradio_config && location.origin !== "http://localhost:9876" && !window.gradio_config.dev_mode) { + const path = window.gradio_config.root; + const config = window.gradio_config; + let config_root = resolve_root(endpoint, config.root, false); + config.root = config_root; + return { ...config, path }; + } else if (endpoint) { + const config_url = join_urls(endpoint, CONFIG_URL); + const response = await this.fetch(config_url, { + headers, + credentials: "include" + }); + if ((response == null ? void 0 : response.status) === 401 && !this.options.auth) { + throw new Error(MISSING_CREDENTIALS_MSG); + } else if ((response == null ? void 0 : response.status) === 401 && this.options.auth) { + throw new Error(INVALID_CREDENTIALS_MSG); + } + if ((response == null ? void 0 : response.status) === 200) { + let config = await response.json(); + config.path = config.path ?? ""; + config.root = endpoint; + (_a = config.dependencies) == null ? void 0 : _a.forEach((dep, i) => { + if (dep.id === void 0) { + dep.id = i; + } + }); + return config; + } else if ((response == null ? void 0 : response.status) === 401) { + throw new Error(UNAUTHORIZED_MSG); + } + throw new Error(CONFIG_ERROR_MSG); + } + throw new Error(CONFIG_ERROR_MSG); +} +async function resolve_cookies() { + const { http_protocol, host } = await process_endpoint( + this.app_reference, + this.options.hf_token + ); + try { + if (this.options.auth) { + const cookie_header = await get_cookie_header( + http_protocol, + host, + this.options.auth, + this.fetch, + this.options.hf_token + ); + if (cookie_header) + this.set_cookies(cookie_header); + } + } catch (e) { + throw Error(e.message); + } +} +async function get_cookie_header(http_protocol, host, auth, _fetch, hf_token) { + const formData = new FormData(); + formData.append("username", auth == null ? void 0 : auth[0]); + formData.append("password", auth == null ? void 0 : auth[1]); + let headers = {}; + if (hf_token) { + headers.Authorization = `Bearer ${hf_token}`; + } + const res = await _fetch(`${http_protocol}//${host}/${LOGIN_URL}`, { + headers, + method: "POST", + body: formData, + credentials: "include" + }); + if (res.status === 200) { + return res.headers.get("set-cookie"); + } else if (res.status === 401) { + throw new Error(INVALID_CREDENTIALS_MSG); + } else { + throw new Error(SPACE_METADATA_ERROR_MSG); + } +} function determine_protocol(endpoint) { if (endpoint.startsWith("http")) { - const { protocol, host } = new URL(endpoint); + const { protocol, host, pathname } = new URL(endpoint); if (host.endsWith("hf.space")) { return { ws_protocol: "wss", @@ -23,7 +172,7 @@ function determine_protocol(endpoint) { return { ws_protocol: protocol === "https:" ? "wss" : "ws", http_protocol: protocol, - host + host: host + (pathname !== "/" ? pathname : "") }; } else if (endpoint.startsWith("file:")) { return { @@ -39,29 +188,38 @@ function determine_protocol(endpoint) { host: endpoint }; } -const RE_SPACE_NAME = /^[^\/]*\/[^\/]*$/; +const parse_and_set_cookies = (cookie_header) => { + let cookies = []; + const parts = cookie_header.split(/,(?=\s*[^\s=;]+=[^\s=;]+)/); + parts.forEach((cookie) => { + const [cookie_name, cookie_value] = cookie.split(";")[0].split("="); + if (cookie_name && cookie_value) { + cookies.push(`${cookie_name.trim()}=${cookie_value.trim()}`); + } + }); + return cookies; +}; +const RE_SPACE_NAME = /^[a-zA-Z0-9_\-\.]+\/[a-zA-Z0-9_\-\.]+$/; const RE_SPACE_DOMAIN = /.*hf\.space\/{0,1}$/; -async function process_endpoint(app_reference, token) { +async function process_endpoint(app_reference, hf_token) { const headers = {}; - if (token) { - headers.Authorization = `Bearer ${token}`; + if (hf_token) { + headers.Authorization = `Bearer ${hf_token}`; } - const _app_reference = app_reference.trim(); + const _app_reference = app_reference.trim().replace(/\/$/, ""); if (RE_SPACE_NAME.test(_app_reference)) { try { const res = await fetch( - `https://huggingface.co/api/spaces/${_app_reference}/host`, + `https://huggingface.co/api/spaces/${_app_reference}/${HOST_URL}`, { headers } ); - if (res.status !== 200) - throw new Error("Space metadata could not be loaded."); const _host = (await res.json()).host; return { space_id: app_reference, ...determine_protocol(_host) }; } catch (e) { - throw new Error("Space metadata could not be loaded." + e.message); + throw new Error(SPACE_METADATA_ERROR_MSG); } } if (RE_SPACE_DOMAIN.test(_app_reference)) { @@ -78,161 +236,371 @@ async function process_endpoint(app_reference, token) { ...determine_protocol(_app_reference) }; } -function map_names_to_ids(fns) { - let apis = {}; - fns.forEach(({ api_name }, i) => { - if (api_name) - apis[api_name] = i; - }); - return apis; -} -const RE_DISABLED_DISCUSSION = /^(?=[^]*\b[dD]iscussions{0,1}\b)(?=[^]*\b[dD]isabled\b)[^]*$/; -async function discussions_enabled(space_id) { +const join_urls = (...urls) => { try { - const r = await fetch( - `https://huggingface.co/api/spaces/${space_id}/discussions`, - { - method: "HEAD" - } - ); - const error = r.headers.get("x-error-message"); - if (error && RE_DISABLED_DISCUSSION.test(error)) - return false; - return true; + return urls.reduce((base_url, part) => { + base_url = base_url.replace(/\/+$/, ""); + part = part.replace(/^\/+/, ""); + return new URL(part, base_url + "/").toString(); + }); } catch (e) { - return false; + throw new Error(INVALID_URL_MSG); } +}; +function transform_api_info(api_info, config, api_map) { + const transformed_info = { + named_endpoints: {}, + unnamed_endpoints: {} + }; + Object.keys(api_info).forEach((category) => { + if (category === "named_endpoints" || category === "unnamed_endpoints") { + transformed_info[category] = {}; + Object.entries(api_info[category]).forEach( + ([endpoint, { parameters, returns }]) => { + var _a, _b, _c, _d; + const dependencyIndex = ((_a = config.dependencies.find( + (dep) => dep.api_name === endpoint || dep.api_name === endpoint.replace("/", "") + )) == null ? void 0 : _a.id) || api_map[endpoint.replace("/", "")] || -1; + const dependencyTypes = dependencyIndex !== -1 ? (_b = config.dependencies.find((dep) => dep.id == dependencyIndex)) == null ? void 0 : _b.types : { continuous: false, generator: false, cancel: false }; + if (dependencyIndex !== -1 && ((_d = (_c = config.dependencies.find((dep) => dep.id == dependencyIndex)) == null ? void 0 : _c.inputs) == null ? void 0 : _d.length) !== parameters.length) { + const components = config.dependencies.find((dep) => dep.id == dependencyIndex).inputs.map( + (input) => { + var _a2; + return (_a2 = config.components.find((c) => c.id === input)) == null ? void 0 : _a2.type; + } + ); + try { + components.forEach((comp, idx) => { + if (comp === "state") { + const new_param = { + component: "state", + example: null, + parameter_default: null, + parameter_has_default: true, + parameter_name: null, + hidden: true + }; + parameters.splice(idx, 0, new_param); + } + }); + } catch (e) { + console.error(e); + } + } + const transform_type = (data, component, serializer, signature_type) => ({ + ...data, + description: get_description(data == null ? void 0 : data.type, serializer), + type: get_type(data == null ? void 0 : data.type, component, serializer, signature_type) || "" + }); + transformed_info[category][endpoint] = { + parameters: parameters.map( + (p) => transform_type(p, p == null ? void 0 : p.component, p == null ? void 0 : p.serializer, "parameter") + ), + returns: returns.map( + (r) => transform_type(r, r == null ? void 0 : r.component, r == null ? void 0 : r.serializer, "return") + ), + type: dependencyTypes + }; + } + ); + } + }); + return transformed_info; } -async function get_space_hardware(space_id, token) { - const headers = {}; - if (token) { - headers.Authorization = `Bearer ${token}`; +function get_type(type, component, serializer, signature_type) { + switch (type == null ? void 0 : type.type) { + case "string": + return "string"; + case "boolean": + return "boolean"; + case "number": + return "number"; } - try { - const res = await fetch( - `https://huggingface.co/api/spaces/${space_id}/runtime`, - { headers } - ); - if (res.status !== 200) - throw new Error("Space hardware could not be obtained."); - const { hardware } = await res.json(); - return hardware; - } catch (e) { - throw new Error(e.message); + if (serializer === "JSONSerializable" || serializer === "StringSerializable") { + return "any"; + } else if (serializer === "ListStringSerializable") { + return "string[]"; + } else if (component === "Image") { + return signature_type === "parameter" ? "Blob | File | Buffer" : "string"; + } else if (serializer === "FileSerializable") { + if ((type == null ? void 0 : type.type) === "array") { + return signature_type === "parameter" ? "(Blob | File | Buffer)[]" : `{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}[]`; + } + return signature_type === "parameter" ? "Blob | File | Buffer" : `{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}`; + } else if (serializer === "GallerySerializable") { + return signature_type === "parameter" ? "[(Blob | File | Buffer), (string | null)][]" : `[{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}, (string | null))][]`; } } -async function set_space_hardware(space_id, new_hardware, token) { - const headers = {}; - if (token) { - headers.Authorization = `Bearer ${token}`; +function get_description(type, serializer) { + if (serializer === "GallerySerializable") { + return "array of [file, label] tuples"; + } else if (serializer === "ListStringSerializable") { + return "array of strings"; + } else if (serializer === "FileSerializable") { + return "array of files or single file"; } - try { - const res = await fetch( - `https://huggingface.co/api/spaces/${space_id}/hardware`, - { headers, body: JSON.stringify(new_hardware) } - ); - if (res.status !== 200) - throw new Error( - "Space hardware could not be set. Please ensure the space hardware provided is valid and that a Hugging Face token is passed in." - ); - const { hardware } = await res.json(); - return hardware; - } catch (e) { - throw new Error(e.message); + return type == null ? void 0 : type.description; +} +function handle_message(data, last_status) { + const queue = true; + switch (data.msg) { + case "send_data": + return { type: "data" }; + case "send_hash": + return { type: "hash" }; + case "queue_full": + return { + type: "update", + status: { + queue, + message: QUEUE_FULL_MSG, + stage: "error", + code: data.code, + success: data.success + } + }; + case "heartbeat": + return { + type: "heartbeat" + }; + case "unexpected_error": + return { + type: "unexpected_error", + status: { + queue, + message: data.message, + stage: "error", + success: false + } + }; + case "estimation": + return { + type: "update", + status: { + queue, + stage: last_status || "pending", + code: data.code, + size: data.queue_size, + position: data.rank, + eta: data.rank_eta, + success: data.success + } + }; + case "progress": + return { + type: "update", + status: { + queue, + stage: "pending", + code: data.code, + progress_data: data.progress_data, + success: data.success + } + }; + case "log": + return { type: "log", data }; + case "process_generating": + return { + type: "generating", + status: { + queue, + message: !data.success ? data.output.error : null, + stage: data.success ? "generating" : "error", + code: data.code, + progress_data: data.progress_data, + eta: data.average_duration + }, + data: data.success ? data.output : null + }; + case "process_completed": + if ("error" in data.output) { + return { + type: "update", + status: { + queue, + message: data.output.error, + stage: "error", + code: data.code, + success: data.success + } + }; + } + return { + type: "complete", + status: { + queue, + message: !data.success ? data.output.error : void 0, + stage: data.success ? "complete" : "error", + code: data.code, + progress_data: data.progress_data, + changed_state_ids: data.success ? data.output.changed_state_ids : void 0 + }, + data: data.success ? data.output : null + }; + case "process_starts": + return { + type: "update", + status: { + queue, + stage: "pending", + code: data.code, + size: data.rank, + position: 0, + success: data.success, + eta: data.eta + } + }; } + return { type: "none", status: { stage: "error", queue } }; } -async function set_space_timeout(space_id, timeout, token) { - const headers = {}; - if (token) { - headers.Authorization = `Bearer ${token}`; +const map_data_to_params = (data, api_info) => { + const parameters = Object.values(api_info.named_endpoints).flatMap( + (values) => values.parameters + ); + if (Array.isArray(data)) { + if (data.length > parameters.length) { + console.warn("Too many arguments provided for the endpoint."); + } + return data; } - try { - const res = await fetch( - `https://huggingface.co/api/spaces/${space_id}/hardware`, - { headers, body: JSON.stringify({ seconds: timeout }) } - ); - if (res.status !== 200) + const resolved_data = []; + const provided_keys = Object.keys(data); + parameters.forEach((param, index) => { + if (data.hasOwnProperty(param.parameter_name)) { + resolved_data[index] = data[param.parameter_name]; + } else if (param.parameter_has_default) { + resolved_data[index] = param.parameter_default; + } else { throw new Error( - "Space hardware could not be set. Please ensure the space hardware provided is valid and that a Hugging Face token is passed in." + `No value provided for required parameter: ${param.parameter_name}` ); - const { hardware } = await res.json(); - return hardware; - } catch (e) { - throw new Error(e.message); - } -} -const hardware_types = [ - "cpu-basic", - "cpu-upgrade", - "t4-small", - "t4-medium", - "a10g-small", - "a10g-large", - "a100-large" -]; -function normalise_file(file, server_url, proxy_url) { - if (file == null) { - return null; - } - if (Array.isArray(file)) { - const normalized_file = []; - for (const x of file) { - if (x == null) { - normalized_file.push(null); - } else { - normalized_file.push(normalise_file(x, server_url, proxy_url)); - } } - return normalized_file; - } - if (file.is_stream) { - if (proxy_url == null) { - return new FileData({ - ...file, - url: server_url + "/stream/" + file.path - }); + }); + provided_keys.forEach((key) => { + if (!parameters.some((param) => param.parameter_name === key)) { + throw new Error( + `Parameter \`${key}\` is not a valid keyword argument. Please refer to the API for usage.` + ); } - return new FileData({ - ...file, - url: "/proxy=" + proxy_url + "stream/" + file.path - }); - } - return new FileData({ - ...file, - url: get_fetchable_url_or_file(file.path, server_url, proxy_url) }); -} -function is_url(str) { + resolved_data.forEach((value, idx) => { + if (value === void 0 && !parameters[idx].parameter_has_default) { + throw new Error( + `No value provided for required parameter: ${parameters[idx].parameter_name}` + ); + } + }); + return resolved_data; +}; +async function view_api() { + if (this.api_info) + return this.api_info; + const { hf_token } = this.options; + const { config } = this; + const headers = { "Content-Type": "application/json" }; + if (hf_token) { + headers.Authorization = `Bearer ${hf_token}`; + } + if (!config) { + return; + } try { - const url = new URL(str); - return url.protocol === "http:" || url.protocol === "https:"; - } catch { - return false; + let response; + if (semiver((config == null ? void 0 : config.version) || "2.0.0", "3.30") < 0) { + response = await this.fetch(SPACE_FETCHER_URL, { + method: "POST", + body: JSON.stringify({ + serialize: false, + config: JSON.stringify(config) + }), + headers, + credentials: "include" + }); + } else { + const url = join_urls(config.root, API_INFO_URL); + response = await this.fetch(url, { + headers, + credentials: "include" + }); + } + if (!response.ok) { + throw new Error(BROKEN_CONNECTION_MSG); + } + let api_info = await response.json(); + if ("api" in api_info) { + api_info = api_info.api; + } + if (api_info.named_endpoints["/predict"] && !api_info.unnamed_endpoints["0"]) { + api_info.unnamed_endpoints[0] = api_info.named_endpoints["/predict"]; + } + return transform_api_info(api_info, config, this.api_map); + } catch (e) { + "Could not get API info. " + e.message; } } -function get_fetchable_url_or_file(path, server_url, proxy_url) { - if (path == null) { - return proxy_url ? `/proxy=${proxy_url}file=` : `${server_url}/file=`; +async function upload_files(root_url, files, upload_id) { + var _a; + const headers = {}; + if ((_a = this == null ? void 0 : this.options) == null ? void 0 : _a.hf_token) { + headers.Authorization = `Bearer ${this.options.hf_token}`; } - if (is_url(path)) { - return path; + const chunkSize = 1e3; + const uploadResponses = []; + let response; + for (let i = 0; i < files.length; i += chunkSize) { + const chunk = files.slice(i, i + chunkSize); + const formData = new FormData(); + chunk.forEach((file) => { + formData.append("files", file); + }); + try { + const upload_url = upload_id ? `${root_url}/${UPLOAD_URL}?upload_id=${upload_id}` : `${root_url}/${UPLOAD_URL}`; + response = await this.fetch(upload_url, { + method: "POST", + body: formData, + headers, + credentials: "include" + }); + } catch (e) { + throw new Error(BROKEN_CONNECTION_MSG + e.message); + } + if (!response.ok) { + const error_text = await response.text(); + return { error: `HTTP ${response.status}: ${error_text}` }; + } + const output = await response.json(); + if (output) { + uploadResponses.push(...output); + } } - return proxy_url ? `/proxy=${proxy_url}file=${path}` : `${server_url}/file=${path}`; + return { files: uploadResponses }; } -async function upload(file_data, root, upload_id, upload_fn = upload_files) { +async function upload(file_data, root_url, upload_id, max_file_size) { let files = (Array.isArray(file_data) ? file_data : [file_data]).map( (file_data2) => file_data2.blob ); + const oversized_files = files.filter( + (f) => f.size > (max_file_size ?? Infinity) + ); + if (oversized_files.length) { + throw new Error( + `File size exceeds the maximum allowed size of ${max_file_size} bytes: ${oversized_files.map((f) => f.name).join(", ")}` + ); + } return await Promise.all( - await upload_fn(root, files, void 0, upload_id).then( + await this.upload_files(root_url, files, upload_id).then( async (response) => { if (response.error) { throw new Error(response.error); } else { if (response.files) { return response.files.map((f, i) => { - const file = new FileData({ ...file_data[i], path: f }); - return normalise_file(file, root, null); + const file = new FileData({ + ...file_data[i], + path: f, + url: root_url + "/file=" + f + }); + return file; }); } return []; @@ -243,7 +611,7 @@ async function upload(file_data, root, upload_id, upload_fn = upload_files) { } async function prepare_files(files, is_stream) { return files.map( - (f, i) => new FileData({ + (f) => new FileData({ path: f.name, orig_name: f.name, blob: f, @@ -264,6 +632,15 @@ class FileData { mime_type, alt_text }) { + __publicField(this, "path"); + __publicField(this, "url"); + __publicField(this, "orig_name"); + __publicField(this, "size"); + __publicField(this, "blob"); + __publicField(this, "is_stream"); + __publicField(this, "mime_type"); + __publicField(this, "alt_text"); + __publicField(this, "meta", { _type: "gradio.FileData" }); this.path = path; this.url = url; this.orig_name = orig_name; @@ -274,1319 +651,1831 @@ class FileData { this.alt_text = alt_text; } } -const QUEUE_FULL_MSG = "This application is too busy. Keep trying!"; -const BROKEN_CONNECTION_MSG = "Connection errored out."; -let NodeBlob; -async function duplicate(app_reference, options) { - const { hf_token, private: _private, hardware, timeout } = options; - if (hardware && !hardware_types.includes(hardware)) { - throw new Error( - `Invalid hardware type provided. Valid types are: ${hardware_types.map((v) => `"${v}"`).join(",")}.` - ); +class Command { + constructor(command, meta) { + __publicField(this, "type"); + __publicField(this, "command"); + __publicField(this, "meta"); + __publicField(this, "fileData"); + this.type = "command"; + this.command = command; + this.meta = meta; } - const headers = { - Authorization: `Bearer ${hf_token}` - }; - const user = (await (await fetch(`https://huggingface.co/api/whoami-v2`, { - headers - })).json()).name; - const space_name = app_reference.split("/")[1]; - const body = { - repository: `${user}/${space_name}` - }; - if (_private) { - body.private = true; +} +const is_node = typeof process !== "undefined" && process.versions && process.versions.node; +function update_object(object, newValue, stack) { + while (stack.length > 1) { + const key2 = stack.shift(); + if (typeof key2 === "string" || typeof key2 === "number") { + object = object[key2]; + } else { + throw new Error("Invalid key type"); + } } - try { - const response = await fetch( - `https://huggingface.co/api/spaces/${app_reference}/duplicate`, + const key = stack.shift(); + if (typeof key === "string" || typeof key === "number") { + object[key] = newValue; + } else { + throw new Error("Invalid key type"); + } +} +async function walk_and_store_blobs(data, type = void 0, path = [], root = false, endpoint_info = void 0) { + if (Array.isArray(data)) { + let blob_refs = []; + await Promise.all( + data.map(async (_, index) => { + var _a; + let new_path = path.slice(); + new_path.push(String(index)); + const array_refs = await walk_and_store_blobs( + data[index], + root ? ((_a = endpoint_info == null ? void 0 : endpoint_info.parameters[index]) == null ? void 0 : _a.component) || void 0 : type, + new_path, + false, + endpoint_info + ); + blob_refs = blob_refs.concat(array_refs); + }) + ); + return blob_refs; + } else if (globalThis.Buffer && data instanceof globalThis.Buffer || data instanceof Blob) { + return [ { - method: "POST", - headers: { "Content-Type": "application/json", ...headers }, - body: JSON.stringify(body) + path, + blob: new Blob([data]), + type } - ); - if (response.status === 409) { - return client(`${user}/${space_name}`, options); - } - const duplicated_space = await response.json(); - let original_hardware; - if (!hardware) { - original_hardware = await get_space_hardware(app_reference, hf_token); + ]; + } else if (typeof data === "object" && data !== null) { + let blob_refs = []; + for (const key of Object.keys(data)) { + const new_path = [...path, key]; + const value = data[key]; + blob_refs = blob_refs.concat( + await walk_and_store_blobs( + value, + void 0, + new_path, + false, + endpoint_info + ) + ); } - const requested_hardware = hardware || original_hardware || "cpu-basic"; - await set_space_hardware( - `${user}/${space_name}`, - requested_hardware, - hf_token - ); - await set_space_timeout(`${user}/${space_name}`, timeout || 300, hf_token); - return client(duplicated_space.url, options); - } catch (e) { - throw new Error(e); + return blob_refs; + } + return []; +} +function skip_queue(id, config) { + var _a, _b; + let fn_queue = (_b = (_a = config == null ? void 0 : config.dependencies) == null ? void 0 : _a.find((dep) => dep.id == id)) == null ? void 0 : _b.queue; + if (fn_queue != null) { + return !fn_queue; } + return !config.enable_queue; +} +function post_message(message, origin) { + return new Promise((res, _rej) => { + const channel = new MessageChannel(); + channel.port1.onmessage = ({ data }) => { + channel.port1.close(); + res(data); + }; + window.parent.postMessage(message, origin, [channel.port2]); + }); } -function api_factory(fetch_implementation, EventSource_factory) { - return { post_data: post_data2, upload_files: upload_files2, client: client2, handle_blob: handle_blob2 }; - async function post_data2(url, body, token) { - const headers = { "Content-Type": "application/json" }; - if (token) { - headers.Authorization = `Bearer ${token}`; +function handle_file(file_or_url) { + if (typeof file_or_url === "string") { + if (file_or_url.startsWith("http://") || file_or_url.startsWith("https://")) { + return { + path: file_or_url, + url: file_or_url, + orig_name: file_or_url.split("/").pop() ?? "unknown", + meta: { _type: "gradio.FileData" } + }; } - try { - var response = await fetch_implementation(url, { - method: "POST", - body: JSON.stringify(body), - headers + if (is_node) { + return new Command("upload_file", { + path: file_or_url, + name: file_or_url, + orig_path: file_or_url }); - } catch (e) { - return [{ error: BROKEN_CONNECTION_MSG }, 500]; } - let output; - let status; - try { - output = await response.json(); - status = response.status; - } catch (e) { - output = { error: `Could not parse server response: ${e}` }; - status = 500; + } else if (typeof File !== "undefined" && file_or_url instanceof File) { + return { + path: file_or_url instanceof File ? file_or_url.name : "blob", + orig_name: file_or_url instanceof File ? file_or_url.name : "unknown", + // @ts-ignore + blob: file_or_url instanceof File ? file_or_url : new Blob([file_or_url]), + size: file_or_url instanceof Blob ? file_or_url.size : Buffer.byteLength(file_or_url), + mime_type: file_or_url instanceof File ? file_or_url.type : "application/octet-stream", + // Default MIME type for buffers + meta: { _type: "gradio.FileData" } + }; + } else if (file_or_url instanceof Buffer) { + return new Blob([file_or_url]); + } else if (file_or_url instanceof Blob) { + return file_or_url; + } + throw new Error( + "Invalid input: must be a URL, File, Blob, or Buffer object." + ); +} +function handle_payload(resolved_payload, dependency, components, type, with_null_state = false) { + if (type === "input" && !with_null_state) { + throw new Error("Invalid code path. Cannot skip state inputs for input."); + } + if (type === "output" && with_null_state) { + return resolved_payload; + } + let updated_payload = []; + let payload_index = 0; + for (let i = 0; i < dependency.inputs.length; i++) { + const input_id = dependency.inputs[i]; + const component = components.find((c) => c.id === input_id); + if ((component == null ? void 0 : component.type) === "state") { + if (with_null_state) { + if (resolved_payload.length === dependency.inputs.length) { + const value = resolved_payload[payload_index]; + updated_payload.push(value); + payload_index++; + } else { + updated_payload.push(null); + } + } else { + payload_index++; + continue; + } + continue; + } else { + const value = resolved_payload[payload_index]; + updated_payload.push(value); + payload_index++; } - return [output, status]; } - async function upload_files2(root, files, token, upload_id) { - const headers = {}; - if (token) { - headers.Authorization = `Bearer ${token}`; + return updated_payload; +} +async function handle_blob(endpoint, data, api_info) { + const self = this; + await process_local_file_commands(self, data); + const blobRefs = await walk_and_store_blobs( + data, + void 0, + [], + true, + api_info + ); + const results = await Promise.all( + blobRefs.map(async ({ path, blob, type }) => { + if (!blob) + return { path, type }; + const response = await self.upload_files(endpoint, [blob]); + const file_url = response.files && response.files[0]; + return { + path, + file_url, + type, + name: blob instanceof File ? blob == null ? void 0 : blob.name : void 0 + }; + }) + ); + results.forEach(({ path, file_url, type, name }) => { + if (type === "Gallery") { + update_object(data, file_url, path); + } else if (file_url) { + const file = new FileData({ path: file_url, orig_name: name }); + update_object(data, file, path); + } + }); + return data; +} +async function process_local_file_commands(client2, data) { + var _a, _b; + const root = ((_a = client2.config) == null ? void 0 : _a.root) || ((_b = client2.config) == null ? void 0 : _b.root_url); + if (!root) { + throw new Error(ROOT_URL_ERROR_MSG); + } + await recursively_process_commands(client2, data); +} +async function recursively_process_commands(client2, data, path = []) { + for (const key in data) { + if (data[key] instanceof Command) { + await process_single_command(client2, data, key); + } else if (typeof data[key] === "object" && data[key] !== null) { + await recursively_process_commands(client2, data[key], [...path, key]); } - const chunkSize = 1e3; - const uploadResponses = []; - for (let i = 0; i < files.length; i += chunkSize) { - const chunk = files.slice(i, i + chunkSize); - const formData = new FormData(); - chunk.forEach((file) => { - formData.append("files", file); + } +} +async function process_single_command(client2, data, key) { + var _a, _b; + let cmd_item = data[key]; + const root = ((_a = client2.config) == null ? void 0 : _a.root) || ((_b = client2.config) == null ? void 0 : _b.root_url); + if (!root) { + throw new Error(ROOT_URL_ERROR_MSG); + } + try { + let fileBuffer; + let fullPath; + if (typeof process !== "undefined" && process.versions && process.versions.node) { + const fs = await import("fs/promises"); + const path = await import("path"); + fullPath = path.resolve(process.cwd(), cmd_item.meta.path); + fileBuffer = await fs.readFile(fullPath); + } else { + throw new Error(NODEJS_FS_ERROR_MSG); + } + const file = new Blob([fileBuffer], { type: "application/octet-stream" }); + const response = await client2.upload_files(root, [file]); + const file_url = response.files && response.files[0]; + if (file_url) { + const fileData = new FileData({ + path: file_url, + orig_name: cmd_item.meta.name || "" }); - try { - const upload_url = upload_id ? `${root}/upload?upload_id=${upload_id}` : `${root}/upload`; - var response = await fetch_implementation(upload_url, { - method: "POST", - body: formData, - headers - }); - } catch (e) { - return { error: BROKEN_CONNECTION_MSG }; - } - const output = await response.json(); - uploadResponses.push(...output); + data[key] = fileData; } - return { files: uploadResponses }; - } - async function client2(app_reference, options = { normalise_files: true }) { - return new Promise(async (res) => { - const { status_callback, hf_token, normalise_files } = options; - const return_obj = { - predict, - submit, - view_api, - component_server - }; - const transform_files = normalise_files ?? true; - if ((typeof window === "undefined" || !("WebSocket" in window)) && !global.Websocket) { - const ws = await import("./wrapper-6f348d45.js"); - NodeBlob = (await import("node:buffer")).Blob; - global.WebSocket = ws.WebSocket; - } - const { ws_protocol, http_protocol, host, space_id } = await process_endpoint(app_reference, hf_token); - const session_hash = Math.random().toString(36).substring(2); - const last_status = {}; - let stream_open = false; - let pending_stream_messages = {}; - let event_stream = null; - const event_callbacks = {}; - const unclosed_events = /* @__PURE__ */ new Set(); - let config; - let api_map = {}; - let jwt = false; - if (hf_token && space_id) { - jwt = await get_jwt(space_id, hf_token); - } - async function config_success(_config) { - config = _config; - api_map = map_names_to_ids((_config == null ? void 0 : _config.dependencies) || []); - if (config.auth_required) { - return { - config, - ...return_obj - }; - } - try { - api = await view_api(config); - } catch (e) { - console.error(`Could not get api details: ${e.message}`); + } catch (error) { + console.error(FILE_PROCESSING_ERROR_MSG, error); + } +} +async function post_data(url, body, additional_headers) { + const headers = { "Content-Type": "application/json" }; + if (this.options.hf_token) { + headers.Authorization = `Bearer ${this.options.hf_token}`; + } + try { + var response = await this.fetch(url, { + method: "POST", + body: JSON.stringify(body), + headers: { ...headers, ...additional_headers }, + credentials: "include" + }); + } catch (e) { + return [{ error: BROKEN_CONNECTION_MSG }, 500]; + } + let output; + let status; + try { + output = await response.json(); + status = response.status; + } catch (e) { + output = { error: `Could not parse server response: ${e}` }; + status = 500; + } + return [output, status]; +} +async function predict(endpoint, data) { + let data_returned = false; + let status_complete = false; + let dependency; + if (!this.config) { + throw new Error("Could not resolve app config"); + } + if (typeof endpoint === "number") { + dependency = this.config.dependencies.find((dep) => dep.id == endpoint); + } else { + const trimmed_endpoint = endpoint.replace(/^\//, ""); + dependency = this.config.dependencies.find( + (dep) => dep.id == this.api_map[trimmed_endpoint] + ); + } + if (dependency == null ? void 0 : dependency.types.continuous) { + throw new Error( + "Cannot call predict on this function as it may run forever. Use submit instead" + ); + } + return new Promise(async (resolve, reject) => { + const app = this.submit(endpoint, data, null, null, true); + let result; + for await (const message of app) { + if (message.type === "data") { + if (status_complete) { + resolve(result); } - return { - config, - ...return_obj - }; + data_returned = true; + result = message; } - let api; - async function handle_space_sucess(status) { - if (status_callback) - status_callback(status); - if (status.status === "running") - try { - config = await resolve_config( - fetch_implementation, - `${http_protocol}//${host}`, - hf_token - ); - const _config = await config_success(config); - res(_config); - } catch (e) { - console.error(e); - if (status_callback) { - status_callback({ - status: "error", - message: "Could not load this space.", - load_status: "error", - detail: "NOT_FOUND" - }); - } + if (message.type === "status") { + if (message.stage === "error") + reject(message); + if (message.stage === "complete") { + status_complete = true; + if (data_returned) { + resolve(result); } - } - try { - config = await resolve_config( - fetch_implementation, - `${http_protocol}//${host}`, - hf_token - ); - const _config = await config_success(config); - res(_config); - } catch (e) { - console.error(e); - if (space_id) { - check_space_status( - space_id, - RE_SPACE_NAME.test(space_id) ? "space_name" : "subdomain", - handle_space_sucess - ); - } else { - if (status_callback) - status_callback({ - status: "error", - message: "Could not load this space.", - load_status: "error", - detail: "NOT_FOUND" - }); - } - } - function predict(endpoint, data, event_data) { - let data_returned = false; - let status_complete = false; - let dependency; - if (typeof endpoint === "number") { - dependency = config.dependencies[endpoint]; - } else { - const trimmed_endpoint = endpoint.replace(/^\//, ""); - dependency = config.dependencies[api_map[trimmed_endpoint]]; - } - if (dependency.types.continuous) { - throw new Error( - "Cannot call predict on this function as it may run forever. Use submit instead" - ); } - return new Promise((res2, rej) => { - const app = submit(endpoint, data, event_data); - let result; - app.on("data", (d) => { - if (status_complete) { - app.destroy(); - res2(d); - } - data_returned = true; - result = d; - }).on("status", (status) => { - if (status.stage === "error") - rej(status); - if (status.stage === "complete") { - status_complete = true; - if (data_returned) { - app.destroy(); - res2(result); - } - } - }); - }); } - function submit(endpoint, data, event_data, trigger_id = null) { - let fn_index; - let api_info; - if (typeof endpoint === "number") { - fn_index = endpoint; - api_info = api.unnamed_endpoints[fn_index]; - } else { - const trimmed_endpoint = endpoint.replace(/^\//, ""); - fn_index = api_map[trimmed_endpoint]; - api_info = api.named_endpoints[endpoint.trim()]; - } - if (typeof fn_index !== "number") { - throw new Error( - "There is no endpoint matching that name of fn_index matching that number." - ); - } - let websocket; - let eventSource; - let protocol = config.protocol ?? "ws"; - const _endpoint = typeof endpoint === "number" ? "/predict" : endpoint; - let payload; - let event_id = null; - let complete = false; - const listener_map = {}; - let url_params = ""; - if (typeof window !== "undefined") { - url_params = new URLSearchParams(window.location.search).toString(); - } - handle_blob2(`${config.root}`, data, api_info, hf_token).then( - (_payload) => { - payload = { - data: _payload || [], - event_data, - fn_index, - trigger_id - }; - if (skip_queue(fn_index, config)) { - fire_event({ - type: "status", - endpoint: _endpoint, - stage: "pending", - queue: false, - fn_index, - time: /* @__PURE__ */ new Date() - }); - post_data2( - `${config.root}/run${_endpoint.startsWith("/") ? _endpoint : `/${_endpoint}`}${url_params ? "?" + url_params : ""}`, - { - ...payload, - session_hash - }, - hf_token - ).then(([output, status_code]) => { - const data2 = transform_files ? transform_output( - output.data, - api_info, - config.root, - config.root_url - ) : output.data; - if (status_code == 200) { - fire_event({ - type: "data", - endpoint: _endpoint, - fn_index, - data: data2, - time: /* @__PURE__ */ new Date() - }); - fire_event({ - type: "status", - endpoint: _endpoint, - fn_index, - stage: "complete", - eta: output.average_duration, - queue: false, - time: /* @__PURE__ */ new Date() - }); - } else { - fire_event({ - type: "status", - stage: "error", - endpoint: _endpoint, - fn_index, - message: output.error, - queue: false, - time: /* @__PURE__ */ new Date() - }); - } - }).catch((e) => { - fire_event({ - type: "status", - stage: "error", - message: e.message, - endpoint: _endpoint, - fn_index, - queue: false, - time: /* @__PURE__ */ new Date() - }); - }); - } else if (protocol == "ws") { - fire_event({ - type: "status", - stage: "pending", - queue: true, - endpoint: _endpoint, - fn_index, - time: /* @__PURE__ */ new Date() - }); - let url = new URL(`${ws_protocol}://${resolve_root( - host, - config.path, - true - )} - /queue/join${url_params ? "?" + url_params : ""}`); - if (jwt) { - url.searchParams.set("__sign", jwt); + } + }); +} +async function check_space_status(id, type, status_callback) { + let endpoint = type === "subdomain" ? `https://huggingface.co/api/spaces/by-subdomain/${id}` : `https://huggingface.co/api/spaces/${id}`; + let response; + let _status; + try { + response = await fetch(endpoint); + _status = response.status; + if (_status !== 200) { + throw new Error(); + } + response = await response.json(); + } catch (e) { + status_callback({ + status: "error", + load_status: "error", + message: SPACE_STATUS_ERROR_MSG, + detail: "NOT_FOUND" + }); + return; + } + if (!response || _status !== 200) + return; + const { + runtime: { stage }, + id: space_name + } = response; + switch (stage) { + case "STOPPED": + case "SLEEPING": + status_callback({ + status: "sleeping", + load_status: "pending", + message: "Space is asleep. Waking it up...", + detail: stage + }); + setTimeout(() => { + check_space_status(id, type, status_callback); + }, 1e3); + break; + case "PAUSED": + status_callback({ + status: "paused", + load_status: "error", + message: "This space has been paused by the author. If you would like to try this demo, consider duplicating the space.", + detail: stage, + discussions_enabled: await discussions_enabled(space_name) + }); + break; + case "RUNNING": + case "RUNNING_BUILDING": + status_callback({ + status: "running", + load_status: "complete", + message: "", + detail: stage + }); + break; + case "BUILDING": + status_callback({ + status: "building", + load_status: "pending", + message: "Space is building...", + detail: stage + }); + setTimeout(() => { + check_space_status(id, type, status_callback); + }, 1e3); + break; + default: + status_callback({ + status: "space_error", + load_status: "error", + message: "This space is experiencing an issue.", + detail: stage, + discussions_enabled: await discussions_enabled(space_name) + }); + break; + } +} +const RE_DISABLED_DISCUSSION = /^(?=[^]*\b[dD]iscussions{0,1}\b)(?=[^]*\b[dD]isabled\b)[^]*$/; +async function discussions_enabled(space_id) { + try { + const r = await fetch( + `https://huggingface.co/api/spaces/${space_id}/discussions`, + { + method: "HEAD" + } + ); + const error = r.headers.get("x-error-message"); + if (!r.ok || error && RE_DISABLED_DISCUSSION.test(error)) + return false; + return true; + } catch (e) { + return false; + } +} +async function get_space_hardware(space_id, hf_token) { + const headers = {}; + if (hf_token) { + headers.Authorization = `Bearer ${hf_token}`; + } + try { + const res = await fetch( + `https://huggingface.co/api/spaces/${space_id}/${RUNTIME_URL}`, + { headers } + ); + if (res.status !== 200) + throw new Error("Space hardware could not be obtained."); + const { hardware } = await res.json(); + return hardware.current; + } catch (e) { + throw new Error(e.message); + } +} +async function set_space_timeout(space_id, timeout, hf_token) { + const headers = {}; + if (hf_token) { + headers.Authorization = `Bearer ${hf_token}`; + } + const body = { + seconds: timeout + }; + try { + const res = await fetch( + `https://huggingface.co/api/spaces/${space_id}/${SLEEPTIME_URL}`, + { + method: "POST", + headers: { "Content-Type": "application/json", ...headers }, + body: JSON.stringify(body) + } + ); + if (res.status !== 200) { + throw new Error( + "Could not set sleep timeout on duplicated Space. Please visit *ADD HF LINK TO SETTINGS* to set a timeout manually to reduce billing charges." + ); + } + const response = await res.json(); + return response; + } catch (e) { + throw new Error(e.message); + } +} +const hardware_types = [ + "cpu-basic", + "cpu-upgrade", + "cpu-xl", + "t4-small", + "t4-medium", + "a10g-small", + "a10g-large", + "a10g-largex2", + "a10g-largex4", + "a100-large", + "zero-a10g", + "h100", + "h100x8" +]; +async function duplicate(app_reference, options) { + const { hf_token, private: _private, hardware, timeout, auth } = options; + if (hardware && !hardware_types.includes(hardware)) { + throw new Error( + `Invalid hardware type provided. Valid types are: ${hardware_types.map((v) => `"${v}"`).join(",")}.` + ); + } + const { http_protocol, host } = await process_endpoint( + app_reference, + hf_token + ); + let cookies = null; + if (auth) { + const cookie_header = await get_cookie_header( + http_protocol, + host, + auth, + fetch + ); + if (cookie_header) + cookies = parse_and_set_cookies(cookie_header); + } + const headers = { + Authorization: `Bearer ${hf_token}`, + "Content-Type": "application/json", + ...cookies ? { Cookie: cookies.join("; ") } : {} + }; + const user = (await (await fetch(`https://huggingface.co/api/whoami-v2`, { + headers + })).json()).name; + const space_name = app_reference.split("/")[1]; + const body = { + repository: `${user}/${space_name}` + }; + if (_private) { + body.private = true; + } + let original_hardware; + try { + if (!hardware) { + original_hardware = await get_space_hardware(app_reference, hf_token); + } + } catch (e) { + throw Error(SPACE_METADATA_ERROR_MSG + e.message); + } + const requested_hardware = hardware || original_hardware || "cpu-basic"; + body.hardware = requested_hardware; + try { + const response = await fetch( + `https://huggingface.co/api/spaces/${app_reference}/duplicate`, + { + method: "POST", + headers, + body: JSON.stringify(body) + } + ); + if (response.status === 409) { + try { + const client2 = await Client.connect(`${user}/${space_name}`, options); + return client2; + } catch (error) { + console.error("Failed to connect Client instance:", error); + throw error; + } + } else if (response.status !== 200) { + throw new Error(response.statusText); + } + const duplicated_space = await response.json(); + await set_space_timeout(`${user}/${space_name}`, timeout || 300, hf_token); + return await Client.connect( + get_space_reference(duplicated_space.url), + options + ); + } catch (e) { + throw new Error(e); + } +} +function get_space_reference(url) { + const regex = /https:\/\/huggingface.co\/spaces\/([^/]+\/[^/]+)/; + const match = url.match(regex); + if (match) { + return match[1]; + } +} +class TextLineStream extends TransformStream { + /** Constructs a new instance. */ + constructor(options = { allowCR: false }) { + super({ + transform: (chars, controller) => { + chars = __privateGet(this, _currentLine) + chars; + while (true) { + const lfIndex = chars.indexOf("\n"); + const crIndex = options.allowCR ? chars.indexOf("\r") : -1; + if (crIndex !== -1 && crIndex !== chars.length - 1 && (lfIndex === -1 || lfIndex - 1 > crIndex)) { + controller.enqueue(chars.slice(0, crIndex)); + chars = chars.slice(crIndex + 1); + continue; + } + if (lfIndex === -1) + break; + const endIndex = chars[lfIndex - 1] === "\r" ? lfIndex - 1 : lfIndex; + controller.enqueue(chars.slice(0, endIndex)); + chars = chars.slice(lfIndex + 1); + } + __privateSet(this, _currentLine, chars); + }, + flush: (controller) => { + if (__privateGet(this, _currentLine) === "") + return; + const currentLine = options.allowCR && __privateGet(this, _currentLine).endsWith("\r") ? __privateGet(this, _currentLine).slice(0, -1) : __privateGet(this, _currentLine); + controller.enqueue(currentLine); + } + }); + __privateAdd(this, _currentLine, ""); + } +} +_currentLine = new WeakMap(); +function stream$1(input) { + let decoder = new TextDecoderStream(); + let split2 = new TextLineStream({ allowCR: true }); + return input.pipeThrough(decoder).pipeThrough(split2); +} +function split(input) { + let rgx = /[:]\s*/; + let match = rgx.exec(input); + let idx = match && match.index; + if (idx) { + return [ + input.substring(0, idx), + input.substring(idx + match[0].length) + ]; + } +} +function fallback(headers, key, value) { + let tmp = headers.get(key); + if (!tmp) + headers.set(key, value); +} +async function* events(res, signal) { + if (!res.body) + return; + let iter = stream$1(res.body); + let line, reader = iter.getReader(); + let event; + for (; ; ) { + if (signal && signal.aborted) { + return reader.cancel(); + } + line = await reader.read(); + if (line.done) + return; + if (!line.value) { + if (event) + yield event; + event = void 0; + continue; + } + let [field, value] = split(line.value) || []; + if (!field) + continue; + if (field === "data") { + event || (event = {}); + event[field] = event[field] ? event[field] + "\n" + value : value; + } else if (field === "event") { + event || (event = {}); + event[field] = value; + } else if (field === "id") { + event || (event = {}); + event[field] = +value || value; + } else if (field === "retry") { + event || (event = {}); + event[field] = +value || void 0; + } + } +} +async function stream(input, init) { + let req = new Request(input, init); + fallback(req.headers, "Accept", "text/event-stream"); + fallback(req.headers, "Content-Type", "application/json"); + let r = await fetch(req); + if (!r.ok) + throw r; + return events(r, req.signal); +} +async function open_stream() { + let { + event_callbacks, + unclosed_events, + pending_stream_messages, + stream_status, + config, + jwt + } = this; + const that = this; + if (!config) { + throw new Error("Could not resolve app config"); + } + stream_status.open = true; + let stream2 = null; + let params = new URLSearchParams({ + session_hash: this.session_hash + }).toString(); + let url = new URL(`${config.root}/queue/data?${params}`); + if (jwt) { + url.searchParams.set("__sign", jwt); + } + stream2 = this.stream(url); + if (!stream2) { + console.warn("Cannot connect to SSE endpoint: " + url.toString()); + return; + } + stream2.onmessage = async function(event) { + let _data = JSON.parse(event.data); + if (_data.msg === "close_stream") { + close_stream(stream_status, that.abort_controller); + return; + } + const event_id = _data.event_id; + if (!event_id) { + await Promise.all( + Object.keys(event_callbacks).map( + (event_id2) => event_callbacks[event_id2](_data) + ) + ); + } else if (event_callbacks[event_id] && config) { + if (_data.msg === "process_completed" && ["sse", "sse_v1", "sse_v2", "sse_v2.1", "sse_v3"].includes( + config.protocol + )) { + unclosed_events.delete(event_id); + } + let fn2 = event_callbacks[event_id]; + if (typeof window !== "undefined" && typeof document !== "undefined") { + setTimeout(fn2, 0, _data); + } else { + fn2(_data); + } + } else { + if (!pending_stream_messages[event_id]) { + pending_stream_messages[event_id] = []; + } + pending_stream_messages[event_id].push(_data); + } + }; + stream2.onerror = async function() { + await Promise.all( + Object.keys(event_callbacks).map( + (event_id) => event_callbacks[event_id]({ + msg: "unexpected_error", + message: BROKEN_CONNECTION_MSG + }) + ) + ); + }; +} +function close_stream(stream_status, abort_controller) { + if (stream_status) { + stream_status.open = false; + abort_controller == null ? void 0 : abort_controller.abort(); + } +} +function apply_diff_stream(pending_diff_streams, event_id, data) { + let is_first_generation = !pending_diff_streams[event_id]; + if (is_first_generation) { + pending_diff_streams[event_id] = []; + data.data.forEach((value, i) => { + pending_diff_streams[event_id][i] = value; + }); + } else { + data.data.forEach((value, i) => { + let new_data = apply_diff(pending_diff_streams[event_id][i], value); + pending_diff_streams[event_id][i] = new_data; + data.data[i] = new_data; + }); + } +} +function apply_diff(obj, diff) { + diff.forEach(([action, path, value]) => { + obj = apply_edit(obj, path, action, value); + }); + return obj; +} +function apply_edit(target, path, action, value) { + if (path.length === 0) { + if (action === "replace") { + return value; + } else if (action === "append") { + return target + value; + } + throw new Error(`Unsupported action: ${action}`); + } + let current = target; + for (let i = 0; i < path.length - 1; i++) { + current = current[path[i]]; + } + const last_path = path[path.length - 1]; + switch (action) { + case "replace": + current[last_path] = value; + break; + case "append": + current[last_path] += value; + break; + case "add": + if (Array.isArray(current)) { + current.splice(Number(last_path), 0, value); + } else { + current[last_path] = value; + } + break; + case "delete": + if (Array.isArray(current)) { + current.splice(Number(last_path), 1); + } else { + delete current[last_path]; + } + break; + default: + throw new Error(`Unknown action: ${action}`); + } + return target; +} +function readable_stream(input, init = {}) { + const instance = { + close: () => { + throw new Error("Method not implemented."); + }, + onerror: null, + onmessage: null, + onopen: null, + readyState: 0, + url: input.toString(), + withCredentials: false, + CONNECTING: 0, + OPEN: 1, + CLOSED: 2, + addEventListener: () => { + throw new Error("Method not implemented."); + }, + dispatchEvent: () => { + throw new Error("Method not implemented."); + }, + removeEventListener: () => { + throw new Error("Method not implemented."); + } + }; + stream(input, init).then(async (res) => { + instance.readyState = instance.OPEN; + try { + for await (const chunk of res) { + instance.onmessage && instance.onmessage(chunk); + } + instance.readyState = instance.CLOSED; + } catch (e) { + instance.onerror && instance.onerror(e); + instance.readyState = instance.CLOSED; + } + }).catch((e) => { + console.error(e); + instance.onerror && instance.onerror(e); + instance.readyState = instance.CLOSED; + }); + return instance; +} +function submit(endpoint, data, event_data, trigger_id, all_events) { + var _a; + try { + let fire_event = function(event) { + if (all_events || events_to_publish[event.type]) { + push_event(event); + } + }, close = function() { + done = true; + while (resolvers.length > 0) + resolvers.shift()({ + value: void 0, + done: true + }); + }, push = function(data2) { + if (done) + return; + if (resolvers.length > 0) { + resolvers.shift()(data2); + } else { + values.push(data2); + } + }, push_error = function(error) { + push(thenable_reject(error)); + close(); + }, push_event = function(event) { + push({ value: event, done: false }); + }, next = function() { + if (values.length > 0) + return Promise.resolve(values.shift()); + if (done) + return Promise.resolve({ value: void 0, done: true }); + return new Promise((resolve) => resolvers.push(resolve)); + }; + const { hf_token } = this.options; + const { + fetch: fetch2, + app_reference, + config, + session_hash, + api_info, + api_map, + stream_status, + pending_stream_messages, + pending_diff_streams, + event_callbacks, + unclosed_events, + post_data: post_data2, + options + } = this; + const that = this; + if (!api_info) + throw new Error("No API found"); + if (!config) + throw new Error("Could not resolve app config"); + let { fn_index, endpoint_info, dependency } = get_endpoint_info( + api_info, + endpoint, + api_map, + config + ); + let resolved_data = map_data_to_params(data, api_info); + let websocket; + let stream2; + let protocol = config.protocol ?? "ws"; + const _endpoint = typeof endpoint === "number" ? "/predict" : endpoint; + let payload; + let event_id = null; + let complete = false; + let last_status = {}; + let url_params = typeof window !== "undefined" && typeof document !== "undefined" ? new URLSearchParams(window.location.search).toString() : ""; + const events_to_publish = ((_a = options == null ? void 0 : options.events) == null ? void 0 : _a.reduce( + (acc, event) => { + acc[event] = true; + return acc; + }, + {} + )) || {}; + async function cancel() { + const _status = { + stage: "complete", + queue: false, + time: /* @__PURE__ */ new Date() + }; + complete = _status; + fire_event({ + ..._status, + type: "status", + endpoint: _endpoint, + fn_index + }); + let reset_request = {}; + let cancel_request = {}; + if (protocol === "ws") { + if (websocket && websocket.readyState === 0) { + websocket.addEventListener("open", () => { + websocket.close(); + }); + } else { + websocket.close(); + } + reset_request = { fn_index, session_hash }; + } else { + close_stream(stream_status, that.abort_controller); + close(); + reset_request = { event_id }; + cancel_request = { event_id, session_hash, fn_index }; + } + try { + if (!config) { + throw new Error("Could not resolve app config"); + } + if ("event_id" in cancel_request) { + await fetch2(`${config.root}/cancel`, { + headers: { "Content-Type": "application/json" }, + method: "POST", + body: JSON.stringify(cancel_request) + }); + } + await fetch2(`${config.root}/reset`, { + headers: { "Content-Type": "application/json" }, + method: "POST", + body: JSON.stringify(reset_request) + }); + } catch (e) { + console.warn( + "The `/reset` endpoint could not be called. Subsequent endpoint results may be unreliable." + ); + } + } + const resolve_heartbeat = async (config2) => { + await this._resolve_hearbeat(config2); + }; + async function handle_render_config(render_config) { + if (!config) + return; + let render_id = render_config.render_id; + config.components = [ + ...config.components.filter((c) => c.props.rendered_in !== render_id), + ...render_config.components + ]; + config.dependencies = [ + ...config.dependencies.filter((d) => d.rendered_in !== render_id), + ...render_config.dependencies + ]; + const any_state = config.components.some((c) => c.type === "state"); + const any_unload = config.dependencies.some( + (d) => d.targets.some((t) => t[1] === "unload") + ); + config.connect_heartbeat = any_state || any_unload; + await resolve_heartbeat(config); + fire_event({ + type: "render", + data: render_config, + endpoint: _endpoint, + fn_index + }); + } + this.handle_blob(config.root, resolved_data, endpoint_info).then( + async (_payload) => { + var _a2; + let input_data = handle_payload( + _payload, + dependency, + config.components, + "input", + true + ); + payload = { + data: input_data || [], + event_data, + fn_index, + trigger_id + }; + if (skip_queue(fn_index, config)) { + fire_event({ + type: "status", + endpoint: _endpoint, + stage: "pending", + queue: false, + fn_index, + time: /* @__PURE__ */ new Date() + }); + post_data2( + `${config.root}/run${_endpoint.startsWith("/") ? _endpoint : `/${_endpoint}`}${url_params ? "?" + url_params : ""}`, + { + ...payload, + session_hash + } + ).then(([output, status_code]) => { + const data2 = output.data; + if (status_code == 200) { + fire_event({ + type: "data", + endpoint: _endpoint, + fn_index, + data: handle_payload( + data2, + dependency, + config.components, + "output", + options.with_null_state + ), + time: /* @__PURE__ */ new Date(), + event_data, + trigger_id + }); + if (output.render_config) { + handle_render_config(output.render_config); } - websocket = new WebSocket(url); - websocket.onclose = (evt) => { - if (!evt.wasClean) { - fire_event({ - type: "status", - stage: "error", - broken: true, - message: BROKEN_CONNECTION_MSG, - queue: true, - endpoint: _endpoint, - fn_index, - time: /* @__PURE__ */ new Date() - }); - } - }; - websocket.onmessage = function(event) { - const _data = JSON.parse(event.data); - const { type, status, data: data2 } = handle_message( - _data, - last_status[fn_index] - ); - if (type === "update" && status && !complete) { - fire_event({ - type: "status", - endpoint: _endpoint, - fn_index, - time: /* @__PURE__ */ new Date(), - ...status - }); - if (status.stage === "error") { - websocket.close(); - } - } else if (type === "hash") { - websocket.send(JSON.stringify({ fn_index, session_hash })); - return; - } else if (type === "data") { - websocket.send(JSON.stringify({ ...payload, session_hash })); - } else if (type === "complete") { - complete = status; - } else if (type === "log") { - fire_event({ - type: "log", - log: data2.log, - level: data2.level, - endpoint: _endpoint, - fn_index - }); - } else if (type === "generating") { - fire_event({ - type: "status", - time: /* @__PURE__ */ new Date(), - ...status, - stage: status == null ? void 0 : status.stage, - queue: true, - endpoint: _endpoint, - fn_index - }); - } - if (data2) { - fire_event({ - type: "data", - time: /* @__PURE__ */ new Date(), - data: transform_files ? transform_output( - data2.data, - api_info, - config.root, - config.root_url - ) : data2.data, - endpoint: _endpoint, - fn_index - }); - if (complete) { - fire_event({ - type: "status", - time: /* @__PURE__ */ new Date(), - ...complete, - stage: status == null ? void 0 : status.stage, - queue: true, - endpoint: _endpoint, - fn_index - }); - websocket.close(); - } - } - }; - if (semiver(config.version || "2.0.0", "3.6") < 0) { - addEventListener( - "open", - () => websocket.send(JSON.stringify({ hash: session_hash })) - ); + fire_event({ + type: "status", + endpoint: _endpoint, + fn_index, + stage: "complete", + eta: output.average_duration, + queue: false, + time: /* @__PURE__ */ new Date() + }); + } else { + fire_event({ + type: "status", + stage: "error", + endpoint: _endpoint, + fn_index, + message: output.error, + queue: false, + time: /* @__PURE__ */ new Date() + }); + } + }).catch((e) => { + fire_event({ + type: "status", + stage: "error", + message: e.message, + endpoint: _endpoint, + fn_index, + queue: false, + time: /* @__PURE__ */ new Date() + }); + }); + } else if (protocol == "ws") { + const { ws_protocol, host } = await process_endpoint( + app_reference, + hf_token + ); + fire_event({ + type: "status", + stage: "pending", + queue: true, + endpoint: _endpoint, + fn_index, + time: /* @__PURE__ */ new Date() + }); + let url = new URL( + `${ws_protocol}://${resolve_root( + host, + config.path, + true + )}/queue/join${url_params ? "?" + url_params : ""}` + ); + if (this.jwt) { + url.searchParams.set("__sign", this.jwt); + } + websocket = new WebSocket(url); + websocket.onclose = (evt) => { + if (!evt.wasClean) { + fire_event({ + type: "status", + stage: "error", + broken: true, + message: BROKEN_CONNECTION_MSG, + queue: true, + endpoint: _endpoint, + fn_index, + time: /* @__PURE__ */ new Date() + }); + } + }; + websocket.onmessage = function(event) { + const _data = JSON.parse(event.data); + const { type, status, data: data2 } = handle_message( + _data, + last_status[fn_index] + ); + if (type === "update" && status && !complete) { + fire_event({ + type: "status", + endpoint: _endpoint, + fn_index, + time: /* @__PURE__ */ new Date(), + ...status + }); + if (status.stage === "error") { + websocket.close(); + } + } else if (type === "hash") { + websocket.send(JSON.stringify({ fn_index, session_hash })); + return; + } else if (type === "data") { + websocket.send(JSON.stringify({ ...payload, session_hash })); + } else if (type === "complete") { + complete = status; + } else if (type === "log") { + fire_event({ + type: "log", + log: data2.log, + level: data2.level, + endpoint: _endpoint, + fn_index + }); + } else if (type === "generating") { + fire_event({ + type: "status", + time: /* @__PURE__ */ new Date(), + ...status, + stage: status == null ? void 0 : status.stage, + queue: true, + endpoint: _endpoint, + fn_index + }); + } + if (data2) { + fire_event({ + type: "data", + time: /* @__PURE__ */ new Date(), + data: handle_payload( + data2.data, + dependency, + config.components, + "output", + options.with_null_state + ), + endpoint: _endpoint, + fn_index, + event_data, + trigger_id + }); + if (complete) { + fire_event({ + type: "status", + time: /* @__PURE__ */ new Date(), + ...complete, + stage: status == null ? void 0 : status.stage, + queue: true, + endpoint: _endpoint, + fn_index + }); + websocket.close(); + } + } + }; + if (semiver(config.version || "2.0.0", "3.6") < 0) { + addEventListener( + "open", + () => websocket.send(JSON.stringify({ hash: session_hash })) + ); + } + } else if (protocol == "sse") { + fire_event({ + type: "status", + stage: "pending", + queue: true, + endpoint: _endpoint, + fn_index, + time: /* @__PURE__ */ new Date() + }); + var params = new URLSearchParams({ + fn_index: fn_index.toString(), + session_hash + }).toString(); + let url = new URL( + `${config.root}/queue/join?${url_params ? url_params + "&" : ""}${params}` + ); + if (this.jwt) { + url.searchParams.set("__sign", this.jwt); + } + stream2 = this.stream(url); + if (!stream2) { + return Promise.reject( + new Error("Cannot connect to SSE endpoint: " + url.toString()) + ); + } + stream2.onmessage = async function(event) { + const _data = JSON.parse(event.data); + const { type, status, data: data2 } = handle_message( + _data, + last_status[fn_index] + ); + if (type === "update" && status && !complete) { + fire_event({ + type: "status", + endpoint: _endpoint, + fn_index, + time: /* @__PURE__ */ new Date(), + ...status + }); + if (status.stage === "error") { + stream2 == null ? void 0 : stream2.close(); + close(); + } + } else if (type === "data") { + event_id = _data.event_id; + let [_, status2] = await post_data2(`${config.root}/queue/data`, { + ...payload, + session_hash, + event_id + }); + if (status2 !== 200) { + fire_event({ + type: "status", + stage: "error", + message: BROKEN_CONNECTION_MSG, + queue: true, + endpoint: _endpoint, + fn_index, + time: /* @__PURE__ */ new Date() + }); + stream2 == null ? void 0 : stream2.close(); + close(); } - } else if (protocol == "sse") { + } else if (type === "complete") { + complete = status; + } else if (type === "log") { + fire_event({ + type: "log", + log: data2.log, + level: data2.level, + endpoint: _endpoint, + fn_index + }); + } else if (type === "generating") { fire_event({ type: "status", - stage: "pending", + time: /* @__PURE__ */ new Date(), + ...status, + stage: status == null ? void 0 : status.stage, queue: true, endpoint: _endpoint, + fn_index + }); + } + if (data2) { + fire_event({ + type: "data", + time: /* @__PURE__ */ new Date(), + data: handle_payload( + data2.data, + dependency, + config.components, + "output", + options.with_null_state + ), + endpoint: _endpoint, fn_index, - time: /* @__PURE__ */ new Date() + event_data, + trigger_id }); - var params = new URLSearchParams({ - fn_index: fn_index.toString(), + if (complete) { + fire_event({ + type: "status", + time: /* @__PURE__ */ new Date(), + ...complete, + stage: status == null ? void 0 : status.stage, + queue: true, + endpoint: _endpoint, + fn_index + }); + stream2 == null ? void 0 : stream2.close(); + close(); + } + } + }; + } else if (protocol == "sse_v1" || protocol == "sse_v2" || protocol == "sse_v2.1" || protocol == "sse_v3") { + fire_event({ + type: "status", + stage: "pending", + queue: true, + endpoint: _endpoint, + fn_index, + time: /* @__PURE__ */ new Date() + }); + let hostname = ""; + if (typeof window !== "undefined" && typeof document !== "undefined") { + hostname = (_a2 = window == null ? void 0 : window.location) == null ? void 0 : _a2.hostname; + } + let hfhubdev = "dev.spaces.huggingface.tech"; + const origin = hostname.includes(".dev.") ? `https://moon-${hostname.split(".")[1]}.${hfhubdev}` : `https://huggingface.co`; + const is_iframe = typeof window !== "undefined" && typeof document !== "undefined" && window.parent != window; + const is_zerogpu_space = dependency.zerogpu && config.space_id; + const zerogpu_auth_promise = is_iframe && is_zerogpu_space ? post_message("zerogpu-headers", origin) : Promise.resolve(null); + const post_data_promise = zerogpu_auth_promise.then((headers) => { + return post_data2( + `${config.root}/queue/join?${url_params}`, + { + ...payload, session_hash - }).toString(); - let url = new URL( - `${config.root}/queue/join?${url_params ? url_params + "&" : ""}${params}` - ); - eventSource = EventSource_factory(url); - eventSource.onmessage = async function(event) { - const _data = JSON.parse(event.data); - const { type, status, data: data2 } = handle_message( - _data, - last_status[fn_index] - ); - if (type === "update" && status && !complete) { - fire_event({ - type: "status", - endpoint: _endpoint, - fn_index, - time: /* @__PURE__ */ new Date(), - ...status - }); - if (status.stage === "error") { - eventSource.close(); - } - } else if (type === "data") { - event_id = _data.event_id; - let [_, status2] = await post_data2( - `${config.root}/queue/data`, - { - ...payload, - session_hash, - event_id - }, - hf_token + }, + headers + ); + }); + post_data_promise.then(async ([response, status]) => { + if (status === 503) { + fire_event({ + type: "status", + stage: "error", + message: QUEUE_FULL_MSG, + queue: true, + endpoint: _endpoint, + fn_index, + time: /* @__PURE__ */ new Date() + }); + } else if (status !== 200) { + fire_event({ + type: "status", + stage: "error", + message: BROKEN_CONNECTION_MSG, + queue: true, + endpoint: _endpoint, + fn_index, + time: /* @__PURE__ */ new Date() + }); + } else { + event_id = response.event_id; + let callback = async function(_data) { + try { + const { type, status: status2, data: data2 } = handle_message( + _data, + last_status[fn_index] ); - if (status2 !== 200) { + if (type == "heartbeat") { + return; + } + if (type === "update" && status2 && !complete) { + fire_event({ + type: "status", + endpoint: _endpoint, + fn_index, + time: /* @__PURE__ */ new Date(), + ...status2 + }); + } else if (type === "complete") { + complete = status2; + } else if (type == "unexpected_error") { + console.error("Unexpected error", status2 == null ? void 0 : status2.message); fire_event({ type: "status", stage: "error", - message: BROKEN_CONNECTION_MSG, + message: (status2 == null ? void 0 : status2.message) || "An Unexpected Error Occurred!", queue: true, endpoint: _endpoint, fn_index, time: /* @__PURE__ */ new Date() }); - eventSource.close(); - } - } else if (type === "complete") { - complete = status; - } else if (type === "log") { - fire_event({ - type: "log", - log: data2.log, - level: data2.level, - endpoint: _endpoint, - fn_index - }); - } else if (type === "generating") { - fire_event({ - type: "status", - time: /* @__PURE__ */ new Date(), - ...status, - stage: status == null ? void 0 : status.stage, - queue: true, - endpoint: _endpoint, - fn_index - }); - } - if (data2) { - fire_event({ - type: "data", - time: /* @__PURE__ */ new Date(), - data: transform_files ? transform_output( - data2.data, - api_info, - config.root, - config.root_url - ) : data2.data, - endpoint: _endpoint, - fn_index - }); - if (complete) { + } else if (type === "log") { + fire_event({ + type: "log", + log: data2.log, + level: data2.level, + endpoint: _endpoint, + fn_index + }); + return; + } else if (type === "generating") { fire_event({ type: "status", time: /* @__PURE__ */ new Date(), - ...complete, - stage: status == null ? void 0 : status.stage, + ...status2, + stage: status2 == null ? void 0 : status2.stage, queue: true, endpoint: _endpoint, fn_index }); - eventSource.close(); + if (data2 && ["sse_v2", "sse_v2.1", "sse_v3"].includes(protocol)) { + apply_diff_stream(pending_diff_streams, event_id, data2); + } } - } - }; - } else if (protocol == "sse_v1") { - fire_event({ - type: "status", - stage: "pending", - queue: true, - endpoint: _endpoint, - fn_index, - time: /* @__PURE__ */ new Date() - }); - post_data2( - `${config.root}/queue/join?${url_params}`, - { - ...payload, - session_hash - }, - hf_token - ).then(([response, status]) => { - if (status === 503) { - fire_event({ - type: "status", - stage: "error", - message: QUEUE_FULL_MSG, - queue: true, - endpoint: _endpoint, - fn_index, - time: /* @__PURE__ */ new Date() - }); - } else if (status !== 200) { + if (data2) { + fire_event({ + type: "data", + time: /* @__PURE__ */ new Date(), + data: handle_payload( + data2.data, + dependency, + config.components, + "output", + options.with_null_state + ), + endpoint: _endpoint, + fn_index + }); + if (data2.render_config) { + await handle_render_config(data2.render_config); + } + if (complete) { + fire_event({ + type: "status", + time: /* @__PURE__ */ new Date(), + ...complete, + stage: status2 == null ? void 0 : status2.stage, + queue: true, + endpoint: _endpoint, + fn_index + }); + } + } + if ((status2 == null ? void 0 : status2.stage) === "complete" || (status2 == null ? void 0 : status2.stage) === "error") { + if (event_callbacks[event_id]) { + delete event_callbacks[event_id]; + } + if (event_id in pending_diff_streams) { + delete pending_diff_streams[event_id]; + } + } + } catch (e) { + console.error("Unexpected client exception", e); fire_event({ type: "status", stage: "error", - message: BROKEN_CONNECTION_MSG, + message: "An Unexpected Error Occurred!", queue: true, endpoint: _endpoint, fn_index, time: /* @__PURE__ */ new Date() }); - } else { - event_id = response.event_id; - let callback = async function(_data) { - try { - const { type, status: status2, data: data2 } = handle_message( - _data, - last_status[fn_index] - ); - if (type == "heartbeat") { - return; - } - if (type === "update" && status2 && !complete) { - fire_event({ - type: "status", - endpoint: _endpoint, - fn_index, - time: /* @__PURE__ */ new Date(), - ...status2 - }); - } else if (type === "complete") { - complete = status2; - } else if (type == "unexpected_error") { - console.error("Unexpected error", status2 == null ? void 0 : status2.message); - fire_event({ - type: "status", - stage: "error", - message: (status2 == null ? void 0 : status2.message) || "An Unexpected Error Occurred!", - queue: true, - endpoint: _endpoint, - fn_index, - time: /* @__PURE__ */ new Date() - }); - } else if (type === "log") { - fire_event({ - type: "log", - log: data2.log, - level: data2.level, - endpoint: _endpoint, - fn_index - }); - return; - } else if (type === "generating") { - fire_event({ - type: "status", - time: /* @__PURE__ */ new Date(), - ...status2, - stage: status2 == null ? void 0 : status2.stage, - queue: true, - endpoint: _endpoint, - fn_index - }); - } - if (data2) { - fire_event({ - type: "data", - time: /* @__PURE__ */ new Date(), - data: transform_files ? transform_output( - data2.data, - api_info, - config.root, - config.root_url - ) : data2.data, - endpoint: _endpoint, - fn_index - }); - if (complete) { - fire_event({ - type: "status", - time: /* @__PURE__ */ new Date(), - ...complete, - stage: status2 == null ? void 0 : status2.stage, - queue: true, - endpoint: _endpoint, - fn_index - }); - } - } - if ((status2 == null ? void 0 : status2.stage) === "complete" || (status2 == null ? void 0 : status2.stage) === "error") { - if (event_callbacks[event_id]) { - delete event_callbacks[event_id]; - } - } - } catch (e) { - console.error("Unexpected client exception", e); - fire_event({ - type: "status", - stage: "error", - message: "An Unexpected Error Occurred!", - queue: true, - endpoint: _endpoint, - fn_index, - time: /* @__PURE__ */ new Date() - }); - close_stream(); - } - }; - if (event_id in pending_stream_messages) { - pending_stream_messages[event_id].forEach( - (msg) => callback(msg) - ); - delete pending_stream_messages[event_id]; - } - event_callbacks[event_id] = callback; - unclosed_events.add(event_id); - if (!stream_open) { - open_stream(); + if (["sse_v2", "sse_v2.1", "sse_v3"].includes(protocol)) { + close_stream(stream_status, that.abort_controller); + stream_status.open = false; + close(); } } - }); - } - } - ); - function fire_event(event) { - const narrowed_listener_map = listener_map; - const listeners = narrowed_listener_map[event.type] || []; - listeners == null ? void 0 : listeners.forEach((l) => l(event)); - } - function on(eventType, listener) { - const narrowed_listener_map = listener_map; - const listeners = narrowed_listener_map[eventType] || []; - narrowed_listener_map[eventType] = listeners; - listeners == null ? void 0 : listeners.push(listener); - return { on, off, cancel, destroy }; - } - function off(eventType, listener) { - const narrowed_listener_map = listener_map; - let listeners = narrowed_listener_map[eventType] || []; - listeners = listeners == null ? void 0 : listeners.filter((l) => l !== listener); - narrowed_listener_map[eventType] = listeners; - return { on, off, cancel, destroy }; - } - async function cancel() { - const _status = { - stage: "complete", - queue: false, - time: /* @__PURE__ */ new Date() - }; - complete = _status; - fire_event({ - ..._status, - type: "status", - endpoint: _endpoint, - fn_index - }); - let cancel_request = {}; - if (protocol === "ws") { - if (websocket && websocket.readyState === 0) { - websocket.addEventListener("open", () => { - websocket.close(); - }); - } else { - websocket.close(); - } - cancel_request = { fn_index, session_hash }; - } else { - eventSource.close(); - cancel_request = { event_id }; - } - try { - await fetch_implementation(`${config.root}/reset`, { - headers: { "Content-Type": "application/json" }, - method: "POST", - body: JSON.stringify(cancel_request) - }); - } catch (e) { - console.warn( - "The `/reset` endpoint could not be called. Subsequent endpoint results may be unreliable." - ); - } - } - function destroy() { - for (const event_type in listener_map) { - listener_map[event_type].forEach((fn2) => { - off(event_type, fn2); - }); - } - } - return { - on, - off, - cancel, - destroy - }; - } - function open_stream() { - stream_open = true; - let params = new URLSearchParams({ - session_hash - }).toString(); - let url = new URL(`${config.root}/queue/data?${params}`); - event_stream = EventSource_factory(url); - event_stream.onmessage = async function(event) { - let _data = JSON.parse(event.data); - const event_id = _data.event_id; - if (!event_id) { - await Promise.all( - Object.keys(event_callbacks).map( - (event_id2) => event_callbacks[event_id2](_data) - ) - ); - } else if (event_callbacks[event_id]) { - if (_data.msg === "process_completed") { - unclosed_events.delete(event_id); - if (unclosed_events.size === 0) { - close_stream(); + }; + if (event_id in pending_stream_messages) { + pending_stream_messages[event_id].forEach( + (msg) => callback(msg) + ); + delete pending_stream_messages[event_id]; + } + event_callbacks[event_id] = callback; + unclosed_events.add(event_id); + if (!stream_status.open) { + await this.open_stream(); } } - let fn2 = event_callbacks[event_id]; - window.setTimeout(fn2, 0, _data); - } else { - if (!pending_stream_messages[event_id]) { - pending_stream_messages[event_id] = []; - } - pending_stream_messages[event_id].push(_data); - } - }; - event_stream.onerror = async function(event) { - await Promise.all( - Object.keys(event_callbacks).map( - (event_id) => event_callbacks[event_id]({ - msg: "unexpected_error", - message: BROKEN_CONNECTION_MSG - }) - ) - ); - close_stream(); - }; - } - function close_stream() { - stream_open = false; - event_stream == null ? void 0 : event_stream.close(); - } - async function component_server(component_id, fn_name, data) { - var _a; - const headers = { "Content-Type": "application/json" }; - if (hf_token) { - headers.Authorization = `Bearer ${hf_token}`; - } - let root_url; - let component = config.components.find( - (comp) => comp.id === component_id - ); - if ((_a = component == null ? void 0 : component.props) == null ? void 0 : _a.root_url) { - root_url = component.props.root_url; - } else { - root_url = config.root; - } - const response = await fetch_implementation( - `${root_url}/component_server/`, - { - method: "POST", - body: JSON.stringify({ - data, - component_id, - fn_name, - session_hash - }), - headers - } - ); - if (!response.ok) { - throw new Error( - "Could not connect to component server: " + response.statusText - ); - } - const output = await response.json(); - return output; - } - async function view_api(config2) { - if (api) - return api; - const headers = { "Content-Type": "application/json" }; - if (hf_token) { - headers.Authorization = `Bearer ${hf_token}`; - } - let response; - if (semiver(config2.version || "2.0.0", "3.30") < 0) { - response = await fetch_implementation( - "https://gradio-space-api-fetcher-v2.hf.space/api", - { - method: "POST", - body: JSON.stringify({ - serialize: false, - config: JSON.stringify(config2) - }), - headers - } - ); - } else { - response = await fetch_implementation(`${config2.root}/info`, { - headers }); } - if (!response.ok) { - throw new Error(BROKEN_CONNECTION_MSG); - } - let api_info = await response.json(); - if ("api" in api_info) { - api_info = api_info.api; - } - if (api_info.named_endpoints["/predict"] && !api_info.unnamed_endpoints["0"]) { - api_info.unnamed_endpoints[0] = api_info.named_endpoints["/predict"]; - } - const x = transform_api_info(api_info, config2, api_map); - return x; } - }); + ); + let done = false; + const values = []; + const resolvers = []; + const iterator = { + [Symbol.asyncIterator]: () => iterator, + next, + throw: async (value) => { + push_error(value); + return next(); + }, + return: async () => { + close(); + return next(); + }, + cancel + }; + return iterator; + } catch (error) { + console.error("Submit function encountered an error:", error); + throw error; } - async function handle_blob2(endpoint, data, api_info, token) { - const blob_refs = await walk_and_store_blobs( - data, - void 0, - [], - true, - api_info +} +function thenable_reject(error) { + return { + then: (resolve, reject) => reject(error) + }; +} +function get_endpoint_info(api_info, endpoint, api_map, config) { + let fn_index; + let endpoint_info; + let dependency; + if (typeof endpoint === "number") { + fn_index = endpoint; + endpoint_info = api_info.unnamed_endpoints[fn_index]; + dependency = config.dependencies.find((dep) => dep.id == endpoint); + } else { + const trimmed_endpoint = endpoint.replace(/^\//, ""); + fn_index = api_map[trimmed_endpoint]; + endpoint_info = api_info.named_endpoints[endpoint.trim()]; + dependency = config.dependencies.find( + (dep) => dep.id == api_map[trimmed_endpoint] + ); + } + if (typeof fn_index !== "number") { + throw new Error( + "There is no endpoint matching that name of fn_index matching that number." ); - return Promise.all( - blob_refs.map(async ({ path, blob, type }) => { - if (blob) { - const file_url = (await upload_files2(endpoint, [blob], token)).files[0]; - return { path, file_url, type, name: blob == null ? void 0 : blob.name }; - } - return { path, type }; - }) - ).then((r) => { - r.forEach(({ path, file_url, type, name }) => { - if (type === "Gallery") { - update_object(data, file_url, path); - } else if (file_url) { - const file = new FileData({ path: file_url, orig_name: name }); - update_object(data, file, path); - } - }); - return data; - }); } + return { fn_index, endpoint_info, dependency }; } -const { post_data, upload_files, client, handle_blob } = api_factory( - fetch, - (...args) => new EventSource(...args) -); -function transform_output(data, api_info, root_url, remote_url) { - return data.map((d, i) => { - var _a, _b, _c, _d; - if (((_b = (_a = api_info == null ? void 0 : api_info.returns) == null ? void 0 : _a[i]) == null ? void 0 : _b.component) === "File") { - return normalise_file(d, root_url, remote_url); - } else if (((_d = (_c = api_info == null ? void 0 : api_info.returns) == null ? void 0 : _c[i]) == null ? void 0 : _d.component) === "Gallery") { - return d.map((img) => { - return Array.isArray(img) ? [normalise_file(img[0], root_url, remote_url), img[1]] : [normalise_file(img, root_url, remote_url), null]; - }); - } else if (typeof d === "object" && d.path) { - return normalise_file(d, root_url, remote_url); +class Client { + constructor(app_reference, options = { events: ["data"] }) { + __publicField(this, "app_reference"); + __publicField(this, "options"); + __publicField(this, "config"); + __publicField(this, "api_info"); + __publicField(this, "api_map", {}); + __publicField(this, "session_hash", Math.random().toString(36).substring(2)); + __publicField(this, "jwt", false); + __publicField(this, "last_status", {}); + __publicField(this, "cookies", null); + // streaming + __publicField(this, "stream_status", { open: false }); + __publicField(this, "pending_stream_messages", {}); + __publicField(this, "pending_diff_streams", {}); + __publicField(this, "event_callbacks", {}); + __publicField(this, "unclosed_events", /* @__PURE__ */ new Set()); + __publicField(this, "heartbeat_event", null); + __publicField(this, "abort_controller", null); + __publicField(this, "stream_instance", null); + __publicField(this, "view_api"); + __publicField(this, "upload_files"); + __publicField(this, "upload"); + __publicField(this, "handle_blob"); + __publicField(this, "post_data"); + __publicField(this, "submit"); + __publicField(this, "predict"); + __publicField(this, "open_stream"); + __publicField(this, "resolve_config"); + __publicField(this, "resolve_cookies"); + this.app_reference = app_reference; + if (!options.events) { + options.events = ["data"]; } - return d; - }); -} -function get_type(type, component, serializer, signature_type) { - switch (type.type) { - case "string": - return "string"; - case "boolean": - return "boolean"; - case "number": - return "number"; + this.options = options; + this.view_api = view_api.bind(this); + this.upload_files = upload_files.bind(this); + this.handle_blob = handle_blob.bind(this); + this.post_data = post_data.bind(this); + this.submit = submit.bind(this); + this.predict = predict.bind(this); + this.open_stream = open_stream.bind(this); + this.resolve_config = resolve_config.bind(this); + this.resolve_cookies = resolve_cookies.bind(this); + this.upload = upload.bind(this); } - if (serializer === "JSONSerializable" || serializer === "StringSerializable") { - return "any"; - } else if (serializer === "ListStringSerializable") { - return "string[]"; - } else if (component === "Image") { - return signature_type === "parameter" ? "Blob | File | Buffer" : "string"; - } else if (serializer === "FileSerializable") { - if ((type == null ? void 0 : type.type) === "array") { - return signature_type === "parameter" ? "(Blob | File | Buffer)[]" : `{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}[]`; + fetch(input, init) { + const headers = new Headers((init == null ? void 0 : init.headers) || {}); + if (this && this.cookies) { + headers.append("Cookie", this.cookies); } - return signature_type === "parameter" ? "Blob | File | Buffer" : `{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}`; - } else if (serializer === "GallerySerializable") { - return signature_type === "parameter" ? "[(Blob | File | Buffer), (string | null)][]" : `[{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}, (string | null))][]`; + return fetch(input, { ...init, headers }); } -} -function get_description(type, serializer) { - if (serializer === "GallerySerializable") { - return "array of [file, label] tuples"; - } else if (serializer === "ListStringSerializable") { - return "array of strings"; - } else if (serializer === "FileSerializable") { - return "array of files or single file"; + stream(url) { + this.abort_controller = new AbortController(); + this.stream_instance = readable_stream(url.toString(), { + signal: this.abort_controller.signal + }); + return this.stream_instance; } - return type.description; -} -function transform_api_info(api_info, config, api_map) { - const new_data = { - named_endpoints: {}, - unnamed_endpoints: {} - }; - for (const key in api_info) { - const cat = api_info[key]; - for (const endpoint in cat) { - const dep_index = config.dependencies[endpoint] ? endpoint : api_map[endpoint.replace("/", "")]; - const info = cat[endpoint]; - new_data[key][endpoint] = {}; - new_data[key][endpoint].parameters = {}; - new_data[key][endpoint].returns = {}; - new_data[key][endpoint].type = config.dependencies[dep_index].types; - new_data[key][endpoint].parameters = info.parameters.map( - ({ label, component, type, serializer }) => ({ - label, - component, - type: get_type(type, component, serializer, "parameter"), - description: get_description(type, serializer) - }) - ); - new_data[key][endpoint].returns = info.returns.map( - ({ label, component, type, serializer }) => ({ - label, - component, - type: get_type(type, component, serializer, "return"), - description: get_description(type, serializer) - }) + async init() { + var _a; + if ((typeof window === "undefined" || !("WebSocket" in window)) && !global.WebSocket) { + const ws = await import("./wrapper-CviSselG.js"); + global.WebSocket = ws.WebSocket; + } + try { + if (this.options.auth) { + await this.resolve_cookies(); + } + await this._resolve_config().then( + ({ config }) => this._resolve_hearbeat(config) ); + } catch (e) { + throw Error(e); } + this.api_info = await this.view_api(); + this.api_map = map_names_to_ids(((_a = this.config) == null ? void 0 : _a.dependencies) || []); } - return new_data; -} -async function get_jwt(space, token) { - try { - const r = await fetch(`https://huggingface.co/api/spaces/${space}/jwt`, { - headers: { - Authorization: `Bearer ${token}` + async _resolve_hearbeat(_config) { + if (_config) { + this.config = _config; + if (this.config && this.config.connect_heartbeat) { + if (this.config.space_id && this.options.hf_token) { + this.jwt = await get_jwt( + this.config.space_id, + this.options.hf_token, + this.cookies + ); + } } - }); - const jwt = (await r.json()).token; - return jwt || false; - } catch (e) { - console.error(e); - return false; + } + if (_config.space_id && this.options.hf_token) { + this.jwt = await get_jwt(_config.space_id, this.options.hf_token); + } + if (this.config && this.config.connect_heartbeat) { + const heartbeat_url = new URL( + `${this.config.root}/heartbeat/${this.session_hash}` + ); + if (this.jwt) { + heartbeat_url.searchParams.set("__sign", this.jwt); + } + if (!this.heartbeat_event) { + this.heartbeat_event = this.stream(heartbeat_url); + } + } } -} -function update_object(object, newValue, stack) { - while (stack.length > 1) { - object = object[stack.shift()]; + static async connect(app_reference, options = { + events: ["data"] + }) { + const client2 = new this(app_reference, options); + await client2.init(); + return client2; + } + close() { + var _a; + (_a = this.heartbeat_event) == null ? void 0 : _a.close(); } - object[stack.shift()] = newValue; -} -async function walk_and_store_blobs(param, type = void 0, path = [], root = false, api_info = void 0) { - if (Array.isArray(param)) { - let blob_refs = []; - await Promise.all( - param.map(async (v, i) => { - var _a; - let new_path = path.slice(); - new_path.push(i); - const array_refs = await walk_and_store_blobs( - param[i], - root ? ((_a = api_info == null ? void 0 : api_info.parameters[i]) == null ? void 0 : _a.component) || void 0 : type, - new_path, - false, - api_info - ); - blob_refs = blob_refs.concat(array_refs); - }) + static async duplicate(app_reference, options = { + events: ["data"] + }) { + return duplicate(app_reference, options); + } + async _resolve_config() { + const { http_protocol, host, space_id } = await process_endpoint( + this.app_reference, + this.options.hf_token ); - return blob_refs; - } else if (globalThis.Buffer && param instanceof globalThis.Buffer) { - const is_image = type === "Image"; - return [ - { - path, - blob: is_image ? false : new NodeBlob([param]), - type + const { status_callback } = this.options; + let config; + try { + config = await this.resolve_config(`${http_protocol}//${host}`); + if (!config) { + throw new Error(CONFIG_ERROR_MSG); } - ]; - } else if (typeof param === "object") { - let blob_refs = []; - for (let key in param) { - if (param.hasOwnProperty(key)) { - let new_path = path.slice(); - new_path.push(key); - blob_refs = blob_refs.concat( - await walk_and_store_blobs( - param[key], - void 0, - new_path, - false, - api_info - ) + return this.config_success(config); + } catch (e) { + if (space_id && status_callback) { + check_space_status( + space_id, + RE_SPACE_NAME.test(space_id) ? "space_name" : "subdomain", + this.handle_space_success ); + } else { + if (status_callback) + status_callback({ + status: "error", + message: "Could not load this space.", + load_status: "error", + detail: "NOT_FOUND" + }); + throw Error(e); } } - return blob_refs; - } - return []; -} -function skip_queue(id, config) { - var _a, _b, _c, _d; - return !(((_b = (_a = config == null ? void 0 : config.dependencies) == null ? void 0 : _a[id]) == null ? void 0 : _b.queue) === null ? config.enable_queue : (_d = (_c = config == null ? void 0 : config.dependencies) == null ? void 0 : _c[id]) == null ? void 0 : _d.queue) || false; -} -async function resolve_config(fetch_implementation, endpoint, token) { - const headers = {}; - if (token) { - headers.Authorization = `Bearer ${token}`; } - if (typeof window !== "undefined" && window.gradio_config && location.origin !== "http://localhost:9876" && !window.gradio_config.dev_mode) { - const path = window.gradio_config.root; - const config = window.gradio_config; - config.root = resolve_root(endpoint, config.root, false); - return { ...config, path }; - } else if (endpoint) { - let response = await fetch_implementation(`${endpoint}/config`, { - headers - }); - if (response.status === 200) { - const config = await response.json(); - config.path = config.path ?? ""; - config.root = endpoint; - return config; + async config_success(_config) { + this.config = _config; + if (typeof window !== "undefined" && typeof document !== "undefined") { + if (window.location.protocol === "https:") { + this.config.root = this.config.root.replace("http://", "https://"); + } + } + if (this.config.auth_required) { + return this.prepare_return_obj(); } - throw new Error("Could not get config."); + try { + this.api_info = await this.view_api(); + } catch (e) { + console.error(API_INFO_ERROR_MSG + e.message); + } + return this.prepare_return_obj(); } - throw new Error("No config or app endpoint found"); -} -async function check_space_status(id, type, status_callback) { - let endpoint = type === "subdomain" ? `https://huggingface.co/api/spaces/by-subdomain/${id}` : `https://huggingface.co/api/spaces/${id}`; - let response; - let _status; - try { - response = await fetch(endpoint); - _status = response.status; - if (_status !== 200) { - throw new Error(); + async handle_space_success(status) { + if (!this) { + throw new Error(CONFIG_ERROR_MSG); + } + const { status_callback } = this.options; + if (status_callback) + status_callback(status); + if (status.status === "running") { + try { + this.config = await this._resolve_config(); + if (!this.config) { + throw new Error(CONFIG_ERROR_MSG); + } + const _config = await this.config_success(this.config); + return _config; + } catch (e) { + if (status_callback) { + status_callback({ + status: "error", + message: "Could not load this space.", + load_status: "error", + detail: "NOT_FOUND" + }); + } + throw e; + } } - response = await response.json(); - } catch (e) { - status_callback({ - status: "error", - load_status: "error", - message: "Could not get space status", - detail: "NOT_FOUND" - }); - return; } - if (!response || _status !== 200) - return; - const { - runtime: { stage }, - id: space_name - } = response; - switch (stage) { - case "STOPPED": - case "SLEEPING": - status_callback({ - status: "sleeping", - load_status: "pending", - message: "Space is asleep. Waking it up...", - detail: stage - }); - setTimeout(() => { - check_space_status(id, type, status_callback); - }, 1e3); - break; - case "PAUSED": - status_callback({ - status: "paused", - load_status: "error", - message: "This space has been paused by the author. If you would like to try this demo, consider duplicating the space.", - detail: stage, - discussions_enabled: await discussions_enabled(space_name) - }); - break; - case "RUNNING": - case "RUNNING_BUILDING": - status_callback({ - status: "running", - load_status: "complete", - message: "", - detail: stage - }); - break; - case "BUILDING": - status_callback({ - status: "building", - load_status: "pending", - message: "Space is building...", - detail: stage + async component_server(component_id, fn_name, data) { + var _a; + if (!this.config) { + throw new Error(CONFIG_ERROR_MSG); + } + const headers = {}; + const { hf_token } = this.options; + const { session_hash } = this; + if (hf_token) { + headers.Authorization = `Bearer ${this.options.hf_token}`; + } + let root_url; + let component = this.config.components.find( + (comp) => comp.id === component_id + ); + if ((_a = component == null ? void 0 : component.props) == null ? void 0 : _a.root_url) { + root_url = component.props.root_url; + } else { + root_url = this.config.root; + } + let body; + if ("binary" in data) { + body = new FormData(); + for (const key in data.data) { + if (key === "binary") + continue; + body.append(key, data.data[key]); + } + body.set("component_id", component_id.toString()); + body.set("fn_name", fn_name); + body.set("session_hash", session_hash); + } else { + body = JSON.stringify({ + data, + component_id, + fn_name, + session_hash }); - setTimeout(() => { - check_space_status(id, type, status_callback); - }, 1e3); - break; - default: - status_callback({ - status: "space_error", - load_status: "error", - message: "This space is experiencing an issue.", - detail: stage, - discussions_enabled: await discussions_enabled(space_name) + headers["Content-Type"] = "application/json"; + } + if (hf_token) { + headers.Authorization = `Bearer ${hf_token}`; + } + try { + const response = await this.fetch(`${root_url}/component_server/`, { + method: "POST", + body, + headers, + credentials: "include" }); - break; - } -} -function handle_message(data, last_status) { - const queue = true; - switch (data.msg) { - case "send_data": - return { type: "data" }; - case "send_hash": - return { type: "hash" }; - case "queue_full": - return { - type: "update", - status: { - queue, - message: QUEUE_FULL_MSG, - stage: "error", - code: data.code, - success: data.success - } - }; - case "heartbeat": - return { - type: "heartbeat" - }; - case "unexpected_error": - return { - type: "unexpected_error", - status: { - queue, - message: data.message, - stage: "error", - success: false - } - }; - case "estimation": - return { - type: "update", - status: { - queue, - stage: last_status || "pending", - code: data.code, - size: data.queue_size, - position: data.rank, - eta: data.rank_eta, - success: data.success - } - }; - case "progress": - return { - type: "update", - status: { - queue, - stage: "pending", - code: data.code, - progress_data: data.progress_data, - success: data.success - } - }; - case "log": - return { type: "log", data }; - case "process_generating": - return { - type: "generating", - status: { - queue, - message: !data.success ? data.output.error : null, - stage: data.success ? "generating" : "error", - code: data.code, - progress_data: data.progress_data, - eta: data.average_duration - }, - data: data.success ? data.output : null - }; - case "process_completed": - if ("error" in data.output) { - return { - type: "update", - status: { - queue, - message: data.output.error, - stage: "error", - code: data.code, - success: data.success - } - }; + if (!response.ok) { + throw new Error( + "Could not connect to component server: " + response.statusText + ); } - return { - type: "complete", - status: { - queue, - message: !data.success ? data.output.error : void 0, - stage: data.success ? "complete" : "error", - code: data.code, - progress_data: data.progress_data - }, - data: data.success ? data.output : null - }; - case "process_starts": - return { - type: "update", - status: { - queue, - stage: "pending", - code: data.code, - size: data.rank, - position: 0, - success: data.success, - eta: data.eta - } - }; + const output = await response.json(); + return output; + } catch (e) { + console.warn(e); + } } - return { type: "none", status: { stage: "error", queue } }; + set_cookies(raw_cookies) { + this.cookies = parse_and_set_cookies(raw_cookies).join("; "); + } + prepare_return_obj() { + return { + config: this.config, + predict: this.predict, + submit: this.submit, + view_api: this.view_api, + component_server: this.component_server + }; + } +} +async function client(app_reference, options = { + events: ["data"] +}) { + return await Client.connect(app_reference, options); +} +async function duplicate_space(app_reference, options) { + return await Client.duplicate(app_reference, options); } export { + Client, FileData, - api_factory, client, - duplicate, - get_fetchable_url_or_file, - normalise_file, - post_data, + duplicate_space as duplicate, + handle_file, + predict, prepare_files, + submit, upload, upload_files }; diff --git a/node_modules/@gradio/client/dist/test/handlers.d.ts b/node_modules/@gradio/client/dist/test/handlers.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..379dbe7871f6d0e74290139b977598640ed6e2a3 --- /dev/null +++ b/node_modules/@gradio/client/dist/test/handlers.d.ts @@ -0,0 +1,4 @@ +import { RequestHandler } from "msw"; +export declare const direct_space_url = "https://hmb-hello-world.hf.space"; +export declare const handlers: RequestHandler[]; +//# sourceMappingURL=handlers.d.ts.map \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/test/handlers.d.ts.map b/node_modules/@gradio/client/dist/test/handlers.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..af40fffe69b02ab37140d82f30cf211e48a63467 --- /dev/null +++ b/node_modules/@gradio/client/dist/test/handlers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"handlers.d.ts","sourceRoot":"","sources":["../../src/test/handlers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsB,cAAc,EAAE,MAAM,KAAK,CAAC;AAuBzD,eAAO,MAAM,gBAAgB,qCAAqC,CAAC;AAqBnE,eAAO,MAAM,QAAQ,EAAE,cAAc,EAwoBpC,CAAC"} \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/test/mock_eventsource.d.ts b/node_modules/@gradio/client/dist/test/mock_eventsource.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fecaa636c8deed45b2f0cebced58e709815d94db --- /dev/null +++ b/node_modules/@gradio/client/dist/test/mock_eventsource.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=mock_eventsource.d.ts.map \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/test/mock_eventsource.d.ts.map b/node_modules/@gradio/client/dist/test/mock_eventsource.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..5a249f5a4ae9c0a41b8a6f26d27eb2d227927793 --- /dev/null +++ b/node_modules/@gradio/client/dist/test/mock_eventsource.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"mock_eventsource.d.ts","sourceRoot":"","sources":["../../src/test/mock_eventsource.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/test/server.d.ts b/node_modules/@gradio/client/dist/test/server.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e7b6d7385d7c54cc5ccea7f30f30ab24ce407242 --- /dev/null +++ b/node_modules/@gradio/client/dist/test/server.d.ts @@ -0,0 +1,2 @@ +export declare function initialise_server(): any; +//# sourceMappingURL=server.d.ts.map \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/test/server.d.ts.map b/node_modules/@gradio/client/dist/test/server.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..da108d064bf287d0e7756476543e476bf7dcc8e6 --- /dev/null +++ b/node_modules/@gradio/client/dist/test/server.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/test/server.ts"],"names":[],"mappings":"AAGA,wBAAgB,iBAAiB,IAAI,GAAG,CAEvC"} \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/test/test_data.d.ts b/node_modules/@gradio/client/dist/test/test_data.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..992f31d292809e5ee921bf176724a75553a68f9f --- /dev/null +++ b/node_modules/@gradio/client/dist/test/test_data.d.ts @@ -0,0 +1,76 @@ +import { ApiData, ApiInfo, Config, EndpointInfo } from "../types"; +export declare const runtime_response: { + stage: string; + hardware: { + current: string; + requested: string; + }; + storage: { + current: null; + requested: null; + }; + gcTimeout: number; + replicas: { + current: number; + requested: number; + }; + devMode: boolean; + domains: { + domain: string; + isCustom: boolean; + stage: string; + }[]; +}; +export declare const transformed_api_info: ApiInfo; +export declare const response_api_info: ApiInfo; +export declare const config_response: Config; +export declare const whoami_response: { + type: string; + id: string; + name: string; + fullname: string; + email: string; + emailVerified: boolean; + canPay: boolean; + periodEnd: number; + isPro: boolean; + avatarUrl: string; + orgs: never[]; + auth: { + type: string; + accessToken: { + displayName: string; + role: string; + }; + }; +}; +export declare const duplicate_response: { + url: string; +}; +export declare const hardware_sleeptime_response: { + stage: string; + hardware: { + current: string; + requested: string; + }; + storage: null; + gcTimeout: number; + replicas: { + current: number; + requested: number; + }; + devMode: boolean; + domains: { + domain: string; + isCustom: boolean; + stage: string; + }[]; +}; +export declare const endpoint_info: EndpointInfo; +export declare const discussions_response: { + discussions: never[]; + count: number; + start: number; + numClosedDiscussions: number; +}; +//# sourceMappingURL=test_data.d.ts.map \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/test/test_data.d.ts.map b/node_modules/@gradio/client/dist/test/test_data.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..b61d61155c4b680fd7a0ae7d4d567a0c58289d75 --- /dev/null +++ b/node_modules/@gradio/client/dist/test/test_data.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"test_data.d.ts","sourceRoot":"","sources":["../../src/test/test_data.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAElE,eAAO,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;;;;CAuB5B,CAAC;AAEF,eAAO,MAAM,oBAAoB,EAAE,OAAO,CAAC,OAAO,CA6CjD,CAAC;AAEF,eAAO,MAAM,iBAAiB,EAAE,OAAO,CAAC,OAAO,CAiC9C,CAAC;AAEF,eAAO,MAAM,eAAe,EAAE,MAkW7B,CAAC;AAEF,eAAO,MAAM,eAAe;;;;;;;;;;;;;;;;;;;CAmB3B,CAAC;AAEF,eAAO,MAAM,kBAAkB;;CAE9B,CAAC;AAEF,eAAO,MAAM,2BAA2B;;;;;;;;;;;;;;;;;;CAoBvC,CAAC;AAEF,eAAO,MAAM,aAAa,EAAE,YAAY,CAAC,OAAO,CA0C/C,CAAC;AAEF,eAAO,MAAM,oBAAoB;;;;;CAKhC,CAAC"} \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/types.d.ts b/node_modules/@gradio/client/dist/types.d.ts index d21788db9648a1fdb51a69ba5bb95e6f6bebb7a2..0d441fc4ac0e9accaef588646f6e2775dbc812d7 100644 --- a/node_modules/@gradio/client/dist/types.d.ts +++ b/node_modules/@gradio/client/dist/types.d.ts @@ -1,13 +1,117 @@ +/// +import { hardware_types } from "./helpers/spaces"; +import type { SvelteComponent } from "svelte"; +import type { ComponentType } from "svelte"; +export interface ApiData { + label: string; + parameter_name: string; + parameter_default?: any; + parameter_has_default?: boolean; + type: { + type: any; + description: string; + }; + component: string; + example_input?: any; + python_type: { + type: string; + description: string; + }; + serializer: string; +} +export interface JsApiData { + label: string; + parameter_name: string; + parameter_default?: any; + parameter_has_default?: boolean; + type: string; + description: string; + component: string; + example_input?: any; + serializer: string; + python_type: { + type: string; + description: string; + }; +} +export interface EndpointInfo { + parameters: T[]; + returns: T[]; + type?: DependencyTypes; +} +export interface ApiInfo { + named_endpoints: Record>; + unnamed_endpoints: Record>; +} +export interface BlobRef { + path: string[]; + type: string | undefined; + blob: Blob | File | false; +} +export type DataType = string | Buffer | Record | any[]; +export declare class Command { + type: string; + command: string; + meta: { + path: string; + name: string; + orig_path: string; + }; + fileData?: FileData; + constructor(command: string, meta: { + path: string; + name: string; + orig_path: string; + }); +} +export type SubmitFunction = (endpoint: string | number, data: unknown[] | Record, event_data?: unknown, trigger_id?: number | null) => SubmitIterable; +export type PredictFunction = (endpoint: string | number, data: unknown[] | Record, event_data?: unknown) => Promise; +export type client_return = { + config: Config | undefined; + predict: PredictFunction; + submit: SubmitFunction; + component_server: (component_id: number, fn_name: string, data: unknown[]) => any; + view_api: (_fetch: typeof fetch) => Promise>; +}; +export interface SubmitIterable extends AsyncIterable { + [Symbol.asyncIterator](): AsyncIterator; + cancel: () => Promise; +} +export type PredictReturn = { + type: EventType; + time: Date; + data: unknown; + endpoint: string; + fn_index: number; +}; +export type SpaceStatus = SpaceStatusNormal | SpaceStatusError; +export interface SpaceStatusNormal { + status: "sleeping" | "running" | "building" | "error" | "stopped"; + detail: "SLEEPING" | "RUNNING" | "RUNNING_BUILDING" | "BUILDING" | "NOT_FOUND"; + load_status: "pending" | "error" | "complete" | "generating"; + message: string; +} +export interface SpaceStatusError { + status: "space_error" | "paused"; + detail: "NO_APP_FILE" | "CONFIG_ERROR" | "BUILD_ERROR" | "RUNTIME_ERROR" | "PAUSED"; + load_status: "error"; + message: string; + discussions_enabled: boolean; +} +export type SpaceStatusCallback = (a: SpaceStatus) => void; export interface Config { - auth_required: boolean | undefined; + auth_required: boolean; + analytics_enabled: boolean; + connect_heartbeat: boolean; auth_message: string; - components: any[]; + components: ComponentMeta[]; css: string | null; js: string | null; head: string | null; - dependencies: any[]; + dependencies: Dependency[]; dev_mode: boolean; enable_queue: boolean; + show_error: boolean; layout: any; mode: "blocks" | "interface"; root: string; @@ -16,17 +120,89 @@ export interface Config { title: string; version: string; space_id: string | null; + is_space: boolean; is_colab: boolean; show_api: boolean; stylesheets: string[]; path: string; - protocol?: "sse_v1" | "sse" | "ws"; + protocol: "sse_v3" | "sse_v2.1" | "sse_v2" | "sse_v1" | "sse" | "ws"; + max_file_size?: number; + theme_hash?: number; +} +export interface ComponentMeta { + type: string; + id: number; + has_modes: boolean; + props: SharedProps; + instance: SvelteComponent; + component: ComponentType; + documentation?: Documentation; + children?: ComponentMeta[]; + parent?: ComponentMeta; + value?: any; + component_class_id: string; + key: string | number | null; + rendered_in?: number; +} +interface SharedProps { + elem_id?: string; + elem_classes?: string[]; + components?: string[]; + server_fns?: string[]; + interactive: boolean; + [key: string]: unknown; + root_url?: string; +} +export interface Documentation { + type?: TypeDescription; + description?: TypeDescription; + example_data?: string; +} +interface TypeDescription { + input_payload?: string; + response_object?: string; + payload?: string; +} +export interface Dependency { + id: number; + targets: [number, string][]; + inputs: number[]; + outputs: number[]; + backend_fn: boolean; + js: string | null; + scroll_to_output: boolean; + trigger: "click" | "load" | string; + max_batch_size: number; + show_progress: "full" | "minimal" | "hidden"; + frontend_fn: ((...args: unknown[]) => Promise) | null; + status?: string; + queue: boolean | null; + every: number | null; + batch: boolean; + api_name: string | null; + cancels: number[]; + types: DependencyTypes; + collects_event_data: boolean; + pending_request?: boolean; + trigger_after?: number; + trigger_only_on_success?: boolean; + trigger_mode: "once" | "multiple" | "always_last"; + final_event: Payload | null; + show_api: boolean; + zerogpu?: boolean; + rendered_in: number | null; +} +export interface DependencyTypes { + continuous: boolean; + generator: boolean; + cancel: boolean; } export interface Payload { + fn_index: number; data: unknown[]; - fn_index?: number; - event_data?: unknown; time?: Date; + event_data?: unknown; + trigger_id?: number | null; } export interface PostResponse { error?: string; @@ -36,6 +212,50 @@ export interface UploadResponse { error?: string; files?: string[]; } +export interface DuplicateOptions extends ClientOptions { + private?: boolean; + hardware?: (typeof hardware_types)[number]; + timeout?: number; +} +export interface ClientOptions { + hf_token?: `hf_${string}`; + status_callback?: SpaceStatusCallback | null; + auth?: [string, string] | null; + with_null_state?: boolean; + events?: EventType[]; +} +export interface FileData { + name: string; + orig_name?: string; + size?: number; + data: string; + blob?: File; + is_file?: boolean; + mime_type?: string; + alt_text?: string; +} +export type EventType = "data" | "status" | "log" | "render"; +export interface EventMap { + data: PayloadMessage; + status: StatusMessage; + log: LogMessage; + render: RenderMessage; +} +export type GradioEvent = { + [P in EventType]: EventMap[P]; +}[EventType]; +export interface Log { + log: string; + level: "warning" | "info"; +} +export interface Render { + data: { + components: any[]; + layout: any; + dependencies: Dependency[]; + render_id: number; + }; +} export interface Status { queue: boolean; code?: string; @@ -54,52 +274,27 @@ export interface Status { desc: string | null; }[]; time?: Date; + changed_state_ids?: number[]; } -export interface LogMessage { - log: string; - level: "warning" | "info"; -} -export interface SpaceStatusNormal { - status: "sleeping" | "running" | "building" | "error" | "stopped"; - detail: "SLEEPING" | "RUNNING" | "RUNNING_BUILDING" | "BUILDING" | "NOT_FOUND"; - load_status: "pending" | "error" | "complete" | "generating"; - message: string; +export interface StatusMessage extends Status { + type: "status"; + endpoint: string; + fn_index: number; } -export interface SpaceStatusError { - status: "space_error" | "paused"; - detail: "NO_APP_FILE" | "CONFIG_ERROR" | "BUILD_ERROR" | "RUNTIME_ERROR" | "PAUSED"; - load_status: "error"; - message: string; - discussions_enabled: boolean; +export interface PayloadMessage extends Payload { + type: "data"; + endpoint: string; + fn_index: number; } -export type SpaceStatus = SpaceStatusNormal | SpaceStatusError; -export type status_callback_function = (a: Status) => void; -export type SpaceStatusCallback = (a: SpaceStatus) => void; -export type EventType = "data" | "status" | "log"; -export interface EventMap { - data: Payload; - status: Status; - log: LogMessage; +export interface LogMessage extends Log { + type: "log"; + endpoint: string; + fn_index: number; } -export type Event = { - [P in K]: EventMap[P] & { - type: P; - endpoint: string; - fn_index: number; - }; -}[K]; -export type EventListener = (event: Event) => void; -export type ListenerMap = { - [P in K]?: EventListener[]; -}; -export interface FileData { - name: string; - orig_name?: string; - size?: number; - data: string; - blob?: File; - is_file?: boolean; - mime_type?: string; - alt_text?: string; +export interface RenderMessage extends Render { + type: "render"; + endpoint: string; + fn_index: number; } +export {}; //# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/types.d.ts.map b/node_modules/@gradio/client/dist/types.d.ts.map index aa3e5c67abce350a819f9778b4712588ce979427..3af060093be8bd61b7885088b76eb041c3082fff 100644 --- a/node_modules/@gradio/client/dist/types.d.ts.map +++ b/node_modules/@gradio/client/dist/types.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"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"} \ No newline at end of file +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"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"} \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/upload.d.ts b/node_modules/@gradio/client/dist/upload.d.ts index ae951c0c89d33d7b94898354f1d16bf965ba6781..b88fbaa343ab9426f9463358d0991b7d2a1242d7 100644 --- a/node_modules/@gradio/client/dist/upload.d.ts +++ b/node_modules/@gradio/client/dist/upload.d.ts @@ -1,10 +1,5 @@ -import { upload_files } from "./client"; -export declare function normalise_file(file: FileData | null, server_url: string, proxy_url: string | null): FileData | null; -export declare function normalise_file(file: FileData[] | null, server_url: string, proxy_url: string | null): FileData[] | null; -export declare function normalise_file(file: FileData[] | FileData | null, server_url: string, // root: string, -proxy_url: string | null): FileData[] | FileData | null; -export declare function get_fetchable_url_or_file(path: string | null, server_url: string, proxy_url: string | null): string; -export declare function upload(file_data: FileData[], root: string, upload_id?: string, upload_fn?: typeof upload_files): Promise<(FileData | null)[] | null>; +import type { Client } from "./client"; +export declare function upload(this: Client, file_data: FileData[], root_url: string, upload_id?: string, max_file_size?: number): Promise<(FileData | null)[] | null>; export declare function prepare_files(files: File[], is_stream?: boolean): Promise; export declare class FileData { path: string; @@ -15,6 +10,9 @@ export declare class FileData { is_stream?: boolean; mime_type?: string; alt_text?: string; + readonly meta: { + _type: string; + }; constructor({ path, url, orig_name, size, blob, is_stream, mime_type, alt_text }: { path: string; url?: string; diff --git a/node_modules/@gradio/client/dist/upload.d.ts.map b/node_modules/@gradio/client/dist/upload.d.ts.map index 171bcb37faac09e061b28a2666735eb8bcae6a4c..dd3eb79e34fa8f5b642c8ae2097353607f1efae6 100644 --- a/node_modules/@gradio/client/dist/upload.d.ts.map +++ b/node_modules/@gradio/client/dist/upload.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"upload.d.ts","sourceRoot":"","sources":["../src/upload.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAExC,wBAAgB,cAAc,CAC7B,IAAI,EAAE,QAAQ,GAAG,IAAI,EACrB,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,MAAM,GAAG,IAAI,GACtB,QAAQ,GAAG,IAAI,CAAC;AAEnB,wBAAgB,cAAc,CAC7B,IAAI,EAAE,QAAQ,EAAE,GAAG,IAAI,EACvB,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,MAAM,GAAG,IAAI,GACtB,QAAQ,EAAE,GAAG,IAAI,CAAC;AAErB,wBAAgB,cAAc,CAC7B,IAAI,EAAE,QAAQ,EAAE,GAAG,QAAQ,GAAG,IAAI,EAClC,UAAU,EAAE,MAAM,EAAE,gBAAgB;AACpC,SAAS,EAAE,MAAM,GAAG,IAAI,GACtB,QAAQ,EAAE,GAAG,QAAQ,GAAG,IAAI,CAAC;AAqDhC,wBAAgB,yBAAyB,CACxC,IAAI,EAAE,MAAM,GAAG,IAAI,EACnB,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,MAAM,GAAG,IAAI,GACtB,MAAM,CAUR;AAED,wBAAsB,MAAM,CAC3B,SAAS,EAAE,QAAQ,EAAE,EACrB,IAAI,EAAE,MAAM,EACZ,SAAS,CAAC,EAAE,MAAM,EAClB,SAAS,GAAE,OAAO,YAA2B,GAC3C,OAAO,CAAC,CAAC,QAAQ,GAAG,IAAI,CAAC,EAAE,GAAG,IAAI,CAAC,CAwBrC;AAED,wBAAsB,aAAa,CAClC,KAAK,EAAE,IAAI,EAAE,EACb,SAAS,CAAC,EAAE,OAAO,GACjB,OAAO,CAAC,QAAQ,EAAE,CAAC,CAYrB;AAED,qBAAa,QAAQ;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,IAAI,CAAC;IACZ,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;gBAEN,EACX,IAAI,EACJ,GAAG,EACH,SAAS,EACT,IAAI,EACJ,IAAI,EACJ,SAAS,EACT,SAAS,EACT,QAAQ,EACR,EAAE;QACF,IAAI,EAAE,MAAM,CAAC;QACb,GAAG,CAAC,EAAE,MAAM,CAAC;QACb,SAAS,CAAC,EAAE,MAAM,CAAC;QACnB,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,IAAI,CAAC,EAAE,IAAI,CAAC;QACZ,SAAS,CAAC,EAAE,OAAO,CAAC;QACpB,SAAS,CAAC,EAAE,MAAM,CAAC;QACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;KAClB;CAUD"} \ No newline at end of file +{"version":3,"file":"upload.d.ts","sourceRoot":"","sources":["../src/upload.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAEvC,wBAAsB,MAAM,CAC3B,IAAI,EAAE,MAAM,EACZ,SAAS,EAAE,QAAQ,EAAE,EACrB,QAAQ,EAAE,MAAM,EAChB,SAAS,CAAC,EAAE,MAAM,EAClB,aAAa,CAAC,EAAE,MAAM,GACpB,OAAO,CAAC,CAAC,QAAQ,GAAG,IAAI,CAAC,EAAE,GAAG,IAAI,CAAC,CAsCrC;AAED,wBAAsB,aAAa,CAClC,KAAK,EAAE,IAAI,EAAE,EACb,SAAS,CAAC,EAAE,OAAO,GACjB,OAAO,CAAC,QAAQ,EAAE,CAAC,CAYrB;AAED,qBAAa,QAAQ;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,IAAI,CAAC;IACZ,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,IAAI;;MAAgC;gBAEjC,EACX,IAAI,EACJ,GAAG,EACH,SAAS,EACT,IAAI,EACJ,IAAI,EACJ,SAAS,EACT,SAAS,EACT,QAAQ,EACR,EAAE;QACF,IAAI,EAAE,MAAM,CAAC;QACb,GAAG,CAAC,EAAE,MAAM,CAAC;QACb,SAAS,CAAC,EAAE,MAAM,CAAC;QACnB,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,IAAI,CAAC,EAAE,IAAI,CAAC;QACZ,SAAS,CAAC,EAAE,OAAO,CAAC;QACpB,SAAS,CAAC,EAAE,MAAM,CAAC;QACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;KAClB;CAUD"} \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/utils.d.ts.map b/node_modules/@gradio/client/dist/utils.d.ts.map deleted file mode 100644 index c8e6010f70f6421ccff8f6d56625c53e837c5a1c..0000000000000000000000000000000000000000 --- a/node_modules/@gradio/client/dist/utils.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AAEzC;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAC3B,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,MAAM,EACjB,eAAe,EAAE,OAAO,GACtB,MAAM,CAKR;AAED,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,GAAG;IACrD,WAAW,EAAE,IAAI,GAAG,KAAK,CAAC;IAC1B,aAAa,EAAE,OAAO,GAAG,QAAQ,CAAC;IAClC,IAAI,EAAE,MAAM,CAAC;CACb,CAgCA;AAED,eAAO,MAAM,aAAa,QAAqB,CAAC;AAChD,eAAO,MAAM,eAAe,QAAwB,CAAC;AACrD,wBAAsB,gBAAgB,CACrC,aAAa,EAAE,MAAM,EACrB,KAAK,CAAC,EAAE,MAAM,MAAM,EAAE,GACpB,OAAO,CAAC;IACV,QAAQ,EAAE,MAAM,GAAG,KAAK,CAAC;IACzB,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,IAAI,GAAG,KAAK,CAAC;IAC1B,aAAa,EAAE,OAAO,GAAG,QAAQ,CAAC;CAClC,CAAC,CA4CD;AAED,wBAAgB,gBAAgB,CAC/B,GAAG,EAAE,MAAM,CAAC,cAAc,CAAC,GACzB,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAQxB;AAID,wBAAsB,mBAAmB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAe5E;AAED,wBAAsB,kBAAkB,CACvC,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,MAAM,EAAE,GACnB,OAAO,CAAC,CAAC,OAAO,cAAc,CAAC,CAAC,MAAM,CAAC,CAAC,CAqB1C;AAED,wBAAsB,kBAAkB,CACvC,QAAQ,EAAE,MAAM,EAChB,YAAY,EAAE,CAAC,OAAO,cAAc,CAAC,CAAC,MAAM,CAAC,EAC7C,KAAK,EAAE,MAAM,MAAM,EAAE,GACnB,OAAO,CAAC,CAAC,OAAO,cAAc,CAAC,CAAC,MAAM,CAAC,CAAC,CAuB1C;AAED,wBAAsB,iBAAiB,CACtC,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,MAAM,MAAM,EAAE,GACnB,OAAO,CAAC,MAAM,CAAC,CAuBjB;AAED,eAAO,MAAM,cAAc,0GAQjB,CAAC"} \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/utils/duplicate.d.ts b/node_modules/@gradio/client/dist/utils/duplicate.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2db4e1f6aed77c8ef0ac705cf467fd8d0c3a1083 --- /dev/null +++ b/node_modules/@gradio/client/dist/utils/duplicate.d.ts @@ -0,0 +1,4 @@ +import type { DuplicateOptions } from "../types"; +import { Client } from "../client"; +export declare function duplicate(app_reference: string, options: DuplicateOptions): Promise; +//# sourceMappingURL=duplicate.d.ts.map \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/utils/duplicate.d.ts.map b/node_modules/@gradio/client/dist/utils/duplicate.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..d13451ab2c1d2b1adddcb79165b1d936e3e384d6 --- /dev/null +++ b/node_modules/@gradio/client/dist/utils/duplicate.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"duplicate.d.ts","sourceRoot":"","sources":["../../src/utils/duplicate.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAQnC,wBAAsB,SAAS,CAC9B,aAAa,EAAE,MAAM,EACrB,OAAO,EAAE,gBAAgB,GACvB,OAAO,CAAC,MAAM,CAAC,CAuGjB"} \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/utils/handle_blob.d.ts b/node_modules/@gradio/client/dist/utils/handle_blob.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..42fb43d0da8c8506c52ec47bd0196163f7f359a9 --- /dev/null +++ b/node_modules/@gradio/client/dist/utils/handle_blob.d.ts @@ -0,0 +1,5 @@ +import { type ApiData, type EndpointInfo, type JsApiData } from "../types"; +import type { Client } from ".."; +export declare function handle_blob(this: Client, endpoint: string, data: unknown[], api_info: EndpointInfo): Promise; +export declare function process_local_file_commands(client: Client, data: unknown[]): Promise; +//# sourceMappingURL=handle_blob.d.ts.map \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/utils/handle_blob.d.ts.map b/node_modules/@gradio/client/dist/utils/handle_blob.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..9336156c7c8d83efd7b623ba7b981b2e5f0fef6a --- /dev/null +++ b/node_modules/@gradio/client/dist/utils/handle_blob.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"handle_blob.d.ts","sourceRoot":"","sources":["../../src/utils/handle_blob.ts"],"names":[],"mappings":"AACA,OAAO,EAEN,KAAK,OAAO,EACZ,KAAK,YAAY,EACjB,KAAK,SAAS,EACd,MAAM,UAAU,CAAC;AAElB,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,IAAI,CAAC;AAOjC,wBAAsB,WAAW,CAChC,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,OAAO,EAAE,EACf,QAAQ,EAAE,YAAY,CAAC,SAAS,GAAG,OAAO,CAAC,GACzC,OAAO,CAAC,OAAO,EAAE,CAAC,CAsCpB;AAED,wBAAsB,2BAA2B,CAChD,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,OAAO,EAAE,GACb,OAAO,CAAC,IAAI,CAAC,CAQf"} \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/utils/post_data.d.ts b/node_modules/@gradio/client/dist/utils/post_data.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b08b61ae99d1c05d29b14f7413bc36358379e271 --- /dev/null +++ b/node_modules/@gradio/client/dist/utils/post_data.d.ts @@ -0,0 +1,4 @@ +import type { PostResponse } from "../types"; +import { Client } from ".."; +export declare function post_data(this: Client, url: string, body: unknown, additional_headers?: any): Promise<[PostResponse, number]>; +//# sourceMappingURL=post_data.d.ts.map \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/utils/post_data.d.ts.map b/node_modules/@gradio/client/dist/utils/post_data.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..1803a88c5bbdaeb717922e5e1d82d7b4d623a0c5 --- /dev/null +++ b/node_modules/@gradio/client/dist/utils/post_data.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"post_data.d.ts","sourceRoot":"","sources":["../../src/utils/post_data.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAC7C,OAAO,EAAE,MAAM,EAAE,MAAM,IAAI,CAAC;AAE5B,wBAAsB,SAAS,CAC9B,IAAI,EAAE,MAAM,EACZ,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,OAAO,EACb,kBAAkB,CAAC,EAAE,GAAG,GACtB,OAAO,CAAC,CAAC,YAAY,EAAE,MAAM,CAAC,CAAC,CA4BjC"} \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/utils/predict.d.ts b/node_modules/@gradio/client/dist/utils/predict.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..69ea43c6d7cce55ba438ba203d2062c37143cadf --- /dev/null +++ b/node_modules/@gradio/client/dist/utils/predict.d.ts @@ -0,0 +1,4 @@ +import { Client } from "../client"; +import type { PredictReturn } from "../types"; +export declare function predict(this: Client, endpoint: string | number, data: unknown[] | Record): Promise; +//# sourceMappingURL=predict.d.ts.map \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/utils/predict.d.ts.map b/node_modules/@gradio/client/dist/utils/predict.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..e84337f2a219ab4a4534334f1733849d9c91a727 --- /dev/null +++ b/node_modules/@gradio/client/dist/utils/predict.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"predict.d.ts","sourceRoot":"","sources":["../../src/utils/predict.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACnC,OAAO,KAAK,EAAc,aAAa,EAAE,MAAM,UAAU,CAAC;AAE1D,wBAAsB,OAAO,CAC5B,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,MAAM,GAAG,MAAM,EACzB,IAAI,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GACvC,OAAO,CAAC,aAAa,CAAC,CAiDxB"} \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/utils/stream.d.ts b/node_modules/@gradio/client/dist/utils/stream.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..de5337bc3cba1b86bb38f2d0be720bd68b150d9d --- /dev/null +++ b/node_modules/@gradio/client/dist/utils/stream.d.ts @@ -0,0 +1,9 @@ +import type { Client } from "../client"; +export declare function open_stream(this: Client): Promise; +export declare function close_stream(stream_status: { + open: boolean; +}, abort_controller: AbortController | null): void; +export declare function apply_diff_stream(pending_diff_streams: Record, event_id: string, data: any): void; +export declare function apply_diff(obj: any, diff: [string, (number | string)[], any][]): any; +export declare function readable_stream(input: RequestInfo | URL, init?: RequestInit): EventSource; +//# sourceMappingURL=stream.d.ts.map \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/utils/stream.d.ts.map b/node_modules/@gradio/client/dist/utils/stream.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..2b4217b1d8efc3f614e1d95749ad9ec19ba89f80 --- /dev/null +++ b/node_modules/@gradio/client/dist/utils/stream.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"stream.d.ts","sourceRoot":"","sources":["../../src/utils/stream.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAGxC,wBAAsB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAmF7D;AAED,wBAAgB,YAAY,CAC3B,aAAa,EAAE;IAAE,IAAI,EAAE,OAAO,CAAA;CAAE,EAChC,gBAAgB,EAAE,eAAe,GAAG,IAAI,GACtC,IAAI,CAKN;AAED,wBAAgB,iBAAiB,CAChC,oBAAoB,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,EAAE,EAAE,CAAC,EAC7C,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,GAAG,GACP,IAAI,CAcN;AAED,wBAAgB,UAAU,CACzB,GAAG,EAAE,GAAG,EACR,IAAI,EAAE,CAAC,MAAM,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,EAAE,GAAG,CAAC,EAAE,GACxC,GAAG,CAML;AAkDD,wBAAgB,eAAe,CAC9B,KAAK,EAAE,WAAW,GAAG,GAAG,EACxB,IAAI,GAAE,WAAgB,GACpB,WAAW,CA8Cb"} \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/utils/submit.d.ts b/node_modules/@gradio/client/dist/utils/submit.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cd3a611dffdbbc4acf42c65dfe75129690edce15 --- /dev/null +++ b/node_modules/@gradio/client/dist/utils/submit.d.ts @@ -0,0 +1,4 @@ +import type { GradioEvent, SubmitIterable } from "../types"; +import { Client } from "../client"; +export declare function submit(this: Client, endpoint: string | number, data: unknown[] | Record, event_data?: unknown, trigger_id?: number | null, all_events?: boolean): SubmitIterable; +//# sourceMappingURL=submit.d.ts.map \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/utils/submit.d.ts.map b/node_modules/@gradio/client/dist/utils/submit.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..cd661695b9077268483d7ebd3b4fdc131b909a25 --- /dev/null +++ b/node_modules/@gradio/client/dist/utils/submit.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"submit.d.ts","sourceRoot":"","sources":["../../src/utils/submit.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAGX,WAAW,EAMX,cAAc,EACd,MAAM,UAAU,CAAC;AAYlB,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAEnC,wBAAgB,MAAM,CACrB,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,MAAM,GAAG,MAAM,EACzB,IAAI,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACzC,UAAU,CAAC,EAAE,OAAO,EACpB,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,EAC1B,UAAU,CAAC,EAAE,OAAO,GAClB,cAAc,CAAC,WAAW,CAAC,CAwvB7B"} \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/utils/upload_files.d.ts b/node_modules/@gradio/client/dist/utils/upload_files.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9696aae9fd3e8cd1d7e4eb0fe2927430d37a692f --- /dev/null +++ b/node_modules/@gradio/client/dist/utils/upload_files.d.ts @@ -0,0 +1,4 @@ +import type { Client } from ".."; +import type { UploadResponse } from "../types"; +export declare function upload_files(this: Client, root_url: string, files: (Blob | File)[], upload_id?: string): Promise; +//# sourceMappingURL=upload_files.d.ts.map \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/utils/upload_files.d.ts.map b/node_modules/@gradio/client/dist/utils/upload_files.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..a73856c66c15eb074dba1d2b737104dcd40aae62 --- /dev/null +++ b/node_modules/@gradio/client/dist/utils/upload_files.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"upload_files.d.ts","sourceRoot":"","sources":["../../src/utils/upload_files.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,IAAI,CAAC;AAEjC,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAE/C,wBAAsB,YAAY,CACjC,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,CAAC,IAAI,GAAG,IAAI,CAAC,EAAE,EACtB,SAAS,CAAC,EAAE,MAAM,GAChB,OAAO,CAAC,cAAc,CAAC,CA0CzB"} \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/utils/view_api.d.ts b/node_modules/@gradio/client/dist/utils/view_api.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0110c2bf57fa9f618868c490c5df71d8e2906ee7 --- /dev/null +++ b/node_modules/@gradio/client/dist/utils/view_api.d.ts @@ -0,0 +1,3 @@ +import { Client } from "../client"; +export declare function view_api(this: Client): Promise; +//# sourceMappingURL=view_api.d.ts.map \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/utils/view_api.d.ts.map b/node_modules/@gradio/client/dist/utils/view_api.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..4c6145fb7502dfead21011d46cc69ed5f53a839b --- /dev/null +++ b/node_modules/@gradio/client/dist/utils/view_api.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"view_api.d.ts","sourceRoot":"","sources":["../../src/utils/view_api.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAInC,wBAAsB,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,CA8DzD"} \ No newline at end of file diff --git a/node_modules/@gradio/client/dist/wrapper-6f348d45.js b/node_modules/@gradio/client/dist/wrapper-CviSselG.js similarity index 92% rename from node_modules/@gradio/client/dist/wrapper-6f348d45.js rename to node_modules/@gradio/client/dist/wrapper-CviSselG.js index 4c7627d28002f2a8a6aee066f8025c118298437e..f8f357ba505fbfd749fa757bd944f3d02b654031 100644 --- a/node_modules/@gradio/client/dist/wrapper-6f348d45.js +++ b/node_modules/@gradio/client/dist/wrapper-CviSselG.js @@ -1,12 +1,15 @@ import require$$0 from "stream"; -import require$$0$1 from "zlib"; -import require$$0$2 from "buffer"; +import require$$0$2 from "zlib"; +import require$$0$1 from "fs"; +import require$$1$1 from "path"; +import require$$2 from "os"; +import require$$0$3 from "buffer"; import require$$3 from "net"; import require$$4 from "tls"; import require$$5 from "crypto"; -import require$$0$3 from "events"; -import require$$1$1 from "https"; -import require$$2 from "http"; +import require$$0$4 from "events"; +import require$$1$2 from "https"; +import require$$2$1 from "http"; import require$$7 from "url"; function getDefaultExportFromCjs(x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x; @@ -18,10 +21,7 @@ function getAugmentedNamespace(n) { if (typeof f == "function") { var a = function a2() { if (this instanceof a2) { - var args = [null]; - args.push.apply(args, arguments); - var Ctor = Function.bind.apply(f, args); - return new Ctor(); + return Reflect.construct(f, arguments, this.constructor); } return f.apply(this, arguments); }; @@ -151,6 +151,248 @@ var constants = { NOOP: () => { } }; +var bufferutil = { exports: {} }; +var nodeGypBuild$1 = { exports: {} }; +function commonjsRequire(path) { + throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.'); +} +var nodeGypBuild; +var hasRequiredNodeGypBuild$1; +function requireNodeGypBuild$1() { + if (hasRequiredNodeGypBuild$1) + return nodeGypBuild; + hasRequiredNodeGypBuild$1 = 1; + var fs = require$$0$1; + var path = require$$1$1; + var os = require$$2; + var runtimeRequire = typeof __webpack_require__ === "function" ? __non_webpack_require__ : commonjsRequire; + var vars = process.config && process.config.variables || {}; + var prebuildsOnly = !!process.env.PREBUILDS_ONLY; + var abi = process.versions.modules; + var runtime = isElectron() ? "electron" : isNwjs() ? "node-webkit" : "node"; + var arch = process.env.npm_config_arch || os.arch(); + var platform = process.env.npm_config_platform || os.platform(); + var libc = process.env.LIBC || (isAlpine(platform) ? "musl" : "glibc"); + var armv = process.env.ARM_VERSION || (arch === "arm64" ? "8" : vars.arm_version) || ""; + var uv = (process.versions.uv || "").split(".")[0]; + nodeGypBuild = load; + function load(dir) { + return runtimeRequire(load.resolve(dir)); + } + load.resolve = load.path = function(dir) { + dir = path.resolve(dir || "."); + try { + var name = runtimeRequire(path.join(dir, "package.json")).name.toUpperCase().replace(/-/g, "_"); + if (process.env[name + "_PREBUILD"]) + dir = process.env[name + "_PREBUILD"]; + } catch (err) { + } + if (!prebuildsOnly) { + var release = getFirst(path.join(dir, "build/Release"), matchBuild); + if (release) + return release; + var debug = getFirst(path.join(dir, "build/Debug"), matchBuild); + if (debug) + return debug; + } + var prebuild = resolve(dir); + if (prebuild) + return prebuild; + var nearby = resolve(path.dirname(process.execPath)); + if (nearby) + return nearby; + var target = [ + "platform=" + platform, + "arch=" + arch, + "runtime=" + runtime, + "abi=" + abi, + "uv=" + uv, + armv ? "armv=" + armv : "", + "libc=" + libc, + "node=" + process.versions.node, + process.versions.electron ? "electron=" + process.versions.electron : "", + typeof __webpack_require__ === "function" ? "webpack=true" : "" + // eslint-disable-line + ].filter(Boolean).join(" "); + throw new Error("No native build was found for " + target + "\n loaded from: " + dir + "\n"); + function resolve(dir2) { + var tuples = readdirSync(path.join(dir2, "prebuilds")).map(parseTuple); + var tuple = tuples.filter(matchTuple(platform, arch)).sort(compareTuples)[0]; + if (!tuple) + return; + var prebuilds = path.join(dir2, "prebuilds", tuple.name); + var parsed = readdirSync(prebuilds).map(parseTags); + var candidates = parsed.filter(matchTags(runtime, abi)); + var winner = candidates.sort(compareTags(runtime))[0]; + if (winner) + return path.join(prebuilds, winner.file); + } + }; + function readdirSync(dir) { + try { + return fs.readdirSync(dir); + } catch (err) { + return []; + } + } + function getFirst(dir, filter) { + var files = readdirSync(dir).filter(filter); + return files[0] && path.join(dir, files[0]); + } + function matchBuild(name) { + return /\.node$/.test(name); + } + function parseTuple(name) { + var arr = name.split("-"); + if (arr.length !== 2) + return; + var platform2 = arr[0]; + var architectures = arr[1].split("+"); + if (!platform2) + return; + if (!architectures.length) + return; + if (!architectures.every(Boolean)) + return; + return { name, platform: platform2, architectures }; + } + function matchTuple(platform2, arch2) { + return function(tuple) { + if (tuple == null) + return false; + if (tuple.platform !== platform2) + return false; + return tuple.architectures.includes(arch2); + }; + } + function compareTuples(a, b) { + return a.architectures.length - b.architectures.length; + } + function parseTags(file) { + var arr = file.split("."); + var extension2 = arr.pop(); + var tags = { file, specificity: 0 }; + if (extension2 !== "node") + return; + for (var i = 0; i < arr.length; i++) { + var tag = arr[i]; + if (tag === "node" || tag === "electron" || tag === "node-webkit") { + tags.runtime = tag; + } else if (tag === "napi") { + tags.napi = true; + } else if (tag.slice(0, 3) === "abi") { + tags.abi = tag.slice(3); + } else if (tag.slice(0, 2) === "uv") { + tags.uv = tag.slice(2); + } else if (tag.slice(0, 4) === "armv") { + tags.armv = tag.slice(4); + } else if (tag === "glibc" || tag === "musl") { + tags.libc = tag; + } else { + continue; + } + tags.specificity++; + } + return tags; + } + function matchTags(runtime2, abi2) { + return function(tags) { + if (tags == null) + return false; + if (tags.runtime !== runtime2 && !runtimeAgnostic(tags)) + return false; + if (tags.abi !== abi2 && !tags.napi) + return false; + if (tags.uv && tags.uv !== uv) + return false; + if (tags.armv && tags.armv !== armv) + return false; + if (tags.libc && tags.libc !== libc) + return false; + return true; + }; + } + function runtimeAgnostic(tags) { + return tags.runtime === "node" && tags.napi; + } + function compareTags(runtime2) { + return function(a, b) { + if (a.runtime !== b.runtime) { + return a.runtime === runtime2 ? -1 : 1; + } else if (a.abi !== b.abi) { + return a.abi ? -1 : 1; + } else if (a.specificity !== b.specificity) { + return a.specificity > b.specificity ? -1 : 1; + } else { + return 0; + } + }; + } + function isNwjs() { + return !!(process.versions && process.versions.nw); + } + function isElectron() { + if (process.versions && process.versions.electron) + return true; + if (process.env.ELECTRON_RUN_AS_NODE) + return true; + return typeof window !== "undefined" && window.process && window.process.type === "renderer"; + } + function isAlpine(platform2) { + return platform2 === "linux" && fs.existsSync("/etc/alpine-release"); + } + load.parseTags = parseTags; + load.matchTags = matchTags; + load.compareTags = compareTags; + load.parseTuple = parseTuple; + load.matchTuple = matchTuple; + load.compareTuples = compareTuples; + return nodeGypBuild; +} +var hasRequiredNodeGypBuild; +function requireNodeGypBuild() { + if (hasRequiredNodeGypBuild) + return nodeGypBuild$1.exports; + hasRequiredNodeGypBuild = 1; + if (typeof process.addon === "function") { + nodeGypBuild$1.exports = process.addon.bind(process); + } else { + nodeGypBuild$1.exports = requireNodeGypBuild$1(); + } + return nodeGypBuild$1.exports; +} +var fallback; +var hasRequiredFallback; +function requireFallback() { + if (hasRequiredFallback) + return fallback; + hasRequiredFallback = 1; + const mask2 = (source, mask3, output, offset, length) => { + for (var i = 0; i < length; i++) { + output[offset + i] = source[i] ^ mask3[i & 3]; + } + }; + const unmask2 = (buffer, mask3) => { + const length = buffer.length; + for (var i = 0; i < length; i++) { + buffer[i] ^= mask3[i & 3]; + } + }; + fallback = { mask: mask2, unmask: unmask2 }; + return fallback; +} +var hasRequiredBufferutil; +function requireBufferutil() { + if (hasRequiredBufferutil) + return bufferutil.exports; + hasRequiredBufferutil = 1; + try { + bufferutil.exports = requireNodeGypBuild()(__dirname); + } catch (e) { + bufferutil.exports = requireFallback(); + } + return bufferutil.exports; +} var unmask$1; var mask; const { EMPTY_BUFFER: EMPTY_BUFFER$3 } = constants; @@ -212,7 +454,7 @@ bufferUtil$1.exports = { }; if (!process.env.WS_NO_BUFFER_UTIL) { try { - const bufferUtil2 = require("bufferutil"); + const bufferUtil2 = requireBufferutil(); mask = bufferUtil$1.exports.mask = function(source, mask2, output, offset, length) { if (length < 48) _mask(source, mask2, output, offset, length); @@ -273,7 +515,7 @@ let Limiter$1 = class Limiter { } }; var limiter = Limiter$1; -const zlib = require$$0$1; +const zlib = require$$0$2; const bufferUtil = bufferUtilExports; const Limiter2 = limiter; const { kStatusCode: kStatusCode$2 } = constants; @@ -654,7 +896,7 @@ const __viteOptionalPeerDep_utf8Validate_ws$1 = /* @__PURE__ */ Object.freeze(/* }, Symbol.toStringTag, { value: "Module" })); const require$$1 = /* @__PURE__ */ getAugmentedNamespace(__viteOptionalPeerDep_utf8Validate_ws$1); var isValidUTF8_1; -const { isUtf8 } = require$$0$2; +const { isUtf8 } = require$$0$3; const tokenChars$2 = [ 0, 0, @@ -2159,9 +2401,9 @@ function format$1(extensions) { }).join(", "); } var extension$1 = { format: format$1, parse: parse$2 }; -const EventEmitter$1 = require$$0$3; -const https = require$$1$1; -const http$1 = require$$2; +const EventEmitter$1 = require$$0$4; +const https = require$$1$2; +const http$1 = require$$2$1; const net = require$$3; const tls = require$$4; const { randomBytes, createHash: createHash$1 } = require$$5; @@ -3065,8 +3307,8 @@ function parse(header) { return protocols; } var subprotocol$1 = { parse }; -const EventEmitter = require$$0$3; -const http = require$$2; +const EventEmitter = require$$0$4; +const http = require$$2$1; const { createHash } = require$$5; const extension = extension$1; const PerMessageDeflate2 = permessageDeflate; diff --git a/node_modules/@gradio/client/index.html b/node_modules/@gradio/client/index.html new file mode 100644 index 0000000000000000000000000000000000000000..1afd437873ac0e0ad160a577a5fb325dcb07142b --- /dev/null +++ b/node_modules/@gradio/client/index.html @@ -0,0 +1,39 @@ + + + + + + + Client + + + +
+ + diff --git a/node_modules/@gradio/client/package.json b/node_modules/@gradio/client/package.json index fba80007e51d742c76c3489c837570591b027e15..024af1390848353e1e6a542b86ada70fffb42f25 100644 --- a/node_modules/@gradio/client/package.json +++ b/node_modules/@gradio/client/package.json @@ -1,33 +1,86 @@ { - "name": "@gradio/client", - "version": "0.10.1", - "description": "Gradio API client", - "type": "module", - "main": "dist/index.js", - "author": "", - "license": "ISC", - "exports": { - ".": { - "import": "./dist/index.js" - }, - "./package.json": "./package.json" + "_from": "@gradio/client", + "_id": "@gradio/client@1.1.1", + "_inBundle": false, + "_integrity": "sha512-6Hzc+/wmNRkodefp0bvfOBQbEakwg31Ye9IVOjfoHkvunHoIzjupM+1m7VwhQXt8pMCjOw8Hc7zhvwnwy6f5GQ==", + "_location": "/@gradio/client", + "_phantomChildren": {}, + "_requested": { + "type": "tag", + "registry": true, + "raw": "@gradio/client", + "name": "@gradio/client", + "escapedName": "@gradio%2fclient", + "scope": "@gradio", + "rawSpec": "", + "saveSpec": null, + "fetchSpec": "latest" }, + "_requiredBy": [ + "#USER", + "/" + ], + "_resolved": "https://registry.npmjs.org/@gradio/client/-/client-1.1.1.tgz", + "_shasum": "4cd2b0769d0ef1d6b5cda8cf6d3209ed0e4364ec", + "_spec": "@gradio/client", + "_where": "/Users/sylvainfiloni/Documents/HuggingFace_Projects/live-vision", + "author": "", + "bundleDependencies": false, "dependencies": { + "@types/eventsource": "^1.1.15", "bufferutil": "^4.0.7", + "eventsource": "^2.0.2", + "fetch-event-stream": "^0.1.5", + "msw": "^2.2.1", "semiver": "^1.1.0", + "textlinestream": "^1.1.1", + "typescript": "^5.0.0", "ws": "^8.13.0" }, + "deprecated": false, + "description": "Gradio API client", "devDependencies": { - "@types/ws": "^8.5.4", - "esbuild": "^0.19.0" + "@types/ws": "^8.5.10", + "esbuild": "^0.21.0" }, "engines": { "node": ">=18.0.0" }, + "exports": { + ".": { + "import": "./dist/index.js" + }, + "./package.json": "./package.json" + }, + "license": "ISC", + "main": "dist/index.js", "main_changeset": true, + "name": "@gradio/client", "scripts": { + "build": "pnpm bundle && pnpm generate_types", "bundle": "vite build --ssr", "generate_types": "tsc", - "build": "pnpm bundle && pnpm generate_types" - } -} \ No newline at end of file + "preview:browser": "vite dev --mode=preview", + "test": "pnpm test:client && pnpm test:client:node", + "test:client": "vitest run -c vite.config.js", + "test:client:node": "TEST_MODE=node vitest run -c vite.config.js" + }, + "type": "module", + "version": "1.1.1", + "warnings": [ + { + "code": "ENOTSUP", + "required": { + "node": ">=18.0.0" + }, + "pkgid": "@gradio/client@1.1.1" + }, + { + "code": "ENOTSUP", + "required": { + "node": ">=18.0.0" + }, + "pkgid": "@gradio/client@1.1.1" + } + ] +} diff --git a/node_modules/@gradio/client/src/client.node-test.ts b/node_modules/@gradio/client/src/client.node-test.ts deleted file mode 100644 index 9964583b4558d55a62b0fbf78a440e572e5a204f..0000000000000000000000000000000000000000 --- a/node_modules/@gradio/client/src/client.node-test.ts +++ /dev/null @@ -1,172 +0,0 @@ -import { test, describe, assert } from "vitest"; -import { readFileSync } from "fs"; -import { join, dirname } from "path"; -import { fileURLToPath } from "url"; -import { Blob } from "node:buffer"; - -const __dirname = dirname(fileURLToPath(import.meta.url)); -const image_path = join( - __dirname, - "..", - "..", - "..", - "demo", - "kitchen_sink", - "files", - "lion.jpg" -); - -import { walk_and_store_blobs, client, handle_blob } from "./client"; - -describe.skip("extract blob parts", () => { - test("convert Buffer to Blob", async () => { - const image = readFileSync(image_path); - await client("gradio/hello_world_main"); - const parts = walk_and_store_blobs({ - data: { - image - } - }); - - assert.isTrue(parts[0].blob instanceof Blob); - }); - - test("leave node Blob as Blob", async () => { - const image = new Blob([readFileSync(image_path)]); - - await client("gradio/hello_world_main"); - const parts = walk_and_store_blobs({ - data: { - image - } - }); - - assert.isTrue(parts[0].blob instanceof Blob); - }); - - test("handle deep structures", async () => { - const image = new Blob([readFileSync(image_path)]); - - await client("gradio/hello_world_main"); - const parts = walk_and_store_blobs({ - a: { - b: { - data: { - image - } - } - } - }); - - assert.isTrue(parts[0].blob instanceof Blob); - }); - - test("handle deep structures with arrays", async () => { - const image = new Blob([readFileSync(image_path)]); - - await client("gradio/hello_world_main"); - const parts = walk_and_store_blobs({ - a: [ - { - b: [ - { - data: [ - { - image - } - ] - } - ] - } - ] - }); - - assert.isTrue(parts[0].blob instanceof Blob); - }); - - test("handle deep structures with arrays 2", async () => { - const image = new Blob([readFileSync(image_path)]); - - await client("gradio/hello_world_main"); - const obj = { - a: [ - { - b: [ - { - data: [[image], image, [image, [image]]] - } - ] - } - ] - }; - const parts = walk_and_store_blobs(obj); - - function map_path( - obj: Record, - parts: { path: string[]; blob: any }[] - ) { - const { path, blob } = parts[parts.length - 1]; - let ref = obj; - path.forEach((p) => (ref = ref[p])); - - return ref === blob; - } - - assert.isTrue(parts[0].blob instanceof Blob); - // assert.isTrue(map_path(obj, parts)); - }); -}); - -describe("handle_blob", () => { - test("handle blobs", async () => { - const image = new Blob([readFileSync(image_path)]); - - const app = await client("gradio/hello_world_main"); - const obj = [ - { - a: [ - { - b: [ - { - data: [[image], image, [image, [image]]] - } - ] - } - ] - } - ]; - - const parts = await handle_blob(app.config.root, obj, undefined); - //@ts-ignore - // assert.isString(parts.data[0].a[0].b[0].data[0][0]); - }); -}); - -describe.skip("private space", () => { - test("can access a private space", async () => { - const image = new Blob([readFileSync(image_path)]); - - const app = await client("pngwn/hello_world", { - hf_token: "hf_" - }); - - console.log(app); - const obj = [ - { - a: [ - { - b: [ - { - data: [[image], image, [image, [image]]] - } - ] - } - ] - } - ]; - - const parts = await handle_blob(app.config.root, obj, "hf_"); - //@ts-ignore - assert.isString(parts.data[0].a[0].b[0].data[0][0]); - }); -}); diff --git a/node_modules/@gradio/client/src/client.ts b/node_modules/@gradio/client/src/client.ts index 6355d5a04cadee5dcb057a73eefd2b7e0eeabbf5..0d694fd7bdc09b7fc25ebb082485566b710d6510 100644 --- a/node_modules/@gradio/client/src/client.ts +++ b/node_modules/@gradio/client/src/client.ts @@ -1,1727 +1,440 @@ -//@ts-nocheck - -import semiver from "semiver"; - -import { - process_endpoint, - RE_SPACE_NAME, - map_names_to_ids, - discussions_enabled, - get_space_hardware, - set_space_hardware, - set_space_timeout, - hardware_types, - resolve_root -} from "./utils.js"; - import type { - EventType, - EventListener, - ListenerMap, - Event, - Payload, - PostResponse, - UploadResponse, - Status, + ApiData, + ApiInfo, + ClientOptions, + Config, + DuplicateOptions, + EndpointInfo, + JsApiData, + PredictReturn, SpaceStatus, - SpaceStatusCallback -} from "./types.js"; - -import { FileData, normalise_file } from "./upload"; - -import type { Config } from "./types.js"; - -type event = ( - eventType: K, - listener: EventListener -) => SubmitReturn; -type predict = ( - endpoint: string | number, - data?: unknown[], - event_data?: unknown -) => Promise; - -type client_return = { - predict: predict; - config: Config; - submit: ( - endpoint: string | number, - data?: unknown[], - event_data?: unknown, - trigger_id?: number | null - ) => SubmitReturn; - component_server: ( - component_id: number, - fn_name: string, - data: unknown[] - ) => any; - view_api: (c?: Config) => Promise>; -}; - -type SubmitReturn = { - on: event; - off: event; - cancel: () => Promise; - destroy: () => void; -}; - -const QUEUE_FULL_MSG = "This application is too busy. Keep trying!"; -const BROKEN_CONNECTION_MSG = "Connection errored out."; - -export let NodeBlob; - -export async function duplicate( - app_reference: string, - options: { - hf_token: `hf_${string}`; - private?: boolean; - status_callback: SpaceStatusCallback; - hardware?: (typeof hardware_types)[number]; - timeout?: number; - } -): Promise { - const { hf_token, private: _private, hardware, timeout } = options; - - if (hardware && !hardware_types.includes(hardware)) { - throw new Error( - `Invalid hardware type provided. Valid types are: ${hardware_types - .map((v) => `"${v}"`) - .join(",")}.` - ); - } - const headers = { - Authorization: `Bearer ${hf_token}` - }; - - const user = ( - await ( - await fetch(`https://huggingface.co/api/whoami-v2`, { - headers - }) - ).json() - ).name; - - const space_name = app_reference.split("/")[1]; - const body: { - repository: string; - private?: boolean; - } = { - repository: `${user}/${space_name}` - }; - - if (_private) { - body.private = true; - } - - try { - const response = await fetch( - `https://huggingface.co/api/spaces/${app_reference}/duplicate`, - { - method: "POST", - headers: { "Content-Type": "application/json", ...headers }, - body: JSON.stringify(body) - } - ); - - if (response.status === 409) { - return client(`${user}/${space_name}`, options); + Status, + UploadResponse, + client_return, + SubmitIterable, + GradioEvent +} from "./types"; +import { view_api } from "./utils/view_api"; +import { upload_files } from "./utils/upload_files"; +import { upload, FileData } from "./upload"; +import { handle_blob } from "./utils/handle_blob"; +import { post_data } from "./utils/post_data"; +import { predict } from "./utils/predict"; +import { duplicate } from "./utils/duplicate"; +import { submit } from "./utils/submit"; +import { RE_SPACE_NAME, process_endpoint } from "./helpers/api_info"; +import { + map_names_to_ids, + resolve_cookies, + resolve_config, + get_jwt, + parse_and_set_cookies +} from "./helpers/init_helpers"; +import { check_space_status } from "./helpers/spaces"; +import { open_stream, readable_stream } from "./utils/stream"; +import { API_INFO_ERROR_MSG, CONFIG_ERROR_MSG } from "./constants"; + +export class Client { + app_reference: string; + options: ClientOptions; + + config: Config | undefined; + api_info: ApiInfo | undefined; + api_map: Record = {}; + session_hash: string = Math.random().toString(36).substring(2); + jwt: string | false = false; + last_status: Record = {}; + + private cookies: string | null = null; + + // streaming + stream_status = { open: false }; + pending_stream_messages: Record = {}; + pending_diff_streams: Record = {}; + event_callbacks: Record Promise> = {}; + unclosed_events: Set = new Set(); + heartbeat_event: EventSource | null = null; + abort_controller: AbortController | null = null; + stream_instance: EventSource | null = null; + + fetch(input: RequestInfo | URL, init?: RequestInit): Promise { + const headers = new Headers(init?.headers || {}); + if (this && this.cookies) { + headers.append("Cookie", this.cookies); } - const duplicated_space = await response.json(); - let original_hardware; + return fetch(input, { ...init, headers }); + } - if (!hardware) { - original_hardware = await get_space_hardware(app_reference, hf_token); - } + stream(url: URL): EventSource { + this.abort_controller = new AbortController(); - const requested_hardware = hardware || original_hardware || "cpu-basic"; - await set_space_hardware( - `${user}/${space_name}`, - requested_hardware, - hf_token - ); + this.stream_instance = readable_stream(url.toString(), { + signal: this.abort_controller.signal + }); - await set_space_timeout(`${user}/${space_name}`, timeout || 300, hf_token); - return client(duplicated_space.url, options); - } catch (e: any) { - throw new Error(e); + return this.stream_instance; } -} -interface Client { - post_data: ( - url: string, - body: unknown, - token?: `hf_${string}` - ) => Promise<[PostResponse, number]>; + view_api: () => Promise>; upload_files: ( - root: string, - files: File[], - token?: `hf_${string}`, + root_url: string, + files: (Blob | File)[], upload_id?: string ) => Promise; - client: ( - app_reference: string, - options: { - hf_token?: `hf_${string}`; - status_callback?: SpaceStatusCallback; - normalise_files?: boolean; - } - ) => Promise; + upload: ( + file_data: FileData[], + root_url: string, + upload_id?: string, + max_file_size?: number + ) => Promise<(FileData | null)[] | null>; handle_blob: ( endpoint: string, data: unknown[], - api_info: ApiInfo, - token?: `hf_${string}` + endpoint_info: EndpointInfo ) => Promise; -} - -export function api_factory( - fetch_implementation: typeof fetch, - EventSource_factory: (url: URL) => EventSource -): Client { - return { post_data, upload_files, client, handle_blob }; - - async function post_data( + post_data: ( url: string, body: unknown, - token?: `hf_${string}` - ): Promise<[PostResponse, number]> { - const headers: { - Authorization?: string; - "Content-Type": "application/json"; - } = { "Content-Type": "application/json" }; - if (token) { - headers.Authorization = `Bearer ${token}`; - } - try { - var response = await fetch_implementation(url, { - method: "POST", - body: JSON.stringify(body), - headers - }); - } catch (e) { - return [{ error: BROKEN_CONNECTION_MSG }, 500]; - } - let output: PostResponse; - let status: int; - try { - output = await response.json(); - status = response.status; - } catch (e) { - output = { error: `Could not parse server response: ${e}` }; - status = 500; + additional_headers?: any + ) => Promise; + submit: ( + endpoint: string | number, + data: unknown[] | Record, + event_data?: unknown, + trigger_id?: number | null, + all_events?: boolean + ) => SubmitIterable; + predict: ( + endpoint: string | number, + data: unknown[] | Record, + event_data?: unknown + ) => Promise; + open_stream: () => Promise; + private resolve_config: (endpoint: string) => Promise; + private resolve_cookies: () => Promise; + constructor( + app_reference: string, + options: ClientOptions = { events: ["data"] } + ) { + this.app_reference = app_reference; + if (!options.events) { + options.events = ["data"]; } - return [output, status]; - } - async function upload_files( - root: string, - files: (Blob | File)[], - token?: `hf_${string}`, - upload_id?: string - ): Promise { - const headers: { - Authorization?: string; - } = {}; - if (token) { - headers.Authorization = `Bearer ${token}`; - } - const chunkSize = 1000; - const uploadResponses = []; - for (let i = 0; i < files.length; i += chunkSize) { - const chunk = files.slice(i, i + chunkSize); - const formData = new FormData(); - chunk.forEach((file) => { - formData.append("files", file); - }); - try { - const upload_url = upload_id - ? `${root}/upload?upload_id=${upload_id}` - : `${root}/upload`; - var response = await fetch_implementation(upload_url, { - method: "POST", - body: formData, - headers - }); - } catch (e) { - return { error: BROKEN_CONNECTION_MSG }; - } - const output: UploadResponse["files"] = await response.json(); - uploadResponses.push(...output); - } - return { files: uploadResponses }; + this.options = options; + + this.view_api = view_api.bind(this); + this.upload_files = upload_files.bind(this); + this.handle_blob = handle_blob.bind(this); + this.post_data = post_data.bind(this); + this.submit = submit.bind(this); + this.predict = predict.bind(this); + this.open_stream = open_stream.bind(this); + this.resolve_config = resolve_config.bind(this); + this.resolve_cookies = resolve_cookies.bind(this); + this.upload = upload.bind(this); } - async function client( - app_reference: string, - options: { - hf_token?: `hf_${string}`; - status_callback?: SpaceStatusCallback; - normalise_files?: boolean; - } = { normalise_files: true } - ): Promise { - return new Promise(async (res) => { - const { status_callback, hf_token, normalise_files } = options; - const return_obj = { - predict, - submit, - view_api, - component_server - }; - - const transform_files = normalise_files ?? true; - if ( - (typeof window === "undefined" || !("WebSocket" in window)) && - !global.Websocket - ) { - const ws = await import("ws"); - NodeBlob = (await import("node:buffer")).Blob; - //@ts-ignore - global.WebSocket = ws.WebSocket; - } - - const { ws_protocol, http_protocol, host, space_id } = - await process_endpoint(app_reference, hf_token); - - const session_hash = Math.random().toString(36).substring(2); - const last_status: Record = {}; - let stream_open = false; - let pending_stream_messages: Record = {}; // Event messages may be received by the SSE stream before the initial data POST request is complete. To resolve this race condition, we store the messages in a dictionary and process them when the POST request is complete. - let event_stream: EventSource | null = null; - const event_callbacks: Record Promise> = {}; - const unclosed_events: Set = new Set(); - let config: Config; - let api_map: Record = {}; - - let jwt: false | string = false; - - if (hf_token && space_id) { - jwt = await get_jwt(space_id, hf_token); - } - - async function config_success(_config: Config): Promise { - config = _config; - api_map = map_names_to_ids(_config?.dependencies || []); - if (config.auth_required) { - return { - config, - ...return_obj - }; - } - try { - api = await view_api(config); - } catch (e) { - console.error(`Could not get api details: ${e.message}`); - } + private async init(): Promise { + if ( + (typeof window === "undefined" || !("WebSocket" in window)) && + !global.WebSocket + ) { + const ws = await import("ws"); + global.WebSocket = ws.WebSocket as unknown as typeof WebSocket; + } - return { - config, - ...return_obj - }; + try { + if (this.options.auth) { + await this.resolve_cookies(); } - let api: ApiInfo; - async function handle_space_sucess(status: SpaceStatus): Promise { - if (status_callback) status_callback(status); - if (status.status === "running") - try { - config = await resolve_config( - fetch_implementation, - `${http_protocol}//${host}`, - hf_token - ); - const _config = await config_success(config); - res(_config); - } catch (e) { - console.error(e); - if (status_callback) { - status_callback({ - status: "error", - message: "Could not load this space.", - load_status: "error", - detail: "NOT_FOUND" - }); - } - } - } + await this._resolve_config().then(({ config }) => + this._resolve_hearbeat(config) + ); + } catch (e: any) { + throw Error(e); + } - try { - config = await resolve_config( - fetch_implementation, - `${http_protocol}//${host}`, - hf_token - ); + this.api_info = await this.view_api(); + this.api_map = map_names_to_ids(this.config?.dependencies || []); + } - const _config = await config_success(config); - res(_config); - } catch (e) { - console.error(e); - if (space_id) { - check_space_status( - space_id, - RE_SPACE_NAME.test(space_id) ? "space_name" : "subdomain", - handle_space_sucess + async _resolve_hearbeat(_config: Config): Promise { + if (_config) { + this.config = _config; + if (this.config && this.config.connect_heartbeat) { + if (this.config.space_id && this.options.hf_token) { + this.jwt = await get_jwt( + this.config.space_id, + this.options.hf_token, + this.cookies ); - } else { - if (status_callback) - status_callback({ - status: "error", - message: "Could not load this space.", - load_status: "error", - detail: "NOT_FOUND" - }); } } + } - function predict( - endpoint: string, - data: unknown[], - event_data?: unknown - ): Promise { - let data_returned = false; - let status_complete = false; - let dependency; - if (typeof endpoint === "number") { - dependency = config.dependencies[endpoint]; - } else { - const trimmed_endpoint = endpoint.replace(/^\//, ""); - dependency = config.dependencies[api_map[trimmed_endpoint]]; - } - - if (dependency.types.continuous) { - throw new Error( - "Cannot call predict on this function as it may run forever. Use submit instead" - ); - } + if (_config.space_id && this.options.hf_token) { + this.jwt = await get_jwt(_config.space_id, this.options.hf_token); + } - return new Promise((res, rej) => { - const app = submit(endpoint, data, event_data); - let result; + if (this.config && this.config.connect_heartbeat) { + // connect to the heartbeat endpoint via GET request + const heartbeat_url = new URL( + `${this.config.root}/heartbeat/${this.session_hash}` + ); - app - .on("data", (d) => { - // if complete message comes before data, resolve here - if (status_complete) { - app.destroy(); - res(d); - } - data_returned = true; - result = d; - }) - .on("status", (status) => { - if (status.stage === "error") rej(status); - if (status.stage === "complete") { - status_complete = true; - // if complete message comes after data, resolve here - if (data_returned) { - app.destroy(); - res(result); - } - } - }); - }); + // if the jwt is available, add it to the query params + if (this.jwt) { + heartbeat_url.searchParams.set("__sign", this.jwt); } - function submit( - endpoint: string | number, - data: unknown[], - event_data?: unknown, - trigger_id: number | null = null - ): SubmitReturn { - let fn_index: number; - let api_info; - - if (typeof endpoint === "number") { - fn_index = endpoint; - api_info = api.unnamed_endpoints[fn_index]; - } else { - const trimmed_endpoint = endpoint.replace(/^\//, ""); - - fn_index = api_map[trimmed_endpoint]; - api_info = api.named_endpoints[endpoint.trim()]; - } - - if (typeof fn_index !== "number") { - throw new Error( - "There is no endpoint matching that name of fn_index matching that number." - ); - } - - let websocket: WebSocket; - let eventSource: EventSource; - let protocol = config.protocol ?? "ws"; - - const _endpoint = typeof endpoint === "number" ? "/predict" : endpoint; - let payload: Payload; - let event_id: string | null = null; - let complete: false | Record = false; - const listener_map: ListenerMap = {}; - let url_params = ""; - if (typeof window !== "undefined") { - url_params = new URLSearchParams(window.location.search).toString(); - } - - handle_blob(`${config.root}`, data, api_info, hf_token).then( - (_payload) => { - payload = { - data: _payload || [], - event_data, - fn_index, - trigger_id - }; - if (skip_queue(fn_index, config)) { - fire_event({ - type: "status", - endpoint: _endpoint, - stage: "pending", - queue: false, - fn_index, - time: new Date() - }); - - post_data( - `${config.root}/run${ - _endpoint.startsWith("/") ? _endpoint : `/${_endpoint}` - }${url_params ? "?" + url_params : ""}`, - { - ...payload, - session_hash - }, - hf_token - ) - .then(([output, status_code]) => { - const data = transform_files - ? transform_output( - output.data, - api_info, - config.root, - config.root_url - ) - : output.data; - if (status_code == 200) { - fire_event({ - type: "data", - endpoint: _endpoint, - fn_index, - data: data, - time: new Date() - }); - - fire_event({ - type: "status", - endpoint: _endpoint, - fn_index, - stage: "complete", - eta: output.average_duration, - queue: false, - time: new Date() - }); - } else { - fire_event({ - type: "status", - stage: "error", - endpoint: _endpoint, - fn_index, - message: output.error, - queue: false, - time: new Date() - }); - } - }) - .catch((e) => { - fire_event({ - type: "status", - stage: "error", - message: e.message, - endpoint: _endpoint, - fn_index, - queue: false, - time: new Date() - }); - }); - } else if (protocol == "ws") { - fire_event({ - type: "status", - stage: "pending", - queue: true, - endpoint: _endpoint, - fn_index, - time: new Date() - }); - let url = new URL(`${ws_protocol}://${resolve_root( - host, - config.path, - true - )} - /queue/join${url_params ? "?" + url_params : ""}`); - - if (jwt) { - url.searchParams.set("__sign", jwt); - } - - websocket = new WebSocket(url); - - websocket.onclose = (evt) => { - if (!evt.wasClean) { - fire_event({ - type: "status", - stage: "error", - broken: true, - message: BROKEN_CONNECTION_MSG, - queue: true, - endpoint: _endpoint, - fn_index, - time: new Date() - }); - } - }; - - websocket.onmessage = function (event) { - const _data = JSON.parse(event.data); - const { type, status, data } = handle_message( - _data, - last_status[fn_index] - ); - - if (type === "update" && status && !complete) { - // call 'status' listeners - fire_event({ - type: "status", - endpoint: _endpoint, - fn_index, - time: new Date(), - ...status - }); - if (status.stage === "error") { - websocket.close(); - } - } else if (type === "hash") { - websocket.send(JSON.stringify({ fn_index, session_hash })); - return; - } else if (type === "data") { - websocket.send(JSON.stringify({ ...payload, session_hash })); - } else if (type === "complete") { - complete = status; - } else if (type === "log") { - fire_event({ - type: "log", - log: data.log, - level: data.level, - endpoint: _endpoint, - fn_index - }); - } else if (type === "generating") { - fire_event({ - type: "status", - time: new Date(), - ...status, - stage: status?.stage!, - queue: true, - endpoint: _endpoint, - fn_index - }); - } - if (data) { - fire_event({ - type: "data", - time: new Date(), - data: transform_files - ? transform_output( - data.data, - api_info, - config.root, - config.root_url - ) - : data.data, - endpoint: _endpoint, - fn_index - }); - - if (complete) { - fire_event({ - type: "status", - time: new Date(), - ...complete, - stage: status?.stage!, - queue: true, - endpoint: _endpoint, - fn_index - }); - websocket.close(); - } - } - }; - - // different ws contract for gradio versions older than 3.6.0 - //@ts-ignore - if (semiver(config.version || "2.0.0", "3.6") < 0) { - addEventListener("open", () => - websocket.send(JSON.stringify({ hash: session_hash })) - ); - } - } else if (protocol == "sse") { - fire_event({ - type: "status", - stage: "pending", - queue: true, - endpoint: _endpoint, - fn_index, - time: new Date() - }); - var params = new URLSearchParams({ - fn_index: fn_index.toString(), - session_hash: session_hash - }).toString(); - let url = new URL( - `${config.root}/queue/join?${ - url_params ? url_params + "&" : "" - }${params}` - ); - - eventSource = EventSource_factory(url); + // Just connect to the endpoint without parsing the response. Ref: https://github.com/gradio-app/gradio/pull/7974#discussion_r1557717540 + if (!this.heartbeat_event) { + this.heartbeat_event = this.stream(heartbeat_url); + } + } + } - eventSource.onmessage = async function (event) { - const _data = JSON.parse(event.data); - const { type, status, data } = handle_message( - _data, - last_status[fn_index] - ); + static async connect( + app_reference: string, + options: ClientOptions = { + events: ["data"] + } + ): Promise { + const client = new this(app_reference, options); // this refers to the class itself, not the instance + await client.init(); + return client; + } - if (type === "update" && status && !complete) { - // call 'status' listeners - fire_event({ - type: "status", - endpoint: _endpoint, - fn_index, - time: new Date(), - ...status - }); - if (status.stage === "error") { - eventSource.close(); - } - } else if (type === "data") { - event_id = _data.event_id as string; - let [_, status] = await post_data( - `${config.root}/queue/data`, - { - ...payload, - session_hash, - event_id - }, - hf_token - ); - if (status !== 200) { - fire_event({ - type: "status", - stage: "error", - message: BROKEN_CONNECTION_MSG, - queue: true, - endpoint: _endpoint, - fn_index, - time: new Date() - }); - eventSource.close(); - } - } else if (type === "complete") { - complete = status; - } else if (type === "log") { - fire_event({ - type: "log", - log: data.log, - level: data.level, - endpoint: _endpoint, - fn_index - }); - } else if (type === "generating") { - fire_event({ - type: "status", - time: new Date(), - ...status, - stage: status?.stage!, - queue: true, - endpoint: _endpoint, - fn_index - }); - } - if (data) { - fire_event({ - type: "data", - time: new Date(), - data: transform_files - ? transform_output( - data.data, - api_info, - config.root, - config.root_url - ) - : data.data, - endpoint: _endpoint, - fn_index - }); + close(): void { + this.heartbeat_event?.close(); + } - if (complete) { - fire_event({ - type: "status", - time: new Date(), - ...complete, - stage: status?.stage!, - queue: true, - endpoint: _endpoint, - fn_index - }); - eventSource.close(); - } - } - }; - } else if (protocol == "sse_v1") { - fire_event({ - type: "status", - stage: "pending", - queue: true, - endpoint: _endpoint, - fn_index, - time: new Date() - }); + static async duplicate( + app_reference: string, + options: DuplicateOptions = { + events: ["data"] + } + ): Promise { + return duplicate(app_reference, options); + } - post_data( - `${config.root}/queue/join?${url_params}`, - { - ...payload, - session_hash - }, - hf_token - ).then(([response, status]) => { - if (status === 503) { - fire_event({ - type: "status", - stage: "error", - message: QUEUE_FULL_MSG, - queue: true, - endpoint: _endpoint, - fn_index, - time: new Date() - }); - } else if (status !== 200) { - fire_event({ - type: "status", - stage: "error", - message: BROKEN_CONNECTION_MSG, - queue: true, - endpoint: _endpoint, - fn_index, - time: new Date() - }); - } else { - event_id = response.event_id as string; - let callback = async function (_data: object): void { - try { - const { type, status, data } = handle_message( - _data, - last_status[fn_index] - ); + private async _resolve_config(): Promise { + const { http_protocol, host, space_id } = await process_endpoint( + this.app_reference, + this.options.hf_token + ); - if (type == "heartbeat") { - return; - } + const { status_callback } = this.options; + let config: Config | undefined; - if (type === "update" && status && !complete) { - // call 'status' listeners - fire_event({ - type: "status", - endpoint: _endpoint, - fn_index, - time: new Date(), - ...status - }); - } else if (type === "complete") { - complete = status; - } else if (type == "unexpected_error") { - console.error("Unexpected error", status?.message); - fire_event({ - type: "status", - stage: "error", - message: - status?.message || "An Unexpected Error Occurred!", - queue: true, - endpoint: _endpoint, - fn_index, - time: new Date() - }); - } else if (type === "log") { - fire_event({ - type: "log", - log: data.log, - level: data.level, - endpoint: _endpoint, - fn_index - }); - return; - } else if (type === "generating") { - fire_event({ - type: "status", - time: new Date(), - ...status, - stage: status?.stage!, - queue: true, - endpoint: _endpoint, - fn_index - }); - } - if (data) { - fire_event({ - type: "data", - time: new Date(), - data: transform_files - ? transform_output( - data.data, - api_info, - config.root, - config.root_url - ) - : data.data, - endpoint: _endpoint, - fn_index - }); + try { + config = await this.resolve_config(`${http_protocol}//${host}`); - if (complete) { - fire_event({ - type: "status", - time: new Date(), - ...complete, - stage: status?.stage!, - queue: true, - endpoint: _endpoint, - fn_index - }); - } - } + if (!config) { + throw new Error(CONFIG_ERROR_MSG); + } - if ( - status?.stage === "complete" || - status?.stage === "error" - ) { - if (event_callbacks[event_id]) { - delete event_callbacks[event_id]; - } - } - } catch (e) { - console.error("Unexpected client exception", e); - fire_event({ - type: "status", - stage: "error", - message: "An Unexpected Error Occurred!", - queue: true, - endpoint: _endpoint, - fn_index, - time: new Date() - }); - close_stream(); - } - }; - if (event_id in pending_stream_messages) { - pending_stream_messages[event_id].forEach((msg) => - callback(msg) - ); - delete pending_stream_messages[event_id]; - } - event_callbacks[event_id] = callback; - unclosed_events.add(event_id); - if (!stream_open) { - open_stream(); - } - } - }); - } - } + return this.config_success(config); + } catch (e: any) { + if (space_id && status_callback) { + check_space_status( + space_id, + RE_SPACE_NAME.test(space_id) ? "space_name" : "subdomain", + this.handle_space_success ); - - function fire_event(event: Event): void { - const narrowed_listener_map: ListenerMap = listener_map; - const listeners = narrowed_listener_map[event.type] || []; - listeners?.forEach((l) => l(event)); - } - - function on( - eventType: K, - listener: EventListener - ): SubmitReturn { - const narrowed_listener_map: ListenerMap = listener_map; - const listeners = narrowed_listener_map[eventType] || []; - narrowed_listener_map[eventType] = listeners; - listeners?.push(listener); - - return { on, off, cancel, destroy }; - } - - function off( - eventType: K, - listener: EventListener - ): SubmitReturn { - const narrowed_listener_map: ListenerMap = listener_map; - let listeners = narrowed_listener_map[eventType] || []; - listeners = listeners?.filter((l) => l !== listener); - narrowed_listener_map[eventType] = listeners; - - return { on, off, cancel, destroy }; - } - - async function cancel(): Promise { - const _status: Status = { - stage: "complete", - queue: false, - time: new Date() - }; - complete = _status; - fire_event({ - ..._status, - type: "status", - endpoint: _endpoint, - fn_index: fn_index + } else { + if (status_callback) + status_callback({ + status: "error", + message: "Could not load this space.", + load_status: "error", + detail: "NOT_FOUND" }); - - let cancel_request = {}; - if (protocol === "ws") { - if (websocket && websocket.readyState === 0) { - websocket.addEventListener("open", () => { - websocket.close(); - }); - } else { - websocket.close(); - } - cancel_request = { fn_index, session_hash }; - } else { - eventSource.close(); - cancel_request = { event_id }; - } - - try { - await fetch_implementation(`${config.root}/reset`, { - headers: { "Content-Type": "application/json" }, - method: "POST", - body: JSON.stringify(cancel_request) - }); - } catch (e) { - console.warn( - "The `/reset` endpoint could not be called. Subsequent endpoint results may be unreliable." - ); - } - } - - function destroy(): void { - for (const event_type in listener_map) { - listener_map[event_type as "data" | "status"].forEach((fn) => { - off(event_type as "data" | "status", fn); - }); - } - } - - return { - on, - off, - cancel, - destroy - }; + throw Error(e); } + } + } - function open_stream(): void { - stream_open = true; - let params = new URLSearchParams({ - session_hash: session_hash - }).toString(); - let url = new URL(`${config.root}/queue/data?${params}`); - event_stream = EventSource_factory(url); - event_stream.onmessage = async function (event) { - let _data = JSON.parse(event.data); - const event_id = _data.event_id; - if (!event_id) { - await Promise.all( - Object.keys(event_callbacks).map((event_id) => - event_callbacks[event_id](_data) - ) - ); - } else if (event_callbacks[event_id]) { - if (_data.msg === "process_completed") { - unclosed_events.delete(event_id); - if (unclosed_events.size === 0) { - close_stream(); - } - } - let fn = event_callbacks[event_id]; - window.setTimeout(fn, 0, _data); // need to do this to put the event on the end of the event loop, so the browser can refresh between callbacks and not freeze in case of quick generations. See https://github.com/gradio-app/gradio/pull/7055 - } else { - if (!pending_stream_messages[event_id]) { - pending_stream_messages[event_id] = []; - } - pending_stream_messages[event_id].push(_data); - } - }; - event_stream.onerror = async function (event) { - await Promise.all( - Object.keys(event_callbacks).map((event_id) => - event_callbacks[event_id]({ - msg: "unexpected_error", - message: BROKEN_CONNECTION_MSG - }) - ) - ); - close_stream(); - }; - } + private async config_success( + _config: Config + ): Promise { + this.config = _config; - function close_stream(): void { - stream_open = false; - event_stream?.close(); + if (typeof window !== "undefined" && typeof document !== "undefined") { + if (window.location.protocol === "https:") { + this.config.root = this.config.root.replace("http://", "https://"); } + } - async function component_server( - component_id: number, - fn_name: string, - data: unknown[] - ): Promise { - const headers: { - Authorization?: string; - "Content-Type": "application/json"; - } = { "Content-Type": "application/json" }; - if (hf_token) { - headers.Authorization = `Bearer ${hf_token}`; - } - let root_url: string; - let component = config.components.find( - (comp) => comp.id === component_id - ); - if (component?.props?.root_url) { - root_url = component.props.root_url; - } else { - root_url = config.root; - } - const response = await fetch_implementation( - `${root_url}/component_server/`, - { - method: "POST", - body: JSON.stringify({ - data: data, - component_id: component_id, - fn_name: fn_name, - session_hash: session_hash - }), - headers - } - ); - - if (!response.ok) { - throw new Error( - "Could not connect to component server: " + response.statusText - ); - } - - const output = await response.json(); - return output; - } + if (this.config.auth_required) { + return this.prepare_return_obj(); + } - async function view_api(config?: Config): Promise> { - if (api) return api; + try { + this.api_info = await this.view_api(); + } catch (e) { + console.error(API_INFO_ERROR_MSG + (e as Error).message); + } - const headers: { - Authorization?: string; - "Content-Type": "application/json"; - } = { "Content-Type": "application/json" }; - if (hf_token) { - headers.Authorization = `Bearer ${hf_token}`; - } - let response: Response; - // @ts-ignore - if (semiver(config.version || "2.0.0", "3.30") < 0) { - response = await fetch_implementation( - "https://gradio-space-api-fetcher-v2.hf.space/api", - { - method: "POST", - body: JSON.stringify({ - serialize: false, - config: JSON.stringify(config) - }), - headers - } - ); - } else { - response = await fetch_implementation(`${config.root}/info`, { - headers - }); - } + return this.prepare_return_obj(); + } - if (!response.ok) { - throw new Error(BROKEN_CONNECTION_MSG); + async handle_space_success(status: SpaceStatus): Promise { + if (!this) { + throw new Error(CONFIG_ERROR_MSG); + } + const { status_callback } = this.options; + if (status_callback) status_callback(status); + if (status.status === "running") { + try { + this.config = await this._resolve_config(); + if (!this.config) { + throw new Error(CONFIG_ERROR_MSG); } - let api_info = (await response.json()) as - | ApiInfo - | { api: ApiInfo }; - if ("api" in api_info) { - api_info = api_info.api; - } + const _config = await this.config_success(this.config); - if ( - api_info.named_endpoints["/predict"] && - !api_info.unnamed_endpoints["0"] - ) { - api_info.unnamed_endpoints[0] = api_info.named_endpoints["/predict"]; + return _config as Config; + } catch (e) { + if (status_callback) { + status_callback({ + status: "error", + message: "Could not load this space.", + load_status: "error", + detail: "NOT_FOUND" + }); } - - const x = transform_api_info(api_info, config, api_map); - return x; + throw e; } - }); - } - - async function handle_blob( - endpoint: string, - data: unknown[], - api_info: ApiInfo, - token?: `hf_${string}` - ): Promise { - const blob_refs = await walk_and_store_blobs( - data, - undefined, - [], - true, - api_info - ); - - return Promise.all( - blob_refs.map(async ({ path, blob, type }) => { - if (blob) { - const file_url = (await upload_files(endpoint, [blob], token)) - .files[0]; - return { path, file_url, type, name: blob?.name }; - } - return { path, type }; - }) - ).then((r) => { - r.forEach(({ path, file_url, type, name }) => { - if (type === "Gallery") { - update_object(data, file_url, path); - } else if (file_url) { - const file = new FileData({ path: file_url, orig_name: name }); - update_object(data, file, path); - } - }); - - return data; - }); - } -} - -export const { post_data, upload_files, client, handle_blob } = api_factory( - fetch, - (...args) => new EventSource(...args) -); - -function transform_output( - data: any[], - api_info: any, - root_url: string, - remote_url?: string -): unknown[] { - return data.map((d, i) => { - if (api_info?.returns?.[i]?.component === "File") { - return normalise_file(d, root_url, remote_url); - } else if (api_info?.returns?.[i]?.component === "Gallery") { - return d.map((img) => { - return Array.isArray(img) - ? [normalise_file(img[0], root_url, remote_url), img[1]] - : [normalise_file(img, root_url, remote_url), null]; - }); - } else if (typeof d === "object" && d.path) { - return normalise_file(d, root_url, remote_url); } - return d; - }); -} - -interface ApiData { - label: string; - type: { - type: any; - description: string; - }; - component: string; - example_input?: any; -} - -interface JsApiData { - label: string; - type: string; - component: string; - example_input: any; -} - -interface EndpointInfo { - parameters: T[]; - returns: T[]; -} -interface ApiInfo { - named_endpoints: { - [key: string]: EndpointInfo; - }; - unnamed_endpoints: { - [key: string]: EndpointInfo; - }; -} - -function get_type( - type: { [key: string]: any }, - component: string, - serializer: string, - signature_type: "return" | "parameter" -): string { - switch (type.type) { - case "string": - return "string"; - case "boolean": - return "boolean"; - case "number": - return "number"; } - if ( - serializer === "JSONSerializable" || - serializer === "StringSerializable" - ) { - return "any"; - } else if (serializer === "ListStringSerializable") { - return "string[]"; - } else if (component === "Image") { - return signature_type === "parameter" ? "Blob | File | Buffer" : "string"; - } else if (serializer === "FileSerializable") { - if (type?.type === "array") { - return signature_type === "parameter" - ? "(Blob | File | Buffer)[]" - : `{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}[]`; + public async component_server( + component_id: number, + fn_name: string, + data: unknown[] | { binary: boolean; data: Record } + ): Promise { + if (!this.config) { + throw new Error(CONFIG_ERROR_MSG); } - return signature_type === "parameter" - ? "Blob | File | Buffer" - : `{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}`; - } else if (serializer === "GallerySerializable") { - return signature_type === "parameter" - ? "[(Blob | File | Buffer), (string | null)][]" - : `[{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}, (string | null))][]`; - } -} -function get_description( - type: { type: any; description: string }, - serializer: string -): string { - if (serializer === "GallerySerializable") { - return "array of [file, label] tuples"; - } else if (serializer === "ListStringSerializable") { - return "array of strings"; - } else if (serializer === "FileSerializable") { - return "array of files or single file"; - } - return type.description; -} - -function transform_api_info( - api_info: ApiInfo, - config: Config, - api_map: Record -): ApiInfo { - const new_data = { - named_endpoints: {}, - unnamed_endpoints: {} - }; - for (const key in api_info) { - const cat = api_info[key]; + const headers: { + Authorization?: string; + "Content-Type"?: "application/json"; + } = {}; - for (const endpoint in cat) { - const dep_index = config.dependencies[endpoint] - ? endpoint - : api_map[endpoint.replace("/", "")]; + const { hf_token } = this.options; + const { session_hash } = this; - const info = cat[endpoint]; - new_data[key][endpoint] = {}; - new_data[key][endpoint].parameters = {}; - new_data[key][endpoint].returns = {}; - new_data[key][endpoint].type = config.dependencies[dep_index].types; - new_data[key][endpoint].parameters = info.parameters.map( - ({ label, component, type, serializer }) => ({ - label, - component, - type: get_type(type, component, serializer, "parameter"), - description: get_description(type, serializer) - }) - ); + if (hf_token) { + headers.Authorization = `Bearer ${this.options.hf_token}`; + } - new_data[key][endpoint].returns = info.returns.map( - ({ label, component, type, serializer }) => ({ - label, - component, - type: get_type(type, component, serializer, "return"), - description: get_description(type, serializer) - }) - ); + let root_url: string; + let component = this.config.components.find( + (comp) => comp.id === component_id + ); + if (component?.props?.root_url) { + root_url = component.props.root_url; + } else { + root_url = this.config.root; } - } - return new_data; -} + let body: FormData | string; -async function get_jwt( - space: string, - token: `hf_${string}` -): Promise { - try { - const r = await fetch(`https://huggingface.co/api/spaces/${space}/jwt`, { - headers: { - Authorization: `Bearer ${token}` + if ("binary" in data) { + body = new FormData(); + for (const key in data.data) { + if (key === "binary") continue; + body.append(key, data.data[key]); } - }); - - const jwt = (await r.json()).token; - - return jwt || false; - } catch (e) { - console.error(e); - return false; - } -} - -function update_object(object, newValue, stack): void { - while (stack.length > 1) { - object = object[stack.shift()]; - } - - object[stack.shift()] = newValue; -} - -export async function walk_and_store_blobs( - param, - type = undefined, - path = [], - root = false, - api_info = undefined -): Promise< - { - path: string[]; - type: string; - blob: Blob | false; - }[] -> { - if (Array.isArray(param)) { - let blob_refs = []; + body.set("component_id", component_id.toString()); + body.set("fn_name", fn_name); + body.set("session_hash", session_hash); + } else { + body = JSON.stringify({ + data: data, + component_id, + fn_name, + session_hash + }); - await Promise.all( - param.map(async (v, i) => { - let new_path = path.slice(); - new_path.push(i); + headers["Content-Type"] = "application/json"; + } - const array_refs = await walk_and_store_blobs( - param[i], - root ? api_info?.parameters[i]?.component || undefined : type, - new_path, - false, - api_info - ); + if (hf_token) { + headers.Authorization = `Bearer ${hf_token}`; + } - blob_refs = blob_refs.concat(array_refs); - }) - ); + try { + const response = await this.fetch(`${root_url}/component_server/`, { + method: "POST", + body: body, + headers, + credentials: "include" + }); - return blob_refs; - } else if (globalThis.Buffer && param instanceof globalThis.Buffer) { - const is_image = type === "Image"; - return [ - { - path: path, - blob: is_image ? false : new NodeBlob([param]), - type - } - ]; - } else if (typeof param === "object") { - let blob_refs = []; - for (let key in param) { - if (param.hasOwnProperty(key)) { - let new_path = path.slice(); - new_path.push(key); - blob_refs = blob_refs.concat( - await walk_and_store_blobs( - param[key], - undefined, - new_path, - false, - api_info - ) + if (!response.ok) { + throw new Error( + "Could not connect to component server: " + response.statusText ); } - } - return blob_refs; - } - return []; -} - -function image_to_data_uri(blob: Blob): Promise { - return new Promise((resolve, _) => { - const reader = new FileReader(); - reader.onloadend = () => resolve(reader.result); - reader.readAsDataURL(blob); - }); -} - -function skip_queue(id: number, config: Config): boolean { - return ( - !(config?.dependencies?.[id]?.queue === null - ? config.enable_queue - : config?.dependencies?.[id]?.queue) || false - ); -} - -async function resolve_config( - fetch_implementation: typeof fetch, - endpoint?: string, - token?: `hf_${string}` -): Promise { - const headers: { Authorization?: string } = {}; - if (token) { - headers.Authorization = `Bearer ${token}`; - } - if ( - typeof window !== "undefined" && - window.gradio_config && - location.origin !== "http://localhost:9876" && - !window.gradio_config.dev_mode - ) { - const path = window.gradio_config.root; - const config = window.gradio_config; - config.root = resolve_root(endpoint, config.root, false); - return { ...config, path: path }; - } else if (endpoint) { - let response = await fetch_implementation(`${endpoint}/config`, { - headers - }); - if (response.status === 200) { - const config = await response.json(); - config.path = config.path ?? ""; - config.root = endpoint; - return config; + const output = await response.json(); + return output; + } catch (e) { + console.warn(e); } - throw new Error("Could not get config."); } - throw new Error("No config or app endpoint found"); -} - -async function check_space_status( - id: string, - type: "subdomain" | "space_name", - status_callback: SpaceStatusCallback -): Promise { - let endpoint = - type === "subdomain" - ? `https://huggingface.co/api/spaces/by-subdomain/${id}` - : `https://huggingface.co/api/spaces/${id}`; - let response; - let _status; - try { - response = await fetch(endpoint); - _status = response.status; - if (_status !== 200) { - throw new Error(); - } - response = await response.json(); - } catch (e) { - status_callback({ - status: "error", - load_status: "error", - message: "Could not get space status", - detail: "NOT_FOUND" - }); - return; + public set_cookies(raw_cookies: string): void { + this.cookies = parse_and_set_cookies(raw_cookies).join("; "); } - if (!response || _status !== 200) return; - const { - runtime: { stage }, - id: space_name - } = response; - - switch (stage) { - case "STOPPED": - case "SLEEPING": - status_callback({ - status: "sleeping", - load_status: "pending", - message: "Space is asleep. Waking it up...", - detail: stage - }); - - setTimeout(() => { - check_space_status(id, type, status_callback); - }, 1000); // poll for status - break; - case "PAUSED": - status_callback({ - status: "paused", - load_status: "error", - message: - "This space has been paused by the author. If you would like to try this demo, consider duplicating the space.", - detail: stage, - discussions_enabled: await discussions_enabled(space_name) - }); - break; - case "RUNNING": - case "RUNNING_BUILDING": - status_callback({ - status: "running", - load_status: "complete", - message: "", - detail: stage - }); - // load_config(source); - // launch - break; - case "BUILDING": - status_callback({ - status: "building", - load_status: "pending", - message: "Space is building...", - detail: stage - }); - - setTimeout(() => { - check_space_status(id, type, status_callback); - }, 1000); - break; - default: - status_callback({ - status: "space_error", - load_status: "error", - message: "This space is experiencing an issue.", - detail: stage, - discussions_enabled: await discussions_enabled(space_name) - }); - break; + private prepare_return_obj(): client_return { + return { + config: this.config, + predict: this.predict, + submit: this.submit, + view_api: this.view_api, + component_server: this.component_server + }; } } -function handle_message( - data: any, - last_status: Status["stage"] -): { - type: "hash" | "data" | "update" | "complete" | "generating" | "log" | "none"; - data?: any; - status?: Status; -} { - const queue = true; - switch (data.msg) { - case "send_data": - return { type: "data" }; - case "send_hash": - return { type: "hash" }; - case "queue_full": - return { - type: "update", - status: { - queue, - message: QUEUE_FULL_MSG, - stage: "error", - code: data.code, - success: data.success - } - }; - case "heartbeat": - return { - type: "heartbeat" - }; - case "unexpected_error": - return { - type: "unexpected_error", - status: { - queue, - message: data.message, - stage: "error", - success: false - } - }; - case "estimation": - return { - type: "update", - status: { - queue, - stage: last_status || "pending", - code: data.code, - size: data.queue_size, - position: data.rank, - eta: data.rank_eta, - success: data.success - } - }; - case "progress": - return { - type: "update", - status: { - queue, - stage: "pending", - code: data.code, - progress_data: data.progress_data, - success: data.success - } - }; - case "log": - return { type: "log", data: data }; - case "process_generating": - return { - type: "generating", - status: { - queue, - message: !data.success ? data.output.error : null, - stage: data.success ? "generating" : "error", - code: data.code, - progress_data: data.progress_data, - eta: data.average_duration - }, - data: data.success ? data.output : null - }; - case "process_completed": - if ("error" in data.output) { - return { - type: "update", - status: { - queue, - message: data.output.error as string, - stage: "error", - code: data.code, - success: data.success - } - }; - } - return { - type: "complete", - status: { - queue, - message: !data.success ? data.output.error : undefined, - stage: data.success ? "complete" : "error", - code: data.code, - progress_data: data.progress_data - }, - data: data.success ? data.output : null - }; - - case "process_starts": - return { - type: "update", - status: { - queue, - stage: "pending", - code: data.code, - size: data.rank, - position: 0, - success: data.success, - eta: data.eta - } - }; +/** + * @deprecated This method will be removed in v1.0. Use `Client.connect()` instead. + * Creates a client instance for interacting with Gradio apps. + * + * @param {string} app_reference - The reference or URL to a Gradio space or app. + * @param {ClientOptions} options - Configuration options for the client. + * @returns {Promise} A promise that resolves to a `Client` instance. + */ +export async function client( + app_reference: string, + options: ClientOptions = { + events: ["data"] } +): Promise { + return await Client.connect(app_reference, options); +} - return { type: "none", status: { stage: "error", queue } }; +/** + * @deprecated This method will be removed in v1.0. Use `Client.duplicate()` instead. + * Creates a duplicate of a space and returns a client instance for the duplicated space. + * + * @param {string} app_reference - The reference or URL to a Gradio space or app to duplicate. + * @param {DuplicateOptions} options - Configuration options for the client. + * @returns {Promise} A promise that resolves to a `Client` instance. + */ +export async function duplicate_space( + app_reference: string, + options: DuplicateOptions +): Promise { + return await Client.duplicate(app_reference, options); } + +export type ClientInstance = Client; diff --git a/node_modules/@gradio/client/src/constants.ts b/node_modules/@gradio/client/src/constants.ts new file mode 100644 index 0000000000000000000000000000000000000000..488ae760b110a6e176261cb32fd22339f9a3a5b0 --- /dev/null +++ b/node_modules/@gradio/client/src/constants.ts @@ -0,0 +1,36 @@ +// endpoints +export const HOST_URL = "host"; +export const API_URL = "api/predict/"; +export const SSE_URL_V0 = "queue/join"; +export const SSE_DATA_URL_V0 = "queue/data"; +export const SSE_URL = "queue/data"; +export const SSE_DATA_URL = "queue/join"; +export const UPLOAD_URL = "upload"; +export const LOGIN_URL = "login"; +export const CONFIG_URL = "config"; +export const API_INFO_URL = "info"; +export const RUNTIME_URL = "runtime"; +export const SLEEPTIME_URL = "sleeptime"; +export const RAW_API_INFO_URL = "info?serialize=False"; +export const SPACE_FETCHER_URL = + "https://gradio-space-api-fetcher-v2.hf.space/api"; +export const RESET_URL = "reset"; +export const SPACE_URL = "https://hf.space/{}"; + +// messages +export const QUEUE_FULL_MSG = + "This application is currently busy. Please try again. "; +export const BROKEN_CONNECTION_MSG = "Connection errored out. "; +export const CONFIG_ERROR_MSG = "Could not resolve app config. "; +export const SPACE_STATUS_ERROR_MSG = "Could not get space status. "; +export const API_INFO_ERROR_MSG = "Could not get API info. "; +export const SPACE_METADATA_ERROR_MSG = "Space metadata could not be loaded. "; +export const INVALID_URL_MSG = "Invalid URL. A full URL path is required."; +export const UNAUTHORIZED_MSG = "Not authorized to access this space. "; +export const INVALID_CREDENTIALS_MSG = "Invalid credentials. Could not login. "; +export const MISSING_CREDENTIALS_MSG = + "Login credentials are required to access this space."; +export const NODEJS_FS_ERROR_MSG = + "File system access is only available in Node.js environments"; +export const ROOT_URL_ERROR_MSG = "Root URL not found in client config"; +export const FILE_PROCESSING_ERROR_MSG = "Error uploading file"; diff --git a/node_modules/@gradio/client/src/globals.d.ts b/node_modules/@gradio/client/src/globals.d.ts index 64966293360c00b9b6c18a347259650b92c93b91..8125a0bf370f45a1ea2041fcb51f4d726a4eb350 100644 --- a/node_modules/@gradio/client/src/globals.d.ts +++ b/node_modules/@gradio/client/src/globals.d.ts @@ -1,3 +1,5 @@ +import { Config } from "./types"; + declare global { interface Window { __gradio_mode__: "app" | "website"; @@ -6,24 +8,3 @@ declare global { __gradio_space__: string | null; } } - -export interface Config { - auth_required: boolean | undefined; - auth_message: string; - components: any[]; - css: string | null; - dependencies: any[]; - dev_mode: boolean; - enable_queue: boolean; - layout: any; - mode: "blocks" | "interface"; - root: string; - theme: string; - title: string; - version: string; - space_id: string | null; - is_colab: boolean; - show_api: boolean; - stylesheets: string[]; - path: string; -} diff --git a/node_modules/@gradio/client/src/helpers/api_info.ts b/node_modules/@gradio/client/src/helpers/api_info.ts new file mode 100644 index 0000000000000000000000000000000000000000..0c4efcc4fa9df0c89a31f541a5442552c4e8c3d4 --- /dev/null +++ b/node_modules/@gradio/client/src/helpers/api_info.ts @@ -0,0 +1,430 @@ +import type { Status } from "../types"; +import { + HOST_URL, + INVALID_URL_MSG, + QUEUE_FULL_MSG, + SPACE_METADATA_ERROR_MSG +} from "../constants"; +import type { ApiData, ApiInfo, Config, JsApiData } from "../types"; +import { determine_protocol } from "./init_helpers"; + +export const RE_SPACE_NAME = /^[a-zA-Z0-9_\-\.]+\/[a-zA-Z0-9_\-\.]+$/; +export const RE_SPACE_DOMAIN = /.*hf\.space\/{0,1}$/; + +export async function process_endpoint( + app_reference: string, + hf_token?: `hf_${string}` +): Promise<{ + space_id: string | false; + host: string; + ws_protocol: "ws" | "wss"; + http_protocol: "http:" | "https:"; +}> { + const headers: { Authorization?: string } = {}; + if (hf_token) { + headers.Authorization = `Bearer ${hf_token}`; + } + + const _app_reference = app_reference.trim().replace(/\/$/, ""); + + if (RE_SPACE_NAME.test(_app_reference)) { + // app_reference is a HF space name + try { + const res = await fetch( + `https://huggingface.co/api/spaces/${_app_reference}/${HOST_URL}`, + { headers } + ); + + const _host = (await res.json()).host; + + return { + space_id: app_reference, + ...determine_protocol(_host) + }; + } catch (e) { + throw new Error(SPACE_METADATA_ERROR_MSG); + } + } + + if (RE_SPACE_DOMAIN.test(_app_reference)) { + // app_reference is a direct HF space domain + const { ws_protocol, http_protocol, host } = + determine_protocol(_app_reference); + + return { + space_id: host.replace(".hf.space", ""), + ws_protocol, + http_protocol, + host + }; + } + + return { + space_id: false, + ...determine_protocol(_app_reference) + }; +} + +export const join_urls = (...urls: string[]): string => { + try { + return urls.reduce((base_url: string, part: string) => { + base_url = base_url.replace(/\/+$/, ""); + part = part.replace(/^\/+/, ""); + return new URL(part, base_url + "/").toString(); + }); + } catch (e) { + throw new Error(INVALID_URL_MSG); + } +}; + +export function transform_api_info( + api_info: ApiInfo, + config: Config, + api_map: Record +): ApiInfo { + const transformed_info: ApiInfo = { + named_endpoints: {}, + unnamed_endpoints: {} + }; + + Object.keys(api_info).forEach((category) => { + if (category === "named_endpoints" || category === "unnamed_endpoints") { + transformed_info[category] = {}; + + Object.entries(api_info[category]).forEach( + ([endpoint, { parameters, returns }]) => { + const dependencyIndex = + config.dependencies.find( + (dep) => + dep.api_name === endpoint || + dep.api_name === endpoint.replace("/", "") + )?.id || + api_map[endpoint.replace("/", "")] || + -1; + + const dependencyTypes = + dependencyIndex !== -1 + ? config.dependencies.find((dep) => dep.id == dependencyIndex) + ?.types + : { continuous: false, generator: false, cancel: false }; + + if ( + dependencyIndex !== -1 && + config.dependencies.find((dep) => dep.id == dependencyIndex)?.inputs + ?.length !== parameters.length + ) { + const components = config.dependencies + .find((dep) => dep.id == dependencyIndex)! + .inputs.map( + (input) => config.components.find((c) => c.id === input)?.type + ); + + try { + components.forEach((comp, idx) => { + if (comp === "state") { + const new_param = { + component: "state", + example: null, + parameter_default: null, + parameter_has_default: true, + parameter_name: null, + hidden: true + }; + + // @ts-ignore + parameters.splice(idx, 0, new_param); + } + }); + } catch (e) { + console.error(e); + } + } + + const transform_type = ( + data: ApiData, + component: string, + serializer: string, + signature_type: "return" | "parameter" + ): JsApiData => ({ + ...data, + description: get_description(data?.type, serializer), + type: + get_type(data?.type, component, serializer, signature_type) || "" + }); + + transformed_info[category][endpoint] = { + parameters: parameters.map((p: ApiData) => + transform_type(p, p?.component, p?.serializer, "parameter") + ), + returns: returns.map((r: ApiData) => + transform_type(r, r?.component, r?.serializer, "return") + ), + type: dependencyTypes + }; + } + ); + } + }); + + return transformed_info; +} + +export function get_type( + type: { type: any; description: string }, + component: string, + serializer: string, + signature_type: "return" | "parameter" +): string | undefined { + switch (type?.type) { + case "string": + return "string"; + case "boolean": + return "boolean"; + case "number": + return "number"; + } + + if ( + serializer === "JSONSerializable" || + serializer === "StringSerializable" + ) { + return "any"; + } else if (serializer === "ListStringSerializable") { + return "string[]"; + } else if (component === "Image") { + return signature_type === "parameter" ? "Blob | File | Buffer" : "string"; + } else if (serializer === "FileSerializable") { + if (type?.type === "array") { + return signature_type === "parameter" + ? "(Blob | File | Buffer)[]" + : `{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}[]`; + } + return signature_type === "parameter" + ? "Blob | File | Buffer" + : `{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}`; + } else if (serializer === "GallerySerializable") { + return signature_type === "parameter" + ? "[(Blob | File | Buffer), (string | null)][]" + : `[{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}, (string | null))][]`; + } +} + +export function get_description( + type: { type: any; description: string }, + serializer: string +): string { + if (serializer === "GallerySerializable") { + return "array of [file, label] tuples"; + } else if (serializer === "ListStringSerializable") { + return "array of strings"; + } else if (serializer === "FileSerializable") { + return "array of files or single file"; + } + return type?.description; +} + +/* eslint-disable complexity */ +export function handle_message( + data: any, + last_status: Status["stage"] +): { + type: + | "hash" + | "data" + | "update" + | "complete" + | "generating" + | "log" + | "none" + | "heartbeat" + | "unexpected_error"; + data?: any; + status?: Status; +} { + const queue = true; + switch (data.msg) { + case "send_data": + return { type: "data" }; + case "send_hash": + return { type: "hash" }; + case "queue_full": + return { + type: "update", + status: { + queue, + message: QUEUE_FULL_MSG, + stage: "error", + code: data.code, + success: data.success + } + }; + case "heartbeat": + return { + type: "heartbeat" + }; + case "unexpected_error": + return { + type: "unexpected_error", + status: { + queue, + message: data.message, + stage: "error", + success: false + } + }; + case "estimation": + return { + type: "update", + status: { + queue, + stage: last_status || "pending", + code: data.code, + size: data.queue_size, + position: data.rank, + eta: data.rank_eta, + success: data.success + } + }; + case "progress": + return { + type: "update", + status: { + queue, + stage: "pending", + code: data.code, + progress_data: data.progress_data, + success: data.success + } + }; + case "log": + return { type: "log", data: data }; + case "process_generating": + return { + type: "generating", + status: { + queue, + message: !data.success ? data.output.error : null, + stage: data.success ? "generating" : "error", + code: data.code, + progress_data: data.progress_data, + eta: data.average_duration + }, + data: data.success ? data.output : null + }; + case "process_completed": + if ("error" in data.output) { + return { + type: "update", + status: { + queue, + message: data.output.error as string, + stage: "error", + code: data.code, + success: data.success + } + }; + } + return { + type: "complete", + status: { + queue, + message: !data.success ? data.output.error : undefined, + stage: data.success ? "complete" : "error", + code: data.code, + progress_data: data.progress_data, + changed_state_ids: data.success + ? data.output.changed_state_ids + : undefined + }, + data: data.success ? data.output : null + }; + + case "process_starts": + return { + type: "update", + status: { + queue, + stage: "pending", + code: data.code, + size: data.rank, + position: 0, + success: data.success, + eta: data.eta + } + }; + } + + return { type: "none", status: { stage: "error", queue } }; +} +/* eslint-enable complexity */ + +/** + * Maps the provided `data` to the parameters defined by the `/info` endpoint response. + * This allows us to support both positional and keyword arguments passed to the client + * and ensures that all parameters are either directly provided or have default values assigned. + * + * @param {unknown[] | Record} data - The input data for the function, + * which can be either an array of values for positional arguments or an object + * with key-value pairs for keyword arguments. + * @param {JsApiData[]} parameters - Array of parameter descriptions retrieved from the + * `/info` endpoint. + * + * @returns {unknown[]} - Returns an array of resolved data where each element corresponds + * to the expected parameter from the API. The `parameter_default` value is used where + * a value is not provided for a parameter, and optional parameters without defaults are + * set to `undefined`. + * + * @throws {Error} - Throws an error: + * - If more arguments are provided than are defined in the parameters. + * * - If no parameter value is provided for a required parameter and no default value is defined. + * - If an argument is provided that does not match any defined parameter. + */ + +export const map_data_to_params = ( + data: unknown[] | Record, + api_info: ApiInfo +): unknown[] => { + const parameters = Object.values(api_info.named_endpoints).flatMap( + (values) => values.parameters + ); + + if (Array.isArray(data)) { + if (data.length > parameters.length) { + console.warn("Too many arguments provided for the endpoint."); + } + return data; + } + + const resolved_data: unknown[] = []; + const provided_keys = Object.keys(data); + + parameters.forEach((param, index) => { + if (data.hasOwnProperty(param.parameter_name)) { + resolved_data[index] = data[param.parameter_name]; + } else if (param.parameter_has_default) { + resolved_data[index] = param.parameter_default; + } else { + throw new Error( + `No value provided for required parameter: ${param.parameter_name}` + ); + } + }); + + provided_keys.forEach((key) => { + if (!parameters.some((param) => param.parameter_name === key)) { + throw new Error( + `Parameter \`${key}\` is not a valid keyword argument. Please refer to the API for usage.` + ); + } + }); + + resolved_data.forEach((value, idx) => { + if (value === undefined && !parameters[idx].parameter_has_default) { + throw new Error( + `No value provided for required parameter: ${parameters[idx].parameter_name}` + ); + } + }); + + return resolved_data; +}; diff --git a/node_modules/@gradio/client/src/helpers/data.ts b/node_modules/@gradio/client/src/helpers/data.ts new file mode 100644 index 0000000000000000000000000000000000000000..03bcb4cf52496f3cf03ecfb827087960f0d8527b --- /dev/null +++ b/node_modules/@gradio/client/src/helpers/data.ts @@ -0,0 +1,234 @@ +import { + type ApiData, + type BlobRef, + type Config, + type EndpointInfo, + type JsApiData, + type DataType, + Command, + type Dependency, + type ComponentMeta +} from "../types"; +import { FileData } from "../upload"; + +const is_node = + typeof process !== "undefined" && process.versions && process.versions.node; + +export function update_object( + object: { [x: string]: any }, + newValue: any, + stack: (string | number)[] +): void { + while (stack.length > 1) { + const key = stack.shift(); + if (typeof key === "string" || typeof key === "number") { + object = object[key]; + } else { + throw new Error("Invalid key type"); + } + } + + const key = stack.shift(); + if (typeof key === "string" || typeof key === "number") { + object[key] = newValue; + } else { + throw new Error("Invalid key type"); + } +} + +export async function walk_and_store_blobs( + data: DataType, + type: string | undefined = undefined, + path: string[] = [], + root = false, + endpoint_info: EndpointInfo | undefined = undefined +): Promise { + if (Array.isArray(data)) { + let blob_refs: BlobRef[] = []; + + await Promise.all( + data.map(async (_, index) => { + let new_path = path.slice(); + new_path.push(String(index)); + + const array_refs = await walk_and_store_blobs( + data[index], + root + ? endpoint_info?.parameters[index]?.component || undefined + : type, + new_path, + false, + endpoint_info + ); + + blob_refs = blob_refs.concat(array_refs); + }) + ); + + return blob_refs; + } else if ( + (globalThis.Buffer && data instanceof globalThis.Buffer) || + data instanceof Blob + ) { + return [ + { + path: path, + blob: new Blob([data]), + type + } + ]; + } else if (typeof data === "object" && data !== null) { + let blob_refs: BlobRef[] = []; + for (const key of Object.keys(data) as (keyof typeof data)[]) { + const new_path = [...path, key]; + const value = data[key]; + + blob_refs = blob_refs.concat( + await walk_and_store_blobs( + value, + undefined, + new_path, + false, + endpoint_info + ) + ); + } + + return blob_refs; + } + + return []; +} + +export function skip_queue(id: number, config: Config): boolean { + let fn_queue = config?.dependencies?.find((dep) => dep.id == id)?.queue; + if (fn_queue != null) { + return !fn_queue; + } + return !config.enable_queue; +} + +// todo: add jsdoc for this function + +export function post_message( + message: any, + origin: string +): Promise { + return new Promise((res, _rej) => { + const channel = new MessageChannel(); + channel.port1.onmessage = (({ data }) => { + channel.port1.close(); + res(data); + }) as (ev: MessageEvent) => void; + window.parent.postMessage(message, origin, [channel.port2]); + }); +} + +export function handle_file( + file_or_url: File | string | Blob | Buffer +): FileData | Blob | Command { + if (typeof file_or_url === "string") { + if ( + file_or_url.startsWith("http://") || + file_or_url.startsWith("https://") + ) { + return { + path: file_or_url, + url: file_or_url, + orig_name: file_or_url.split("/").pop() ?? "unknown", + meta: { _type: "gradio.FileData" } + }; + } + + if (is_node) { + // Handle local file paths + return new Command("upload_file", { + path: file_or_url, + name: file_or_url, + orig_path: file_or_url + }); + } + } else if (typeof File !== "undefined" && file_or_url instanceof File) { + return { + path: file_or_url instanceof File ? file_or_url.name : "blob", + orig_name: file_or_url instanceof File ? file_or_url.name : "unknown", + // @ts-ignore + blob: file_or_url instanceof File ? file_or_url : new Blob([file_or_url]), + size: + file_or_url instanceof Blob + ? file_or_url.size + : Buffer.byteLength(file_or_url as Buffer), + mime_type: + file_or_url instanceof File + ? file_or_url.type + : "application/octet-stream", // Default MIME type for buffers + meta: { _type: "gradio.FileData" } + }; + } else if (file_or_url instanceof Buffer) { + return new Blob([file_or_url]); + } else if (file_or_url instanceof Blob) { + return file_or_url; + } + throw new Error( + "Invalid input: must be a URL, File, Blob, or Buffer object." + ); +} + +/** + * Handles the payload by filtering out state inputs and returning an array of resolved payload values. + * We send null values for state inputs to the server, but we don't want to include them in the resolved payload. + * + * @param resolved_payload - The resolved payload values received from the client or the server + * @param dependency - The dependency object. + * @param components - The array of component metadata. + * @param with_null_state - Optional. Specifies whether to include null values for state inputs. Default is false. + * @returns An array of resolved payload values, filtered based on the dependency and component metadata. + */ +export function handle_payload( + resolved_payload: unknown[], + dependency: Dependency, + components: ComponentMeta[], + type: "input" | "output", + with_null_state = false +): unknown[] { + if (type === "input" && !with_null_state) { + throw new Error("Invalid code path. Cannot skip state inputs for input."); + } + // data comes from the server with null state values so we skip + if (type === "output" && with_null_state) { + return resolved_payload; + } + + let updated_payload: unknown[] = []; + let payload_index = 0; + for (let i = 0; i < dependency.inputs.length; i++) { + const input_id = dependency.inputs[i]; + const component = components.find((c) => c.id === input_id); + + if (component?.type === "state") { + // input + with_null_state needs us to fill state with null values + if (with_null_state) { + if (resolved_payload.length === dependency.inputs.length) { + const value = resolved_payload[payload_index]; + updated_payload.push(value); + payload_index++; + } else { + updated_payload.push(null); + } + } else { + // this is output & !with_null_state, we skip state inputs + // the server payload always comes with null state values so we move along the payload index + payload_index++; + continue; + } + // input & !with_null_state isn't a case we care about, server needs null + continue; + } else { + const value = resolved_payload[payload_index]; + updated_payload.push(value); + payload_index++; + } + } + + return updated_payload; +} diff --git a/node_modules/@gradio/client/src/helpers/init_helpers.ts b/node_modules/@gradio/client/src/helpers/init_helpers.ts new file mode 100644 index 0000000000000000000000000000000000000000..f4945a5acaf3bdccdfabfadcfc461db10dd1c93f --- /dev/null +++ b/node_modules/@gradio/client/src/helpers/init_helpers.ts @@ -0,0 +1,224 @@ +import type { Config } from "../types"; +import { + CONFIG_ERROR_MSG, + CONFIG_URL, + INVALID_CREDENTIALS_MSG, + LOGIN_URL, + MISSING_CREDENTIALS_MSG, + SPACE_METADATA_ERROR_MSG, + UNAUTHORIZED_MSG +} from "../constants"; +import { Client } from ".."; +import { join_urls, process_endpoint } from "./api_info"; + +/** + * This function is used to resolve the URL for making requests when the app has a root path. + * The root path could be a path suffix like "/app" which is appended to the end of the base URL. Or + * it could be a full URL like "https://abidlabs-test-client-replica--gqf2x.hf.space" which is used when hosting + * Gradio apps on Hugging Face Spaces. + * @param {string} base_url The base URL at which the Gradio server is hosted + * @param {string} root_path The root path, which could be a path suffix (e.g. mounted in FastAPI app) or a full URL (e.g. hosted on Hugging Face Spaces) + * @param {boolean} prioritize_base Whether to prioritize the base URL over the root path. This is used when both the base path and root paths are full URLs. For example, for fetching files the root path should be prioritized, but for making requests, the base URL should be prioritized. + * @returns {string} the resolved URL + */ +export function resolve_root( + base_url: string, + root_path: string, + prioritize_base: boolean +): string { + if (root_path.startsWith("http://") || root_path.startsWith("https://")) { + return prioritize_base ? base_url : root_path; + } + return base_url + root_path; +} + +export async function get_jwt( + space: string, + token: `hf_${string}`, + cookies?: string | null +): Promise { + try { + const r = await fetch(`https://huggingface.co/api/spaces/${space}/jwt`, { + headers: { + Authorization: `Bearer ${token}`, + ...(cookies ? { Cookie: cookies } : {}) + } + }); + + const jwt = (await r.json()).token; + + return jwt || false; + } catch (e) { + return false; + } +} + +export function map_names_to_ids( + fns: Config["dependencies"] +): Record { + let apis: Record = {}; + + fns.forEach(({ api_name, id }) => { + if (api_name) apis[api_name] = id; + }); + return apis; +} + +export async function resolve_config( + this: Client, + endpoint: string +): Promise { + const headers: Record = this.options.hf_token + ? { Authorization: `Bearer ${this.options.hf_token}` } + : {}; + + headers["Content-Type"] = "application/json"; + + if ( + typeof window !== "undefined" && + window.gradio_config && + location.origin !== "http://localhost:9876" && + !window.gradio_config.dev_mode + ) { + const path = window.gradio_config.root; + const config = window.gradio_config; + let config_root = resolve_root(endpoint, config.root, false); + config.root = config_root; + return { ...config, path } as Config; + } else if (endpoint) { + const config_url = join_urls(endpoint, CONFIG_URL); + const response = await this.fetch(config_url, { + headers, + credentials: "include" + }); + + if (response?.status === 401 && !this.options.auth) { + throw new Error(MISSING_CREDENTIALS_MSG); + } else if (response?.status === 401 && this.options.auth) { + throw new Error(INVALID_CREDENTIALS_MSG); + } + if (response?.status === 200) { + let config = await response.json(); + config.path = config.path ?? ""; + config.root = endpoint; + config.dependencies?.forEach((dep: any, i: number) => { + if (dep.id === undefined) { + dep.id = i; + } + }); + return config; + } else if (response?.status === 401) { + throw new Error(UNAUTHORIZED_MSG); + } + throw new Error(CONFIG_ERROR_MSG); + } + + throw new Error(CONFIG_ERROR_MSG); +} + +export async function resolve_cookies(this: Client): Promise { + const { http_protocol, host } = await process_endpoint( + this.app_reference, + this.options.hf_token + ); + + try { + if (this.options.auth) { + const cookie_header = await get_cookie_header( + http_protocol, + host, + this.options.auth, + this.fetch, + this.options.hf_token + ); + + if (cookie_header) this.set_cookies(cookie_header); + } + } catch (e: unknown) { + throw Error((e as Error).message); + } +} + +// separating this from client-bound resolve_cookies so that it can be used in duplicate +export async function get_cookie_header( + http_protocol: string, + host: string, + auth: [string, string], + _fetch: typeof fetch, + hf_token?: `hf_${string}` +): Promise { + const formData = new FormData(); + formData.append("username", auth?.[0]); + formData.append("password", auth?.[1]); + + let headers: { Authorization?: string } = {}; + + if (hf_token) { + headers.Authorization = `Bearer ${hf_token}`; + } + + const res = await _fetch(`${http_protocol}//${host}/${LOGIN_URL}`, { + headers, + method: "POST", + body: formData, + credentials: "include" + }); + + if (res.status === 200) { + return res.headers.get("set-cookie"); + } else if (res.status === 401) { + throw new Error(INVALID_CREDENTIALS_MSG); + } else { + throw new Error(SPACE_METADATA_ERROR_MSG); + } +} + +export function determine_protocol(endpoint: string): { + ws_protocol: "ws" | "wss"; + http_protocol: "http:" | "https:"; + host: string; +} { + if (endpoint.startsWith("http")) { + const { protocol, host, pathname } = new URL(endpoint); + + if (host.endsWith("hf.space")) { + return { + ws_protocol: "wss", + host: host, + http_protocol: protocol as "http:" | "https:" + }; + } + return { + ws_protocol: protocol === "https:" ? "wss" : "ws", + http_protocol: protocol as "http:" | "https:", + host: host + (pathname !== "/" ? pathname : "") + }; + } else if (endpoint.startsWith("file:")) { + // This case is only expected to be used for the Wasm mode (Gradio-lite), + // where users can create a local HTML file using it and open the page in a browser directly via the `file:` protocol. + return { + ws_protocol: "ws", + http_protocol: "http:", + host: "lite.local" // Special fake hostname only used for this case. This matches the hostname allowed in `is_self_host()` in `js/wasm/network/host.ts`. + }; + } + + // default to secure if no protocol is provided + return { + ws_protocol: "wss", + http_protocol: "https:", + host: endpoint + }; +} + +export const parse_and_set_cookies = (cookie_header: string): string[] => { + let cookies: string[] = []; + const parts = cookie_header.split(/,(?=\s*[^\s=;]+=[^\s=;]+)/); + parts.forEach((cookie) => { + const [cookie_name, cookie_value] = cookie.split(";")[0].split("="); + if (cookie_name && cookie_value) { + cookies.push(`${cookie_name.trim()}=${cookie_value.trim()}`); + } + }); + return cookies; +}; diff --git a/node_modules/@gradio/client/src/helpers/spaces.ts b/node_modules/@gradio/client/src/helpers/spaces.ts new file mode 100644 index 0000000000000000000000000000000000000000..50f66281204ab0a004fae6613d0356d6007138c0 --- /dev/null +++ b/node_modules/@gradio/client/src/helpers/spaces.ts @@ -0,0 +1,198 @@ +import { + RUNTIME_URL, + SLEEPTIME_URL, + SPACE_STATUS_ERROR_MSG +} from "../constants"; +import type { SpaceStatusCallback } from "../types"; + +export async function check_space_status( + id: string, + type: "subdomain" | "space_name", + status_callback: SpaceStatusCallback +): Promise { + let endpoint = + type === "subdomain" + ? `https://huggingface.co/api/spaces/by-subdomain/${id}` + : `https://huggingface.co/api/spaces/${id}`; + let response; + let _status; + try { + response = await fetch(endpoint); + _status = response.status; + if (_status !== 200) { + throw new Error(); + } + response = await response.json(); + } catch (e) { + status_callback({ + status: "error", + load_status: "error", + message: SPACE_STATUS_ERROR_MSG, + detail: "NOT_FOUND" + }); + return; + } + + if (!response || _status !== 200) return; + const { + runtime: { stage }, + id: space_name + } = response; + + switch (stage) { + case "STOPPED": + case "SLEEPING": + status_callback({ + status: "sleeping", + load_status: "pending", + message: "Space is asleep. Waking it up...", + detail: stage + }); + + setTimeout(() => { + check_space_status(id, type, status_callback); + }, 1000); // poll for status + break; + case "PAUSED": + status_callback({ + status: "paused", + load_status: "error", + message: + "This space has been paused by the author. If you would like to try this demo, consider duplicating the space.", + detail: stage, + discussions_enabled: await discussions_enabled(space_name) + }); + break; + case "RUNNING": + case "RUNNING_BUILDING": + status_callback({ + status: "running", + load_status: "complete", + message: "", + detail: stage + }); + break; + case "BUILDING": + status_callback({ + status: "building", + load_status: "pending", + message: "Space is building...", + detail: stage + }); + + setTimeout(() => { + check_space_status(id, type, status_callback); + }, 1000); + break; + default: + status_callback({ + status: "space_error", + load_status: "error", + message: "This space is experiencing an issue.", + detail: stage, + discussions_enabled: await discussions_enabled(space_name) + }); + break; + } +} + +const RE_DISABLED_DISCUSSION = + /^(?=[^]*\b[dD]iscussions{0,1}\b)(?=[^]*\b[dD]isabled\b)[^]*$/; +export async function discussions_enabled(space_id: string): Promise { + try { + const r = await fetch( + `https://huggingface.co/api/spaces/${space_id}/discussions`, + { + method: "HEAD" + } + ); + + const error = r.headers.get("x-error-message"); + + if (!r.ok || (error && RE_DISABLED_DISCUSSION.test(error))) return false; + return true; + } catch (e) { + return false; + } +} + +export async function get_space_hardware( + space_id: string, + hf_token?: `hf_${string}` | undefined +): Promise<(typeof hardware_types)[number]> { + const headers: { Authorization?: string } = {}; + if (hf_token) { + headers.Authorization = `Bearer ${hf_token}`; + } + + try { + const res = await fetch( + `https://huggingface.co/api/spaces/${space_id}/${RUNTIME_URL}`, + { headers } + ); + + if (res.status !== 200) + throw new Error("Space hardware could not be obtained."); + + const { hardware } = await res.json(); + + return hardware.current; + } catch (e: any) { + throw new Error(e.message); + } +} + +export async function set_space_timeout( + space_id: string, + timeout: number, + hf_token?: `hf_${string}` +): Promise { + const headers: { Authorization?: string } = {}; + if (hf_token) { + headers.Authorization = `Bearer ${hf_token}`; + } + + const body: { + seconds?: number; + } = { + seconds: timeout + }; + + try { + const res = await fetch( + `https://huggingface.co/api/spaces/${space_id}/${SLEEPTIME_URL}`, + { + method: "POST", + headers: { "Content-Type": "application/json", ...headers }, + body: JSON.stringify(body) + } + ); + + if (res.status !== 200) { + throw new Error( + "Could not set sleep timeout on duplicated Space. Please visit *ADD HF LINK TO SETTINGS* to set a timeout manually to reduce billing charges." + ); + } + + const response = await res.json(); + return response; + } catch (e: any) { + throw new Error(e.message); + } +} + +export const hardware_types = [ + "cpu-basic", + "cpu-upgrade", + "cpu-xl", + "t4-small", + "t4-medium", + "a10g-small", + "a10g-large", + "a10g-largex2", + "a10g-largex4", + "a100-large", + "zero-a10g", + "h100", + "h100x8" +] as const; diff --git a/node_modules/@gradio/client/src/index.ts b/node_modules/@gradio/client/src/index.ts index 98e248e54cc5d72d681ff6dda03db016af70f25f..7717d94f887c3ef86b6b548757e1323ace2a6e21 100644 --- a/node_modules/@gradio/client/src/index.ts +++ b/node_modules/@gradio/client/src/index.ts @@ -1,15 +1,22 @@ -export { - client, - post_data, - upload_files, - duplicate, - api_factory -} from "./client.js"; -export type { SpaceStatus } from "./types.js"; -export { - normalise_file, - FileData, - upload, - get_fetchable_url_or_file, - prepare_files -} from "./upload.js"; +export { Client } from "./client"; + +export { predict } from "./utils/predict"; +export { submit } from "./utils/submit"; +export { upload_files } from "./utils/upload_files"; +export { FileData, upload, prepare_files } from "./upload"; +export { handle_file } from "./helpers/data"; + +export type { + SpaceStatus, + StatusMessage, + Status, + client_return, + UploadResponse, + RenderMessage, + LogMessage, + Payload +} from "./types"; + +// todo: remove in @gradio/client v1.0 +export { client } from "./client"; +export { duplicate_space as duplicate } from "./client"; diff --git a/node_modules/@gradio/client/src/test/api_info.test.ts b/node_modules/@gradio/client/src/test/api_info.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..ad0a7538eaeefd85a816bc80a579a1017d0b3348 --- /dev/null +++ b/node_modules/@gradio/client/src/test/api_info.test.ts @@ -0,0 +1,631 @@ +import { + INVALID_URL_MSG, + QUEUE_FULL_MSG, + SPACE_METADATA_ERROR_MSG +} from "../constants"; +import { beforeAll, afterEach, afterAll, it, expect, describe } from "vitest"; +import { + handle_message, + get_description, + get_type, + process_endpoint, + join_urls, + map_data_to_params +} from "../helpers/api_info"; +import { initialise_server } from "./server"; +import { transformed_api_info } from "./test_data"; + +const server = initialise_server(); + +beforeAll(() => server.listen()); +afterEach(() => server.resetHandlers()); +afterAll(() => server.close()); + +describe("handle_message", () => { + it("should return type 'data' when msg is 'send_data'", () => { + const data = { msg: "send_data" }; + const last_status = "pending"; + const result = handle_message(data, last_status); + expect(result).toEqual({ type: "data" }); + }); + + it("should return type 'hash' when msg is 'send_hash'", () => { + const data = { msg: "send_hash" }; + const last_status = "pending"; + const result = handle_message(data, last_status); + expect(result).toEqual({ type: "hash" }); + }); + + it("should return type 'update' with queue full message when msg is 'queue_full'", () => { + const data = { msg: "queue_full", code: 500, success: false }; + const last_status = "pending"; + const result = handle_message(data, last_status); + expect(result).toEqual({ + type: "update", + status: { + queue: true, + message: QUEUE_FULL_MSG, + stage: "error", + code: 500, + success: false + } + }); + }); + + it("should return type 'heartbeat' when msg is 'heartbeat'", () => { + const data = { msg: "heartbeat" }; + const last_status = "pending"; + const result = handle_message(data, last_status); + expect(result).toEqual({ type: "heartbeat" }); + }); + + it("should return type 'unexpected_error' with error message when msg is 'unexpected_error'", () => { + const data = { msg: "unexpected_error", message: "Something went wrong" }; + const last_status = "pending"; + const result = handle_message(data, last_status); + expect(result).toEqual({ + type: "unexpected_error", + status: { + queue: true, + message: "Something went wrong", + stage: "error", + success: false + } + }); + }); + + it("should return type 'update' with estimation status when msg is 'estimation'", () => { + const data = { + msg: "estimation", + code: 200, + queue_size: 10, + rank: 5, + rank_eta: 60, + success: true + }; + const last_status = "pending"; + const result = handle_message(data, last_status); + expect(result).toEqual({ + type: "update", + status: { + queue: true, + stage: "pending", + code: 200, + size: 10, + position: 5, + eta: 60, + success: true + } + }); + }); + + it("should return type 'update' with progress status when msg is 'progress'", () => { + const data = { + msg: "progress", + code: 200, + progress_data: { current: 50, total: 100 }, + success: true + }; + const last_status = "pending"; + const result = handle_message(data, last_status); + expect(result).toEqual({ + type: "update", + status: { + queue: true, + stage: "pending", + code: 200, + progress_data: { current: 50, total: 100 }, + success: true + } + }); + }); + + it("should return type 'log' with the provided data when msg is 'log'", () => { + const data = { msg: "log", log_data: "Some log message" }; + const last_status = "pending"; + const result = handle_message(data, last_status); + expect(result).toEqual({ + type: "log", + data: { msg: "log", log_data: "Some log message" } + }); + }); + + it("should return type 'generating' with generating status when msg is 'process_generating' and success is true", () => { + const data = { + msg: "process_generating", + success: true, + code: 200, + progress_data: { current: 50, total: 100 }, + average_duration: 120, + output: { result: "Some result" } + }; + const last_status = "pending"; + const result = handle_message(data, last_status); + expect(result).toEqual({ + type: "generating", + status: { + queue: true, + message: null, + stage: "generating", + code: 200, + progress_data: { current: 50, total: 100 }, + eta: 120 + }, + data: { result: "Some result" } + }); + }); + + it("should return type 'update' with error status when msg is 'process_generating' and success is false", () => { + const data = { + msg: "process_generating", + success: false, + code: 500, + progress_data: { current: 50, total: 100 }, + average_duration: 120, + output: { error: "Error" } + }; + const last_status = "pending"; + const result = handle_message(data, last_status); + + expect(result).toEqual({ + type: "generating", + data: null, + status: { + eta: 120, + queue: true, + message: "Error", + stage: "error", + code: 500, + progress_data: { current: 50, total: 100 } + } + }); + }); + + it("should return type 'complete' with success status when msg is 'process_completed' and success is true", () => { + const data = { + msg: "process_completed", + success: true, + code: 200, + progress_data: { current: 100, total: 100 }, + output: { result: "Some result" } + }; + const last_status = "pending"; + const result = handle_message(data, last_status); + expect(result).toEqual({ + type: "complete", + status: { + queue: true, + message: undefined, + stage: "complete", + code: 200, + progress_data: { current: 100, total: 100 } + }, + data: { result: "Some result" } + }); + }); + + it("should return type 'update' with error status when msg is 'process_completed' and success is false", () => { + const data = { + msg: "process_completed", + success: false, + code: 500, + progress_data: { current: 100, total: 100 }, + output: { error: "Some error message" } + }; + const last_status = "pending"; + const result = handle_message(data, last_status); + expect(result).toEqual({ + type: "update", + status: { + queue: true, + message: "Some error message", + stage: "error", + code: 500, + success: false + } + }); + }); + + it("should return type 'update' with pending status when msg is 'process_starts'", () => { + const data = { + msg: "process_starts", + code: 200, + rank: 5, + success: true, + eta: 60 + }; + const last_status = "pending"; + const result = handle_message(data, last_status); + expect(result).toEqual({ + type: "update", + status: { + queue: true, + stage: "pending", + code: 200, + size: 5, + position: 0, + success: true, + eta: 60 + } + }); + }); + + it("should return type 'none' with error status when msg is unknown", () => { + const data = { msg: "unknown" }; + const last_status = "pending"; + const result = handle_message(data, last_status); + expect(result).toEqual({ + type: "none", + status: { stage: "error", queue: true } + }); + }); +}); + +describe("get_description", () => { + it("should return 'array of [file, label] tuples' when serializer is 'GallerySerializable'", () => { + const type = { type: "string", description: "param description" }; + const serializer = "GallerySerializable"; + const result = get_description(type, serializer); + expect(result).toEqual("array of [file, label] tuples"); + }); + + it("should return 'array of strings' when serializer is 'ListStringSerializable'", () => { + const type = { type: "string", description: "param description" }; + const serializer = "ListStringSerializable"; + const result = get_description(type, serializer); + expect(result).toEqual("array of strings"); + }); + + it("should return 'array of files or single file' when serializer is 'FileSerializable'", () => { + const type = { type: "string", description: "param description" }; + const serializer = "FileSerializable"; + const result = get_description(type, serializer); + expect(result).toEqual("array of files or single file"); + }); + + it("should return the type's description when serializer is not 'GallerySerializable', 'ListStringSerializable', or 'FileSerializable'", () => { + const type = { type: "string", description: "param description" }; + const serializer = "SomeOtherSerializer"; + const result = get_description(type, serializer); + expect(result).toEqual(type.description); + }); +}); + +describe("get_type", () => { + it("should return 'string' when type is 'string'", () => { + const type = { type: "string", description: "param description" }; + const component = "Component"; + const serializer = "Serializer"; + const signature_type = "parameter"; + const result = get_type(type, component, serializer, signature_type); + expect(result).toEqual("string"); + }); + + it("should return 'boolean' when type is 'boolean'", () => { + const type = { type: "boolean", description: "param description" }; + const component = "Component"; + const serializer = "Serializer"; + const signature_type = "parameter"; + const result = get_type(type, component, serializer, signature_type); + expect(result).toEqual("boolean"); + }); + + it("should return 'number' when type is 'number'", () => { + const type = { type: "number", description: "param description" }; + const component = "Component"; + const serializer = "Serializer"; + const signature_type = "parameter"; + const result = get_type(type, component, serializer, signature_type); + expect(result).toEqual("number"); + }); + + it("should return 'any' when serializer is 'JSONSerializable'", () => { + const type = { type: "any", description: "param description" }; + const component = "Component"; + const serializer = "JSONSerializable"; + const signature_type = "parameter"; + const result = get_type(type, component, serializer, signature_type); + expect(result).toEqual("any"); + }); + + it("should return 'any' when serializer is 'StringSerializable'", () => { + const type = { type: "any", description: "param description" }; + const component = "Component"; + const serializer = "StringSerializable"; + const signature_type = "parameter"; + const result = get_type(type, component, serializer, signature_type); + expect(result).toEqual("any"); + }); + + it("should return 'string[]' when serializer is 'ListStringSerializable'", () => { + const type = { type: "any", description: "param description" }; + const component = "Component"; + const serializer = "ListStringSerializable"; + const signature_type = "parameter"; + const result = get_type(type, component, serializer, signature_type); + expect(result).toEqual("string[]"); + }); + + it("should return 'Blob | File | Buffer' when component is 'Image' and signature_type is 'parameter'", () => { + const type = { type: "any", description: "param description" }; + const component = "Image"; + const serializer = "Serializer"; + const signature_type = "parameter"; + const result = get_type(type, component, serializer, signature_type); + expect(result).toEqual("Blob | File | Buffer"); + }); + + it("should return 'string' when component is 'Image' and signature_type is 'return'", () => { + const type = { type: "string", description: "param description" }; + const component = "Image"; + const serializer = "Serializer"; + const signature_type = "return"; + const result = get_type(type, component, serializer, signature_type); + expect(result).toEqual("string"); + }); + + it("should return '(Blob | File | Buffer)[]' when serializer is 'FileSerializable' and type is an array and signature_type is 'parameter'", () => { + const type = { type: "array", description: "param description" }; + const component = "Component"; + const serializer = "FileSerializable"; + const signature_type = "parameter"; + const result = get_type(type, component, serializer, signature_type); + expect(result).toEqual("(Blob | File | Buffer)[]"); + }); + + it("should return 'Blob | File | Buffer' when serializer is 'FileSerializable' and type is not an array and signature_type is 'return'", () => { + const type = { type: "any", description: "param description" }; + const component = "Component"; + const serializer = "FileSerializable"; + const signature_type = "return"; + const result = get_type(type, component, serializer, signature_type); + expect(result).toEqual( + "{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}" + ); + }); + + it("should return a FileData object when serializer is 'FileSerializable' and type is not an array and signature_type is 'return'", () => { + const type = { type: "any", description: "param description" }; + const component = "Component"; + const serializer = "FileSerializable"; + const signature_type = "return"; + const result = get_type(type, component, serializer, signature_type); + expect(result).toEqual( + "{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}" + ); + }); + + it("should return '[(Blob | File | Buffer), (string | null)][]' when serializer is 'GallerySerializable' and signature_type is 'parameter'", () => { + const type = { type: "any", description: "param description" }; + const component = "Component"; + const serializer = "GallerySerializable"; + const signature_type = "parameter"; + const result = get_type(type, component, serializer, signature_type); + expect(result).toEqual("[(Blob | File | Buffer), (string | null)][]"); + }); + + it("should return a FileData object when serializer is 'GallerySerializable' and signature_type is 'return'", () => { + const type = { type: "any", description: "param description" }; + const component = "Component"; + const serializer = "GallerySerializable"; + const signature_type = "return"; + const result = get_type(type, component, serializer, signature_type); + expect(result).toEqual( + "[{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}, (string | null))][]" + ); + }); +}); + +describe("process_endpoint", () => { + it("should return space_id, host, ws_protocol, and http_protocol when app_reference is a valid space name", async () => { + const app_reference = "hmb/hello_world"; + const host = "hmb-hello-world.hf.space"; + + const hf_token = "hf_token"; + const expected = { + space_id: app_reference, + host, + ws_protocol: "wss", + http_protocol: "https:" + }; + + const result = await process_endpoint(app_reference, hf_token); + expect(result).toEqual(expected); + }); + + it("should throw an error when fetching space metadata fails", async () => { + const app_reference = "hmb/bye_world"; + const hf_token = "hf_token"; + + try { + await process_endpoint(app_reference, hf_token); + } catch (error) { + expect(error.message).toEqual(SPACE_METADATA_ERROR_MSG); + } + }); + + it("should return the correct data when app_reference is a valid space domain", async () => { + const app_reference = "hmb/hello_world"; + const host = "hmb-hello-world.hf.space"; + + const expected = { + space_id: app_reference, + host, + ws_protocol: "wss", + http_protocol: "https:" + }; + + const result = await process_endpoint("hmb/hello_world"); + expect(result).toEqual(expected); + }); + + it("processes local server URLs correctly", async () => { + const local_url = "http://localhost:7860/gradio"; + const response_local_url = await process_endpoint(local_url); + expect(response_local_url.space_id).toBe(false); + expect(response_local_url.host).toBe("localhost:7860/gradio"); + + const local_url_2 = "http://localhost:7860/gradio/"; + const response_local_url_2 = await process_endpoint(local_url_2); + expect(response_local_url_2.space_id).toBe(false); + expect(response_local_url_2.host).toBe("localhost:7860/gradio"); + }); + + it("handles hugging face space references", async () => { + const space_id = "hmb/hello_world"; + + const response = await process_endpoint(space_id); + expect(response.space_id).toBe(space_id); + expect(response.host).toContain("hf.space"); + }); + + it("handles hugging face domain URLs", async () => { + const app_reference = "https://hmb-hello-world.hf.space/"; + const response = await process_endpoint(app_reference); + expect(response.space_id).toBe("hmb-hello-world"); + expect(response.host).toBe("hmb-hello-world.hf.space"); + }); +}); + +describe("join_urls", () => { + it("joins URLs correctly", () => { + expect(join_urls("http://localhost:7860", "/gradio")).toBe( + "http://localhost:7860/gradio" + ); + expect(join_urls("http://localhost:7860/", "/gradio")).toBe( + "http://localhost:7860/gradio" + ); + expect(join_urls("http://localhost:7860", "app/", "/gradio")).toBe( + "http://localhost:7860/app/gradio" + ); + expect(join_urls("http://localhost:7860/", "/app/", "/gradio/")).toBe( + "http://localhost:7860/app/gradio/" + ); + + expect(join_urls("http://127.0.0.1:8000/app", "/config")).toBe( + "http://127.0.0.1:8000/app/config" + ); + + expect(join_urls("http://127.0.0.1:8000/app/gradio", "/config")).toBe( + "http://127.0.0.1:8000/app/gradio/config" + ); + }); + it("throws an error when the URLs are not valid", () => { + expect(() => join_urls("localhost:7860", "/gradio")).toThrowError( + INVALID_URL_MSG + ); + + expect(() => join_urls("localhost:7860", "/gradio", "app")).toThrowError( + INVALID_URL_MSG + ); + }); +}); + +describe("map_data_params", () => { + let test_data = transformed_api_info; + + test_data.named_endpoints["/predict"].parameters = [ + { + parameter_name: "param1", + parameter_has_default: false, + label: "", + component: "", + serializer: "", + python_type: { + type: "", + description: "" + }, + type: { + type: "", + description: "" + } + }, + { + parameter_name: "param2", + parameter_has_default: false, + label: "", + type: { + type: "", + description: "" + }, + component: "", + serializer: "", + python_type: { + type: "", + description: "" + } + }, + { + parameter_name: "param3", + parameter_has_default: true, + parameter_default: 3, + label: "", + type: { + type: "", + description: "" + }, + component: "", + serializer: "", + python_type: { + type: "", + description: "" + } + } + ]; + + it("should return an array of data when data is an array", () => { + const data = [1, 2]; + + const result = map_data_to_params(data, transformed_api_info); + expect(result).toEqual(data); + }); + + it("should return the data when too many arguments are provided for the endpoint", () => { + const data = [1, 2, 3, 4]; + + const result = map_data_to_params(data, transformed_api_info); + expect(result).toEqual(data); + }); + + it("should return an array of resolved data when data is an object", () => { + const data = { + param1: 1, + param2: 2, + param3: 3 + }; + + const result = map_data_to_params(data, transformed_api_info); + expect(result).toEqual([1, 2, 3]); + }); + + it("should use the default value when a keyword argument is not provided and has a default value", () => { + const data = { + param1: 1, + param2: 2 + }; + + const result = map_data_to_params(data, transformed_api_info); + expect(result).toEqual([1, 2, 3]); + }); + + it("should throw an error when an invalid keyword argument is provided", () => { + const data = { + param1: 1, + param2: 2, + param3: 3, + param4: 4 + }; + + expect(() => map_data_to_params(data, transformed_api_info)).toThrowError( + "Parameter `param4` is not a valid keyword argument. Please refer to the API for usage." + ); + }); + + it("should throw an error when no value is provided for a required parameter", () => { + const data = {}; + + expect(() => map_data_to_params(data, transformed_api_info)).toThrowError( + "No value provided for required parameter: param1" + ); + }); +}); diff --git a/node_modules/@gradio/client/src/test/data.test.ts b/node_modules/@gradio/client/src/test/data.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..3798c89679d95db601afdbb9791ffc1d2dbc440c --- /dev/null +++ b/node_modules/@gradio/client/src/test/data.test.ts @@ -0,0 +1,453 @@ +import { describe, it, expect, vi, afterEach } from "vitest"; +import { + update_object, + walk_and_store_blobs, + skip_queue, + post_message, + handle_file, + handle_payload +} from "../helpers/data"; +import { config_response, endpoint_info } from "./test_data"; +import { BlobRef, Command } from "../types"; +import { FileData } from "../upload"; + +const IS_NODE = process.env.TEST_MODE === "node"; + +describe("walk_and_store_blobs", () => { + it("should convert a Buffer to a Blob", async () => { + const buffer = Buffer.from("test data"); + const parts = await walk_and_store_blobs(buffer, "text"); + + expect(parts).toHaveLength(1); + expect(parts[0].blob).toBeInstanceOf(Blob); + }); + + it("should return a Blob when passed a Blob", async () => { + const blob = new Blob(["test data"]); + const parts = await walk_and_store_blobs( + blob, + undefined, + [], + true, + endpoint_info + ); + + expect(parts[0].blob).toBeInstanceOf(Blob); + }); + + it("should handle arrays", async () => { + const image = new Blob([]); + const parts = await walk_and_store_blobs([image]); + + expect(parts).toHaveLength(1); + expect(parts[0].blob).toBeInstanceOf(Blob); + expect(parts[0].path).toEqual(["0"]); + }); + + it("should handle deep structures", async () => { + const image = new Blob([]); + const parts = await walk_and_store_blobs({ a: { b: { data: { image } } } }); + + expect(parts).toHaveLength(1); + expect(parts[0].blob).toBeInstanceOf(Blob); + expect(parts[0].path).toEqual(["a", "b", "data", "image"]); + }); + + it("should handle deep structures with arrays", async () => { + const image = new Blob([]); + const parts = await walk_and_store_blobs({ + a: [ + { + b: [ + { + data: [ + { + image + } + ] + } + ] + } + ] + }); + + expect(parts[0].blob).toBeInstanceOf(Blob); + }); + + it("should handle deep structures with arrays (with equality check)", async () => { + const image = new Blob([]); + + const obj = { + a: [ + { + b: [ + { + data: [[image], image, [image, [image]]] + } + ] + } + ] + }; + const parts = await walk_and_store_blobs(obj); + + async function map_path(obj: Record, parts: BlobRef[]) { + const { path, blob } = parts[parts.length - 1]; + let ref = obj; + path.forEach((p) => (ref = ref[p])); + + // since ref is a Blob and blob is a Blob, we deep equal check the two buffers instead + if (ref instanceof Blob && blob instanceof Blob) { + const refBuffer = Buffer.from(await ref.arrayBuffer()); + const blobBuffer = Buffer.from(await blob.arrayBuffer()); + return refBuffer.equals(blobBuffer); + } + + return ref === blob; + } + + expect(parts[0].blob).toBeInstanceOf(Blob); + expect(map_path(obj, parts)).toBeTruthy(); + }); + + it("should handle buffer instances and return a BlobRef", async () => { + const buffer = Buffer.from("test"); + const parts = await walk_and_store_blobs(buffer, undefined, ["blob"]); + + expect(parts).toHaveLength(1); + expect(parts[0].blob).toBeInstanceOf(Blob); + expect(parts[0].path).toEqual(["blob"]); + }); + + it("should handle buffer instances with a path and return a BlobRef with the path", async () => { + const buffer = Buffer.from("test data"); + const parts = await walk_and_store_blobs(buffer); + + expect(parts).toHaveLength(1); + expect(parts[0].path).toEqual([]); + expect(parts[0].blob).toBeInstanceOf(Blob); + }); + + it("should convert an object with deep structures to BlobRefs", async () => { + const param = { + a: { + b: { + data: { + image: Buffer.from("test image") + } + } + } + }; + const parts = await walk_and_store_blobs(param); + + expect(parts).toHaveLength(1); + expect(parts[0].path).toEqual(["a", "b", "data", "image"]); + expect(parts[0].blob).toBeInstanceOf(Blob); + }); +}); +describe("update_object", () => { + it("should update the value of a nested property", () => { + const obj = { + a: { + b: { + c: "old value" + } + } + }; + + const stack = ["a", "b", "c"]; + const new_val = "new value"; + + update_object(obj, new_val, stack); + + expect(obj.a.b.c).toBe(new_val); + }); + + it("should throw an error for invalid key type", () => { + const obj = { + a: { + b: { + c: "value" + } + } + }; + + const stack = ["a", "b", true]; + const newValue = "new value"; + + expect(() => { + // @ts-ignore + update_object(obj, newValue, stack); + }).toThrowError("Invalid key type"); + }); +}); + +describe("skip_queue", () => { + const id = 0; + const config = config_response; + + it("should not skip queue when global and dependency queue is enabled", () => { + config.enable_queue = true; + config.dependencies.find((dep) => dep.id === id)!.queue = true; + + const result = skip_queue(id, config_response); + + expect(result).toBe(false); + }); + + it("should not skip queue when global queue is disabled and dependency queue is enabled", () => { + config.enable_queue = false; + config.dependencies.find((dep) => dep.id === id)!.queue = true; + + const result = skip_queue(id, config_response); + + expect(result).toBe(false); + }); + + it("should should skip queue when global queue and dependency queue is disabled", () => { + config.enable_queue = false; + config.dependencies.find((dep) => dep.id === id)!.queue = false; + + const result = skip_queue(id, config_response); + + expect(result).toBe(true); + }); + + it("should should skip queue when global queue is enabled and dependency queue is disabled", () => { + config.enable_queue = true; + config.dependencies.find((dep) => dep.id === id)!.queue = false; + + const result = skip_queue(id, config_response); + + expect(result).toBe(true); + }); +}); + +describe("post_message", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("should send a message to the parent window and resolve with received data", async () => { + const test_data = { key: "value" }; + const test_origin = "https://huggingface.co"; + + const post_message_mock = vi.fn(); + + global.window = { + // @ts-ignore + parent: { + postMessage: post_message_mock + } + }; + + const message_channel_mock = { + port1: { + onmessage: (handler) => { + onmessage = handler; + }, + close: vi.fn() + }, + port2: {} + }; + + vi.stubGlobal("MessageChannel", function () { + this.port1 = message_channel_mock.port1; + this.port2 = message_channel_mock.port2; + return this; + }); + + const promise = post_message(test_data, test_origin); + + if (message_channel_mock.port1.onmessage) { + message_channel_mock.port1.onmessage({ data: test_data }); + } + + await expect(promise).resolves.toEqual(test_data); + expect(post_message_mock).toHaveBeenCalledWith(test_data, test_origin, [ + message_channel_mock.port2 + ]); + }); +}); + +describe("handle_file", () => { + it("should handle a Blob object and return the blob", () => { + const blob = new Blob(["test data"], { type: "image/png" }); + const result = handle_file(blob) as FileData; + + expect(result).toBe(blob); + }); + + it("should handle a Buffer object and return it as a blob", () => { + const buffer = Buffer.from("test data"); + const result = handle_file(buffer) as FileData; + expect(result).toBeInstanceOf(Blob); + }); + it("should handle a local file path and return a Command object", () => { + const file_path = "./owl.png"; + const result = handle_file(file_path) as Command; + expect(result).toBeInstanceOf(Command); + expect(result).toEqual({ + type: "command", + command: "upload_file", + meta: { path: "./owl.png", name: "./owl.png", orig_path: "./owl.png" }, + fileData: undefined + }); + }); + + it("should handle a File object and return it as FileData", () => { + if (IS_NODE) { + return; + } + const file = new File(["test image"], "test.png", { type: "image/png" }); + const result = handle_file(file) as FileData; + expect(result.path).toBe("test.png"); + expect(result.orig_name).toBe("test.png"); + expect(result.blob).toBeInstanceOf(Blob); + expect(result.size).toBe(file.size); + expect(result.mime_type).toBe("image/png"); + expect(result.meta).toEqual({ _type: "gradio.FileData" }); + }); + + it("should throw an error for invalid input", () => { + const invalid_input = 123; + + expect(() => { + // @ts-ignore + handle_file(invalid_input); + }).toThrowError( + "Invalid input: must be a URL, File, Blob, or Buffer object." + ); + }); +}); + +describe("handle_payload", () => { + it("should return an input payload with null in place of `state` when with_null_state is true", () => { + const resolved_payload = [2]; + const dependency = { + inputs: [1, 2] + }; + const components = [ + { id: 1, type: "number" }, + { id: 2, type: "state" } + ]; + const with_null_state = true; + const result = handle_payload( + resolved_payload, + // @ts-ignore + dependency, + components, + "input", + with_null_state + ); + expect(result).toEqual([2, null]); + }); + it("should return an input payload with null in place of two `state` components when with_null_state is true", () => { + const resolved_payload = ["hello", "goodbye"]; + const dependency = { + inputs: [1, 2, 3, 4] + }; + const components = [ + { id: 1, type: "textbox" }, + { id: 2, type: "state" }, + { id: 3, type: "textbox" }, + { id: 4, type: "state" } + ]; + const with_null_state = true; + const result = handle_payload( + resolved_payload, + // @ts-ignore + dependency, + components, + "input", + with_null_state + ); + expect(result).toEqual(["hello", null, "goodbye", null]); + }); + + it("should return an output payload without the state component value when with_null_state is false", () => { + const resolved_payload = ["hello", null]; + const dependency = { + inputs: [2, 3] + }; + const components = [ + { id: 2, type: "textbox" }, + { id: 3, type: "state" } + ]; + const with_null_state = false; + const result = handle_payload( + resolved_payload, + // @ts-ignore + dependency, + components, + "output", + with_null_state + ); + expect(result).toEqual(["hello"]); + }); + + it("should return an ouput payload without the two state component values when with_null_state is false", () => { + const resolved_payload = ["hello", null, "world", null]; + const dependency = { + inputs: [2, 3, 4, 5] + }; + const components = [ + { id: 2, type: "textbox" }, + { id: 3, type: "state" }, + { id: 4, type: "textbox" }, + { id: 5, type: "state" } + ]; + const with_null_state = false; + const result = handle_payload( + resolved_payload, + // @ts-ignore + dependency, + components, + "output", + with_null_state + ); + expect(result).toEqual(["hello", "world"]); + }); + + it("should return an ouput payload with the two state component values when with_null_state is true", () => { + const resolved_payload = ["hello", null, "world", null]; + const dependency = { + inputs: [2, 3, 4, 5] + }; + const components = [ + { id: 2, type: "textbox" }, + { id: 3, type: "state" }, + { id: 4, type: "textbox" }, + { id: 5, type: "state" } + ]; + const with_null_state = true; + const result = handle_payload( + resolved_payload, + // @ts-ignore + dependency, + components, + "output", + with_null_state + ); + expect(result).toEqual(["hello", null, "world", null]); + }); + + it("should return the same payload where no state components are defined", () => { + const resolved_payload = ["hello", "world"]; + const dependency = { + inputs: [2, 3] + }; + const components = [ + { id: 2, type: "textbox" }, + { id: 3, type: "textbox" } + ]; + const with_null_state = true; + const result = handle_payload( + resolved_payload, + // @ts-ignore + dependency, + components, + with_null_state + ); + expect(result).toEqual(["hello", "world"]); + }); +}); diff --git a/node_modules/@gradio/client/src/test/handlers.ts b/node_modules/@gradio/client/src/test/handlers.ts new file mode 100644 index 0000000000000000000000000000000000000000..308b8846bc441714ef9bf6caa39245e6415f8458 --- /dev/null +++ b/node_modules/@gradio/client/src/test/handlers.ts @@ -0,0 +1,693 @@ +import { HttpResponse, http, RequestHandler } from "msw"; +import { + HOST_URL, + API_INFO_URL, + CONFIG_URL, + RUNTIME_URL, + SLEEPTIME_URL, + UPLOAD_URL, + BROKEN_CONNECTION_MSG, + LOGIN_URL +} from "../constants"; +import { + response_api_info, + config_response, + whoami_response, + duplicate_response, + hardware_sleeptime_response, + discussions_response, + runtime_response +} from "./test_data"; + +const root_url = "https://huggingface.co"; + +export const direct_space_url = "https://hmb-hello-world.hf.space"; +const private_space_url = "https://hmb-secret-world.hf.space"; +const private_auth_space_url = "https://hmb-private-auth-space.hf.space"; + +const server_error_space_url = "https://hmb-server-error.hf.space"; +const upload_server_test_space_url = "https://hmb-server-test.hf.space"; +const auth_app_space_url = "https://hmb-auth-space.hf.space"; +const unauth_app_space_url = "https://hmb-unauth-space.hf.space"; +const invalid_auth_space_url = "https://hmb-invalid-auth-space.hf.space"; + +const server_error_reference = "hmb/server_error"; +const app_reference = "hmb/hello_world"; +const broken_app_reference = "hmb/bye_world"; +const duplicate_app_reference = "gradio/hello_world"; +const private_app_reference = "hmb/secret_world"; +const server_test_app_reference = "hmb/server_test"; +const auth_app_reference = "hmb/auth_space"; +const unauth_app_reference = "hmb/unauth_space"; +const invalid_auth_app_reference = "hmb/invalid_auth_space"; +const private_auth_app_reference = "hmb/private_auth_space"; + +export const handlers: RequestHandler[] = [ + // /host requests + http.get(`${root_url}/api/spaces/${app_reference}/${HOST_URL}`, () => { + return new HttpResponse( + JSON.stringify({ + subdomain: "hmb-hello-world", + host: "https://hmb-hello-world.hf.space" + }), + { + status: 200, + headers: { + "Content-Type": "application/json" + } + } + ); + }), + http.get(`${root_url}/api/spaces/${broken_app_reference}/${HOST_URL}`, () => { + return new HttpResponse(null, { + status: 404, + headers: { + "Content-Type": "application/json", + hf_token: "hf_123" + } + }); + }), + http.get( + `${root_url}/api/spaces/${private_auth_app_reference}/${HOST_URL}`, + () => { + return new HttpResponse( + JSON.stringify({ + subdomain: "hmb-private-auth-space", + host: "https://hmb-private-auth-space.hf.space" + }), + { + status: 200, + headers: { + "Content-Type": "application/json" + } + } + ); + } + ), + http.get( + `${root_url}/api/spaces/${private_app_reference}/${HOST_URL}`, + ({ request }) => { + const token = request.headers.get("authorization")?.substring(7); + + if (!token || token !== "hf_123") { + return new HttpResponse(null, { + status: 401, + headers: { + "Content-Type": "application/json" + } + }); + } + + return new HttpResponse( + JSON.stringify({ + subdomain: private_app_reference, + host: private_space_url + }), + { + status: 200, + headers: { + "Content-Type": "application/json" + } + } + ); + } + ), + http.get( + `${root_url}/api/spaces/${server_error_reference}/${HOST_URL}`, + () => { + return new HttpResponse( + JSON.stringify({ + subdomain: "hmb-server-test", + host: "https://hmb-server-test.hf.space" + }), + { + status: 200, + headers: { + "Content-Type": "application/json" + } + } + ); + } + ), + http.get( + `${root_url}/api/spaces/${server_test_app_reference}/${HOST_URL}`, + () => { + return new HttpResponse( + JSON.stringify({ + subdomain: "hmb-server-test", + host: "https://hmb-server-test.hf.space" + }), + { + status: 200, + headers: { + "Content-Type": "application/json" + } + } + ); + } + ), + http.get(`${root_url}/api/spaces/${auth_app_reference}/${HOST_URL}`, () => { + return new HttpResponse( + JSON.stringify({ + subdomain: "hmb-auth-space", + host: "https://hmb-auth-space.hf.space" + }), + { + status: 200, + headers: { + "Content-Type": "application/json" + } + } + ); + }), + http.get( + `${root_url}/api/spaces/${invalid_auth_app_reference}/${HOST_URL}`, + () => { + return new HttpResponse( + JSON.stringify({ + subdomain: "hmb-invalid-auth-space", + host: "https://hmb-invalid-auth-space.hf.space" + }), + { + status: 200, + headers: { + "Content-Type": "application/json" + } + } + ); + } + ), + http.get( + `${root_url}/api/spaces/${duplicate_app_reference}/${HOST_URL}`, + () => { + return new HttpResponse( + JSON.stringify({ + subdomain: "gradio-hello-world", + host: "https://gradio-hello-world.hf.space" + }), + { + status: 200, + headers: { + "Content-Type": "application/json" + } + } + ); + } + ), + http.get(`${root_url}/api/spaces/${unauth_app_reference}/${HOST_URL}`, () => { + return new HttpResponse( + JSON.stringify({ + subdomain: "hmb-unath-space", + host: "https://hmb-unauth-space.hf.space" + }), + { + status: 200, + headers: { + "Content-Type": "application/json" + } + } + ); + }), + // /info requests + http.get(`${direct_space_url}/${API_INFO_URL}`, () => { + return new HttpResponse(JSON.stringify(response_api_info), { + status: 200, + headers: { + "Content-Type": "application/json" + } + }); + }), + http.get(`${upload_server_test_space_url}/${API_INFO_URL}`, () => { + return new HttpResponse(JSON.stringify(response_api_info), { + status: 200, + headers: { + "Content-Type": "application/json" + } + }); + }), + http.get(`${private_space_url}/${API_INFO_URL}`, () => { + return new HttpResponse(JSON.stringify(response_api_info), { + status: 200, + headers: { + "Content-Type": "application/json" + } + }); + }), + http.get(`${server_error_space_url}/${API_INFO_URL}`, () => { + return new HttpResponse(JSON.stringify(response_api_info), { + status: 200, + headers: { + "Content-Type": "application/json" + } + }); + }), + http.get(`${auth_app_space_url}/${API_INFO_URL}`, async () => { + return new HttpResponse(JSON.stringify(response_api_info), { + status: 200, + headers: { + "Content-Type": "application/json" + } + }); + }), + http.get(`${private_auth_space_url}/${API_INFO_URL}`, async () => { + return new HttpResponse(JSON.stringify(response_api_info), { + status: 200, + headers: { + "Content-Type": "application/json" + } + }); + }), + // /config requests + http.get(`${direct_space_url}/${CONFIG_URL}`, () => { + return new HttpResponse(JSON.stringify(config_response), { + status: 200, + headers: { + "Content-Type": "application/json" + } + }); + }), + http.get(`${private_space_url}/${CONFIG_URL}`, () => { + return new HttpResponse( + JSON.stringify({ + ...config_response, + root: "https://hmb-secret-world.hf.space" + }), + { + status: 200, + headers: { + "Content-Type": "application/json" + } + } + ); + }), + http.get(`${upload_server_test_space_url}/${CONFIG_URL}`, () => { + return new HttpResponse( + JSON.stringify({ + ...config_response, + root: "https://hmb-server-test.hf.space" + }), + { + status: 200, + headers: { + "Content-Type": "application/json" + } + } + ); + }), + http.get(`${private_auth_space_url}/${CONFIG_URL}`, () => { + return new HttpResponse( + JSON.stringify({ + ...config_response, + root: "https://hmb-private-auth-space.hf.space" + }), + { + status: 200, + headers: { + "Content-Type": "application/json" + } + } + ); + }), + http.get(`${direct_space_url}/${CONFIG_URL}`, () => { + return new HttpResponse(JSON.stringify(config_response), { + status: 500, + headers: { + "Content-Type": "application/json" + } + }); + }), + http.get(`${server_error_space_url}/${CONFIG_URL}`, () => { + return new HttpResponse(JSON.stringify(config_response), { + status: 200, + headers: { + "Content-Type": "application/json" + } + }); + }), + http.get(`${invalid_auth_space_url}/${CONFIG_URL}`, () => { + return new HttpResponse(JSON.stringify({ detail: "Unauthorized" }), { + status: 401, + headers: { + "Content-Type": "application/json" + } + }); + }), + http.get(`${auth_app_space_url}/${CONFIG_URL}`, ({ request }) => { + return new HttpResponse( + JSON.stringify({ + ...config_response, + root: "https://hmb-auth-space.hf.space", + space_id: "hmb/auth_space" + }), + { + status: 200, + headers: { + "Content-Type": "application/json" + } + } + ); + }), + http.get(`${unauth_app_space_url}/${CONFIG_URL}`, () => { + return new HttpResponse( + JSON.stringify({ + detail: "Unauthorized" + }), + { + status: 401, + headers: { + "Content-Type": "application/json" + } + } + ); + }), + // /whoami requests + http.get(`${root_url}/api/whoami-v2`, () => { + return new HttpResponse(JSON.stringify(whoami_response), { + status: 200, + headers: { + "Content-Type": "application/json", + "hf-token": "hf_123" + } + }); + }), + // /duplicate requests + http.post( + `${root_url}/api/spaces/${duplicate_app_reference}/duplicate`, + ({ request }) => { + if (request.headers.get("authorization")?.substring(7) !== "hf_123") { + throw new HttpResponse(null, { + status: 401, + headers: { + "Content-Type": "application/json" + } + }); + } + return new HttpResponse(JSON.stringify(duplicate_response), { + status: 200, + headers: { + "Content-Type": "application/json" + } + }); + } + ), + // /sleeptime requests + http.post(`${root_url}/api/spaces/${app_reference}/${SLEEPTIME_URL}`, () => { + return new HttpResponse(JSON.stringify(hardware_sleeptime_response), { + status: 200, + headers: { + "Content-Type": "application/json" + } + }); + }), + http.post( + `${root_url}/api/spaces/${server_test_app_reference}/${SLEEPTIME_URL}`, + () => { + throw new HttpResponse(null, { + status: 500, + headers: { + "Content-Type": "application/json" + } + }); + } + ), + // /runtime requests + http.get( + `${root_url}/api/spaces/${broken_app_reference}/${RUNTIME_URL}`, + () => { + return new HttpResponse(null, { + status: 404, + headers: { + "Content-Type": "application/json" + } + }); + } + ), + http.get(`${root_url}/api/spaces/${app_reference}/${RUNTIME_URL}`, () => { + return new HttpResponse(JSON.stringify(hardware_sleeptime_response), { + status: 200, + headers: { + "Content-Type": "application/json" + } + }); + }), + // queue requests + http.get(`${direct_space_url}/queue/data`, () => { + return new HttpResponse(JSON.stringify({ event_id: "123" }), { + status: 200, + headers: { + "Content-Type": "application/json" + } + }); + }), + http.post(`${direct_space_url}/queue/join`, () => { + return new HttpResponse(JSON.stringify({ event_id: "123" }), { + status: 200, + headers: { + "Content-Type": "application/json" + } + }); + }), + // upload requests + http.post(`${direct_space_url}/${UPLOAD_URL}`, () => { + return new HttpResponse(JSON.stringify(["lion.jpg"]), { + status: 200, + headers: { + "Content-Type": "application/json" + } + }); + }), + http.post(`${upload_server_test_space_url}/${UPLOAD_URL}`, () => { + throw new HttpResponse(JSON.parse("Internal Server Error"), { + status: 200, + headers: { + "Content-Type": "application/json" + } + }); + }), + // discussions requests + http.head(`${root_url}/api/spaces/${app_reference}/discussions`, () => { + return new HttpResponse(JSON.stringify(discussions_response), { + status: 200, + headers: { + "Content-Type": "application/json" + } + }); + }), + http.head( + `${root_url}/api/spaces/${broken_app_reference}/discussions`, + () => { + throw new HttpResponse( + JSON.parse("Discussions are disabled for this repo"), + { + status: 403, + headers: { + "Content-Type": "application/json" + } + } + ); + } + ), + // space requests + http.get(`${root_url}/api/spaces/${app_reference}`, () => { + return new HttpResponse( + JSON.stringify({ id: app_reference, runtime: runtime_response }), + { + status: 200, + headers: { + "Content-Type": "application/json" + } + } + ); + }), + http.get(`${root_url}/api/spaces/hmb/paused_space`, () => { + return new HttpResponse( + JSON.stringify({ + id: app_reference, + runtime: { ...runtime_response, stage: "PAUSED" } + }), + { + status: 200, + headers: { + "Content-Type": "application/json" + } + } + ); + }), + http.get(`${root_url}/api/spaces/hmb/building_space`, () => { + return new HttpResponse( + JSON.stringify({ + id: app_reference, + runtime: { ...runtime_response, stage: "BUILDING" } + }), + { + status: 200, + headers: { + "Content-Type": "application/json" + } + } + ); + }), + http.get(`${root_url}/api/spaces/hmb/stopped_space`, () => { + return new HttpResponse( + JSON.stringify({ + id: app_reference, + runtime: { ...runtime_response, stage: "STOPPED" } + }), + { + status: 200, + headers: { + "Content-Type": "application/json" + } + } + ); + }), + http.get(`${root_url}/api/spaces/hmb/failed_space`, () => { + throw new HttpResponse(null, { + status: 500, + headers: { + "Content-Type": "application/json" + } + }); + }), + http.get(`${root_url}/api/spaces/${unauth_app_reference}`, () => { + return new HttpResponse( + JSON.stringify({ + id: unauth_app_reference, + runtime: { ...runtime_response } + }), + { + status: 200, + headers: { + "Content-Type": "application/json" + } + } + ); + }), + // jwt requests + http.get(`${root_url}/api/spaces/${app_reference}/jwt`, () => { + return new HttpResponse( + JSON.stringify({ + token: "jwt_123" + }), + { + status: 200, + headers: { + "Content-Type": "application/json" + } + } + ); + }), + http.get(`${root_url}/api/spaces/${broken_app_reference}/jwt`, () => { + return new HttpResponse(null, { + status: 500, + headers: { + "Content-Type": "application/json" + } + }); + }), + // post_data requests + http.post(`${direct_space_url}`, () => { + return new HttpResponse(JSON.stringify({}), { + status: 200, + headers: { + "Content-Type": "application/json" + } + }); + }), + http.post(`${private_space_url}`, () => { + return new HttpResponse(JSON.stringify(BROKEN_CONNECTION_MSG), { + status: 500, + headers: { + "Content-Type": "application/json" + } + }); + }), + // heartbeat requests + http.get(`*/heartbeat/*`, () => { + return new HttpResponse(null, { + status: 200, + headers: { + "Content-Type": "application/json" + } + }); + }), + // login requests + http.post(`${auth_app_space_url}/${LOGIN_URL}`, async ({ request }) => { + let username; + let password; + + await request.formData().then((data) => { + username = data.get("username"); + password = data.get("password"); + }); + + if (username === "admin" && password === "pass1234") { + return new HttpResponse( + JSON.stringify({ + success: true + }), + { + status: 200, + headers: { + "Content-Type": "application/json", + "Set-Cookie": + "access-token-123=abc; HttpOnly; Path=/; SameSite=none; Secure", + // @ts-ignore - multiple Set-Cookie headers are returned + "Set-Cookie": + "access-token-unsecure-123=abc; HttpOnly; Path=/; SameSite=none; Secure" + } + } + ); + } + + return new HttpResponse(null, { + status: 401, + headers: { + "Content-Type": "application/json" + } + }); + }), + http.post(`${invalid_auth_space_url}/${LOGIN_URL}`, async () => { + return new HttpResponse(null, { + status: 401, + headers: { + "Content-Type": "application/json" + } + }); + }), + http.post(`${private_auth_space_url}/${LOGIN_URL}`, async ({ request }) => { + let username; + let password; + + await request.formData().then((data) => { + username = data.get("username"); + password = data.get("password"); + }); + + if (username === "admin" && password === "pass1234") { + return new HttpResponse( + JSON.stringify({ + success: true + }), + { + status: 200, + headers: { + "Content-Type": "application/json", + "Set-Cookie": + "access-token-123=abc; HttpOnly; Path=/; SameSite=none; Secure", + // @ts-ignore - multiple Set-Cookie headers are returned + "Set-Cookie": + "access-token-unsecure-123=abc; HttpOnly; Path=/; SameSite=none; Secure" + } + } + ); + } + + return new HttpResponse(null, { + status: 401, + headers: { + "Content-Type": "application/json" + } + }); + }) +]; diff --git a/node_modules/@gradio/client/src/test/init.test.ts b/node_modules/@gradio/client/src/test/init.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..b2407009544da893bd1417548ae30166b9b183ba --- /dev/null +++ b/node_modules/@gradio/client/src/test/init.test.ts @@ -0,0 +1,139 @@ +import { + describe, + beforeAll, + afterEach, + afterAll, + test, + expect, + vi +} from "vitest"; + +import { Client, client, duplicate } from ".."; +import { transformed_api_info, config_response } from "./test_data"; +import { initialise_server } from "./server"; +import { CONFIG_ERROR_MSG, SPACE_METADATA_ERROR_MSG } from "../constants"; + +const app_reference = "hmb/hello_world"; +const broken_app_reference = "hmb/bye_world"; +const direct_app_reference = "https://hmb-hello-world.hf.space"; +const secret_direct_app_reference = "https://hmb-secret-world.hf.space"; + +const server = initialise_server(); + +beforeAll(() => server.listen()); +afterEach(() => server.resetHandlers()); +afterAll(() => server.close()); + +describe("Client class", () => { + describe("initialisation", () => { + test("backwards compatibility of client using deprecated syntax", async () => { + const app = await client(app_reference); + expect(app.config).toEqual(config_response); + }); + test("connecting to a running app with a space reference", async () => { + const app = await Client.connect(app_reference); + expect(app.config).toEqual(config_response); + }); + + test("connecting to a running app with a direct app URL", async () => { + const app = await Client.connect(direct_app_reference); + expect(app.config).toEqual(config_response); + }); + + test("connecting successfully to a private running app with a space reference", async () => { + const app = await Client.connect("hmb/secret_world", { + hf_token: "hf_123" + }); + + expect(app.config).toEqual({ + ...config_response, + root: "https://hmb-secret-world.hf.space" + }); + }); + + test("connecting successfully to a private running app with a direct app URL ", async () => { + const app = await Client.connect(secret_direct_app_reference, { + hf_token: "hf_123" + }); + + expect(app.config).toEqual({ + ...config_response, + root: "https://hmb-secret-world.hf.space" + }); + }); + + test("unsuccessfully attempting to connect to a private running app", async () => { + await expect( + Client.connect("hmb/secret_world", { + hf_token: "hf_bad_token" + }) + ).rejects.toThrowError(SPACE_METADATA_ERROR_MSG); + }); + + test("viewing the api info of a running app", async () => { + const app = await Client.connect(app_reference); + expect(await app.view_api()).toEqual(transformed_api_info); + }); + + test("viewing the api info of a non-existent app", async () => { + const app = Client.connect(broken_app_reference); + await expect(app).rejects.toThrowError(); + }); + }); + + describe("duplicate", () => { + test("backwards compatibility of duplicate using deprecated syntax", async () => { + const app = await duplicate("gradio/hello_world", { + hf_token: "hf_123", + private: true, + hardware: "cpu-basic" + }); + + expect(app.config).toEqual(config_response); + }); + + test("creating a duplicate of a running app", async () => { + const duplicate = await Client.duplicate("gradio/hello_world", { + hf_token: "hf_123", + private: true, + hardware: "cpu-basic" + }); + + expect(duplicate.config).toEqual(config_response); + }); + + test("creating a duplicate of a running app without a token", async () => { + const duplicate = Client.duplicate("gradio/hello_world", { + private: true, + hardware: "cpu-basic" + }); + + await expect(duplicate).rejects.toThrow("Error: Unauthorized"); + }); + + test("creating a duplicate of a broken app", async () => { + const duplicate = Client.duplicate(broken_app_reference); + + await expect(duplicate).rejects.toThrow(SPACE_METADATA_ERROR_MSG); + }); + }); + + describe("overriding the Client class", () => { + test("overriding methods on the Client class", async () => { + const mocked_fetch = vi.fn( + (input: RequestInfo | URL, init?: RequestInit): Promise => { + return Promise.resolve( + new Response(JSON.stringify({ data: "test" })) + ); + } + ); + + class CustomClient extends Client { + fetch = mocked_fetch; + } + + await CustomClient.connect("hmb/hello_world"); + expect(mocked_fetch).toHaveBeenCalled(); + }); + }); +}); diff --git a/node_modules/@gradio/client/src/test/init_helpers.test.ts b/node_modules/@gradio/client/src/test/init_helpers.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..2462dd4ea2691e59fc71e817b81839dfb4b9e672 --- /dev/null +++ b/node_modules/@gradio/client/src/test/init_helpers.test.ts @@ -0,0 +1,146 @@ +import { + resolve_root, + get_jwt, + determine_protocol, + parse_and_set_cookies +} from "../helpers/init_helpers"; +import { initialise_server } from "./server"; +import { beforeAll, afterEach, afterAll, it, expect, describe } from "vitest"; +import { Client } from "../client"; +import { INVALID_CREDENTIALS_MSG, MISSING_CREDENTIALS_MSG } from "../constants"; + +const server = initialise_server(); + +beforeAll(() => server.listen()); +afterEach(() => server.resetHandlers()); +afterAll(() => server.close()); + +describe("resolve_root", () => { + it('should return the base URL if the root path starts with "http://"', () => { + const base_url = "https://huggingface.co"; + const root_path = "https://hmb-hello-world.hf.space"; + const prioritize_base = true; + const result = resolve_root(base_url, root_path, prioritize_base); + expect(result).toBe(base_url); + }); + + it('should return the base URL if the root path starts with "https://"', () => { + const base_url = "https://huggingface.co"; + const root_path = "https://hmb-hello-world.hf.space"; + const prioritize_base = true; + const result = resolve_root(base_url, root_path, prioritize_base); + expect(result).toBe(base_url); + }); +}); + +describe("get_jwt", () => { + it("should return a valid JWT token when the API call is successful", async () => { + const space = "hmb/hello_world"; + const token = "hf_123"; + const expected_jwt = "jwt_123"; + + const result = await get_jwt(space, token); + + expect(result).toBe(expected_jwt); + }); + + it("should return false when the API call fails", async () => { + const space = "hmb/bye_world"; + const token = "hf_123"; + + const result = await get_jwt(space, token); + + expect(result).toBe(false); + }); +}); + +describe("determine_protocol", () => { + it('should return the correct protocols and host when the endpoint starts with "http"', () => { + const endpoint = "http://huggingface.co"; + const result = determine_protocol(endpoint); + expect(result).toEqual({ + ws_protocol: "ws", + http_protocol: "http:", + host: "huggingface.co" + }); + }); + + it('should return the correct protocols and host when the endpoint starts with "https"', () => { + const endpoint = "https://huggingface.co"; + const result = determine_protocol(endpoint); + expect(result).toEqual({ + ws_protocol: "wss", + http_protocol: "https:", + host: "huggingface.co" + }); + }); + + it('should return the correct protocols and host when the endpoint starts with "file"', () => { + const endpoint = "file:///path/to/app.html"; + const result = determine_protocol(endpoint); + expect(result).toEqual({ + ws_protocol: "ws", + http_protocol: "http:", + host: "lite.local" + }); + }); + + it('should return the default protocols and host when the endpoint does not start with "http" or "file"', () => { + const endpoint = "huggingface.co"; + const result = determine_protocol(endpoint); + expect(result).toEqual({ + ws_protocol: "wss", + http_protocol: "https:", + host: "huggingface.co" + }); + }); +}); + +describe("parse_and_set_cookies", () => { + it("should return an empty array when the cookie header is empty", () => { + const cookie_header = ""; + const result = parse_and_set_cookies(cookie_header); + expect(result).toEqual([]); + }); + + it("should parse the cookie header and return an array of cookies", () => { + const cookie_header = "access-token-123=abc;access-token-unsecured-456=def"; + const result = parse_and_set_cookies(cookie_header); + expect(result).toEqual(["access-token-123=abc"]); + }); +}); + +describe("resolve_cookies", () => { + it("should set the cookies when correct auth credentials are provided", async () => { + const client = await Client.connect("hmb/auth_space", { + auth: ["admin", "pass1234"] + }); + + const api = client.view_api(); + expect((await api).named_endpoints["/predict"]).toBeDefined(); + }); + + it("should connect to a private and authenticated space", async () => { + const client = await Client.connect("hmb/private_auth_space", { + hf_token: "hf_123", + auth: ["admin", "pass1234"] + }); + + const api = client.view_api(); + expect((await api).named_endpoints["/predict"]).toBeDefined(); + }); + + it("should not set the cookies when auth credentials are invalid", async () => { + await expect( + Client.connect("hmb/invalid_auth_space", { + auth: ["admin", "wrong_password"] + }) + ).rejects.toThrowError(INVALID_CREDENTIALS_MSG); + }); + + it("should not set the cookies when auth option is not provided in an auth space", async () => { + await expect(Client.connect("hmb/unauth_space")).rejects.toThrowError( + MISSING_CREDENTIALS_MSG + ); + }); +}); diff --git a/node_modules/@gradio/client/src/test/mock_eventsource.ts b/node_modules/@gradio/client/src/test/mock_eventsource.ts new file mode 100644 index 0000000000000000000000000000000000000000..1f47258cd3b90b03fa1dc97991806bc4fad54dfc --- /dev/null +++ b/node_modules/@gradio/client/src/test/mock_eventsource.ts @@ -0,0 +1,13 @@ +import { vi } from "vitest"; + +if (process.env.TEST_MODE !== "node") { + Object.defineProperty(window, "EventSource", { + writable: true, + value: vi.fn().mockImplementation(() => ({ + close: vi.fn(() => {}), + addEventListener: vi.fn(), + onmessage: vi.fn((_event: MessageEvent) => {}), + onerror: vi.fn((_event: Event) => {}) + })) + }); +} diff --git a/node_modules/@gradio/client/src/test/post_data.test.ts b/node_modules/@gradio/client/src/test/post_data.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..6ae96fed346ce8d2171ef1621ef394ca45d53684 --- /dev/null +++ b/node_modules/@gradio/client/src/test/post_data.test.ts @@ -0,0 +1,45 @@ +import { Client } from "../client"; + +import { initialise_server } from "./server"; +import { BROKEN_CONNECTION_MSG } from "../constants"; +const server = initialise_server(); +import { beforeAll, afterEach, afterAll, it, expect, describe } from "vitest"; + +beforeAll(() => server.listen()); +afterEach(() => server.resetHandlers()); +afterAll(() => server.close()); + +describe("post_data", () => { + it("should send a POST request with the correct headers and body", async () => { + const app = await Client.connect("hmb/hello_world"); + const config = app.config; + const url = config?.root; + const body = { data: "test" }; + + if (!url) { + throw new Error("No URL provided"); + } + + const [response, status] = await app.post_data(url, body); + + expect(response).toEqual({}); + expect(status).toBe(200); + }); + + it("should handle network errors", async () => { + const app = await Client.connect("hmb/secret_world", { + hf_token: "hf_123" + }); + + const url = "https://hmb-secret-world.hf.space"; + + if (!url) { + throw new Error("No URL provided"); + } + + const [response, status] = await app.post_data(url, {}); + + expect(response).toEqual(BROKEN_CONNECTION_MSG); + expect(status).toBe(500); + }); +}); diff --git a/node_modules/@gradio/client/src/test/server.ts b/node_modules/@gradio/client/src/test/server.ts new file mode 100644 index 0000000000000000000000000000000000000000..8eb91f6b278e6abb51965a1bf45561082c527bb6 --- /dev/null +++ b/node_modules/@gradio/client/src/test/server.ts @@ -0,0 +1,6 @@ +import { setupServer } from "msw/node"; +import { handlers } from "./handlers"; + +export function initialise_server(): any { + return setupServer(...handlers); +} diff --git a/node_modules/@gradio/client/src/test/spaces.test.ts b/node_modules/@gradio/client/src/test/spaces.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..60271ff37a57af9770e88c3b76011e7c98f3e2fc --- /dev/null +++ b/node_modules/@gradio/client/src/test/spaces.test.ts @@ -0,0 +1,145 @@ +import { SPACE_STATUS_ERROR_MSG } from "../constants"; +import { + discussions_enabled, + get_space_hardware, + set_space_timeout, + check_space_status +} from "../helpers/spaces"; +import { beforeAll, afterEach, afterAll, it, expect, describe } from "vitest"; + +import { initialise_server } from "./server"; +import { hardware_sleeptime_response } from "./test_data"; +import { vi } from "vitest"; + +const server = initialise_server(); + +beforeAll(() => server.listen()); +afterEach(() => server.resetHandlers()); +afterAll(() => server.close()); + +describe("set_space_timeout", () => { + it("should set the sleep timeout for a space", async () => { + const space_id = "hmb/hello_world"; + const timeout = 60; + const hf_token = "hf_123"; + + const response = await set_space_timeout(space_id, timeout, hf_token); + + expect(response).toEqual(hardware_sleeptime_response); + }); + + it("should throw an error if the fetch call fails", async () => { + const space_id = "hmb/server_test"; + const timeout = 60; + const hf_token = "hf_123"; + + await expect( + set_space_timeout(space_id, timeout, hf_token) + ).rejects.toThrow( + "Could not set sleep timeout on duplicated Space. Please visit *ADD HF LINK TO SETTINGS* to set a timeout manually to reduce billing charges." + ); + }); +}); + +describe("get_space_hardware", () => { + it("should return the current hardware for a space", async () => { + const space_id = "hmb/hello_world"; + const hf_token = "hf_123"; + + const hardware = await get_space_hardware(space_id, hf_token); + expect(hardware).toEqual(hardware_sleeptime_response.hardware.current); + }); + + it("should throw an error if the fetch call fails", async () => { + const space_id = "hmb/bye_world"; + + await expect(get_space_hardware(space_id)).rejects.toThrow( + "Space hardware could not be obtained." + ); + }); +}); + +describe("discussions_enabled", () => { + it("should return true if discussions are enabled for the space", async () => { + const space_id = "hmb/hello_world"; + const result = await discussions_enabled(space_id); + expect(result).toBe(true); + }); + + it("should return false if discussions are disabled for the space", async () => { + const space_id = "hmb/bye_world"; + const result = await discussions_enabled(space_id); + expect(result).toBe(false); + }); +}); + +describe("check_space_status", () => { + const status_callback = vi.fn(); + + it("should handle a successful response with RUNNING stage", async () => { + const id = "hmb/hello_world"; + const type = "space_name"; + + await check_space_status(id, type, status_callback); + expect(status_callback).toHaveBeenCalledWith({ + status: "running", + load_status: "complete", + message: "", + detail: "RUNNING" + }); + }); + + it("should handle a successful response with PAUSED stage", async () => { + const id = "hmb/paused_space"; + const type = "space_name"; + + await check_space_status(id, type, status_callback); + expect(status_callback).toHaveBeenCalledWith({ + status: "paused", + load_status: "error", + message: + "This space has been paused by the author. If you would like to try this demo, consider duplicating the space.", + detail: "PAUSED", + discussions_enabled: true + }); + }); + + it("should handle a successful response with BUILDING stage", async () => { + const id = "hmb/building_space"; + const type = "space_name"; + + await check_space_status(id, type, status_callback); + expect(status_callback).toHaveBeenCalledWith({ + status: "building", + load_status: "pending", + message: "Space is building...", + detail: "BUILDING" + }); + }); + + it("should handle a successful response with STOPPED stage", async () => { + const id = "hmb/stopped_space"; + const type = "space_name"; + + await check_space_status(id, type, status_callback); + expect(status_callback).toHaveBeenCalledWith({ + status: "sleeping", + load_status: "pending", + message: "Space is asleep. Waking it up...", + detail: "STOPPED" + }); + }); + + it("should handle a failed response", async () => { + const id = "hmb/failed_space"; + const type = "space_name"; + + await check_space_status(id, type, status_callback); + expect(status_callback).toHaveBeenCalledWith({ + status: "error", + load_status: "error", + message: SPACE_STATUS_ERROR_MSG, + detail: "NOT_FOUND" + }); + }); +}); diff --git a/node_modules/@gradio/client/src/test/stream.test.ts b/node_modules/@gradio/client/src/test/stream.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..9ac4b6c6a05b70f4fe07b7801eac9821fec62b8b --- /dev/null +++ b/node_modules/@gradio/client/src/test/stream.test.ts @@ -0,0 +1,81 @@ +import { vi, type Mock } from "vitest"; +import { Client } from "../client"; +import { readable_stream } from "../utils/stream"; +import { initialise_server } from "./server"; +import { direct_space_url } from "./handlers.ts"; + +import { + describe, + it, + expect, + afterEach, + beforeAll, + afterAll, + beforeEach +} from "vitest"; + +const server = initialise_server(); + +beforeAll(() => server.listen()); +afterEach(() => server.resetHandlers()); +afterAll(() => server.close()); + +describe("open_stream", () => { + let app: Client; + + beforeEach(async () => { + app = await Client.connect("hmb/hello_world"); + app.stream = vi.fn().mockImplementation(() => { + app.stream_instance = readable_stream( + new URL(`${direct_space_url}/queue/data`) + ); + return app.stream_instance; + }); + }); + + afterEach(() => { + vi.clearAllMocks(); + }); + + it("should throw an error if config is not defined", () => { + app.config = undefined; + + expect(async () => { + await app.open_stream(); + }).rejects.toThrow("Could not resolve app config"); + }); + + it("should connect to the SSE endpoint and handle messages", async () => { + await app.open_stream(); + + const eventsource_mock_call = (app.stream as Mock).mock.calls[0][0]; + + expect(eventsource_mock_call.href).toMatch( + /https:\/\/hmb-hello-world\.hf\.space\/queue\/data\?session_hash/ + ); + + expect(app.stream).toHaveBeenCalledWith(eventsource_mock_call); + + if (!app.stream_instance?.onmessage || !app.stream_instance?.onerror) { + throw new Error("stream instance is not defined"); + } + + const onMessageCallback = app.stream_instance.onmessage.bind(app); + const onErrorCallback = app.stream_instance.onerror.bind(app); + + const message = { msg: "hello jerry" }; + + onMessageCallback({ data: JSON.stringify(message) }); + expect(app.stream_status.open).toBe(true); + + expect(app.event_callbacks).toEqual({}); + expect(app.pending_stream_messages).toEqual({}); + + const close_stream_message = { msg: "close_stream" }; + onMessageCallback({ data: JSON.stringify(close_stream_message) }); + expect(app.stream_status.open).toBe(false); + + onErrorCallback({ data: JSON.stringify("404") }); + expect(app.stream_status.open).toBe(false); + }); +}); diff --git a/node_modules/@gradio/client/src/test/test_data.ts b/node_modules/@gradio/client/src/test/test_data.ts new file mode 100644 index 0000000000000000000000000000000000000000..b0d7aa5c3a135754c78072a140a55bd99c550735 --- /dev/null +++ b/node_modules/@gradio/client/src/test/test_data.ts @@ -0,0 +1,563 @@ +// @ts-nocheck +import { ApiData, ApiInfo, Config, EndpointInfo } from "../types"; + +export const runtime_response = { + stage: "RUNNING", + hardware: { + current: "cpu-basic", + requested: "cpu-basic" + }, + storage: { + current: null, + requested: null + }, + gcTimeout: 86400, + replicas: { + current: 1, + requested: 1 + }, + devMode: false, + domains: [ + { + domain: "hmb-hello-world.hf.space", + isCustom: false, + stage: "READY" + } + ] +}; + +export const transformed_api_info: ApiInfo = { + named_endpoints: { + "/predict": { + parameters: [ + { + label: "name", + type: "string", + python_type: { type: "str", description: "" }, + component: "Textbox", + example_input: "Hello!!" + } + ], + returns: [ + { + label: "output", + type: "string", + python_type: { type: "str", description: "" }, + component: "Textbox" + } + ], + type: { continuous: false, generator: false, cancel: false } + } + }, + unnamed_endpoints: { + "0": { + parameters: [ + { + label: "name", + type: "string", + python_type: { type: "str", description: "" }, + component: "Textbox", + example_input: "Hello!!" + } + ], + returns: [ + { + label: "output", + type: "string", + python_type: { type: "str", description: "" }, + component: "Textbox" + } + ], + type: { continuous: false, generator: false, cancel: false } + } + } +}; + +export const response_api_info: ApiInfo = { + named_endpoints: { + "/predict": { + parameters: [ + { + label: "name", + type: { + type: "string" + }, + python_type: { + type: "str", + description: "" + }, + component: "Textbox", + example_input: "Hello!!" + } + ], + returns: [ + { + label: "output", + type: { + type: "string" + }, + python_type: { + type: "str", + description: "" + }, + component: "Textbox" + } + ] + } + }, + unnamed_endpoints: {} +}; + +export const config_response: Config = { + version: "4.27.0", + mode: "interface", + app_id: 123, + dev_mode: false, + analytics_enabled: true, + components: [ + { + id: 3, + type: "row", + props: { + variant: "default", + visible: true, + equal_height: false, + name: "row" + }, + skip_api: true, + component_class_id: "" + }, + { + id: 4, + type: "column", + props: { + scale: 1, + min_width: 320, + variant: "panel", + visible: true, + name: "column" + }, + skip_api: true, + component_class_id: "" + }, + { + id: 5, + type: "column", + props: { + scale: 1, + min_width: 320, + variant: "default", + visible: true, + name: "column" + }, + skip_api: true, + component_class_id: "" + }, + { + id: 1, + type: "textbox", + props: { + lines: 1, + max_lines: 20, + label: "name", + show_label: true, + container: true, + min_width: 160, + visible: true, + autofocus: false, + autoscroll: true, + elem_classes: [], + type: "text", + rtl: false, + show_copy_button: false, + name: "textbox", + _selectable: false + }, + skip_api: false, + component_class_id: "", + api_info: { + type: "string" + }, + example_inputs: "Hello!!" + }, + { + id: 6, + type: "form", + props: { + scale: 0, + min_width: 0, + name: "form" + }, + skip_api: true, + component_class_id: "" + }, + { + id: 7, + type: "row", + props: { + variant: "default", + visible: true, + equal_height: true, + name: "row" + }, + skip_api: true, + component_class_id: "" + }, + { + id: 8, + type: "button", + props: { + value: "Clear", + variant: "secondary", + visible: true, + interactive: true, + elem_classes: [], + show_api: false, + name: "button", + _selectable: false + }, + skip_api: true, + component_class_id: "" + }, + { + id: 9, + type: "button", + props: { + value: "Submit", + variant: "primary", + visible: true, + interactive: true, + elem_classes: [], + name: "button", + _selectable: false + }, + skip_api: true, + component_class_id: "" + }, + { + id: 10, + type: "column", + props: { + scale: 1, + min_width: 320, + variant: "panel", + visible: true, + name: "column" + }, + skip_api: true, + component_class_id: "" + }, + { + id: 2, + type: "textbox", + props: { + lines: 1, + max_lines: 20, + label: "output", + show_label: true, + container: true, + min_width: 160, + interactive: false, + visible: true, + autofocus: false, + autoscroll: true, + elem_classes: [], + type: "text", + rtl: false, + show_copy_button: false, + name: "textbox", + _selectable: false + }, + skip_api: false, + component_class_id: "", + api_info: { + type: "string" + }, + example_inputs: "Hello!!" + }, + { + id: 11, + type: "row", + props: { + variant: "default", + visible: true, + equal_height: true, + name: "row" + }, + skip_api: true, + component_class_id: "" + }, + { + id: 12, + type: "form", + props: { + scale: 0, + min_width: 0, + name: "form" + }, + skip_api: true, + component_class_id: "" + } + ], + css: null, + js: null, + head: null, + title: "Gradio", + space_id: "hmb/hello_world", + enable_queue: true, + show_error: false, + show_api: true, + is_colab: false, + stylesheets: [], + theme: "default", + protocol: "sse_v3", + body_css: { + body_background_fill: "white", + body_text_color: "#1f2937", + body_background_fill_dark: "#0b0f19", + body_text_color_dark: "#f3f4f6" + }, + fill_height: false, + layout: { + id: 0, + children: [ + { + id: 3, + children: [ + { + id: 4, + children: [ + { + id: 5, + children: [ + { + id: 6, + children: [ + { + id: 1 + } + ] + } + ] + }, + { + id: 7, + children: [ + { + id: 8 + }, + { + id: 9 + } + ] + } + ] + }, + { + id: 10, + children: [ + { + id: 12, + children: [ + { + id: 2 + } + ] + }, + { + id: 11, + children: [] + } + ] + } + ] + } + ] + }, + dependencies: [ + { + id: 0, + targets: [ + [9, "click"], + [1, "submit"] + ], + inputs: [1], + outputs: [2], + backend_fn: true, + js: null, + queue: null, + api_name: "predict", + scroll_to_output: false, + show_progress: "full", + every: null, + batch: false, + max_batch_size: 4, + cancels: [], + types: { + continuous: false, + generator: false, + cancel: false + }, + collects_event_data: false, + trigger_after: null, + trigger_only_on_success: false, + trigger_mode: "once", + show_api: true, + zerogpu: false + }, + { + id: 1, + targets: [[8, "click"]], + inputs: [], + outputs: [1, 2], + backend_fn: false, + js: "() => [null, null]", + queue: false, + api_name: "js_fn", + scroll_to_output: false, + show_progress: "full", + every: null, + batch: false, + max_batch_size: 4, + cancels: [], + types: { + continuous: false, + generator: false, + cancel: false + }, + collects_event_data: false, + trigger_after: null, + trigger_only_on_success: false, + trigger_mode: "once", + show_api: false, + zerogpu: false + }, + { + id: 2, + targets: [[8, "click"]], + inputs: [], + outputs: [5], + backend_fn: false, + js: '() => [{"variant": null, "visible": true, "__type__": "update"}]\n ', + queue: false, + api_name: "js_fn_1", + scroll_to_output: false, + show_progress: "full", + every: null, + batch: false, + max_batch_size: 4, + cancels: [], + types: { + continuous: false, + generator: false, + cancel: false + }, + collects_event_data: false, + trigger_after: null, + trigger_only_on_success: false, + trigger_mode: "once", + show_api: false, + zerogpu: false + } + ], + root: "https://hmb-hello-world.hf.space", + path: "" +}; + +export const whoami_response = { + type: "user", + id: "123", + name: "hmb", + fullname: "jerry", + email: "jerry@gradio.com", + emailVerified: true, + canPay: true, + periodEnd: 123, + isPro: false, + avatarUrl: "", + orgs: [], + auth: { + type: "access_token", + accessToken: { + displayName: "Gradio Client", + role: "write" + } + } +}; + +export const duplicate_response = { + url: "https://huggingface.co/spaces/hmb/hello_world" +}; + +export const hardware_sleeptime_response = { + stage: "RUNNING", + hardware: { + current: "cpu-basic", + requested: "cpu-upgrade" + }, + storage: null, + gcTimeout: 300, + replicas: { + current: 1, + requested: 1 + }, + devMode: false, + domains: [ + { + domain: "hmb-hello-world.hf.space", + isCustom: false, + stage: "READY" + } + ] +}; + +export const endpoint_info: EndpointInfo = { + parameters: [ + { + label: "parameter_2", + parameter_name: "im", + parameter_has_default: false, + parameter_default: null, + type: "", + python_type: { + type: "Dict(background: filepath | None, layers: List[filepath], composite: filepath | None, id: str | None)", + description: "" + }, + component: "Imageeditor", + example_input: { + background: { + path: "", + meta: { + _type: "gradio.FileData" + }, + orig_name: "bus.png", + url: "" + }, + layers: [], + composite: null + } + } + ], + returns: [ + { + label: "value_3", + type: "string", + python_type: { + type: "filepath", + description: "" + }, + component: "Image" + } + ], + type: { + continuous: false, + generator: false + } +}; + +export const discussions_response = { + discussions: [], + count: 0, + start: 0, + numClosedDiscussions: 0 +}; diff --git a/node_modules/@gradio/client/src/test/upload_files.test.ts b/node_modules/@gradio/client/src/test/upload_files.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..2f50a0984a305d741833eac824b5e112ab6feb00 --- /dev/null +++ b/node_modules/@gradio/client/src/test/upload_files.test.ts @@ -0,0 +1,42 @@ +import { describe, it, expect, afterEach, beforeAll, afterAll } from "vitest"; + +import { Client } from ".."; +import { initialise_server } from "./server"; + +const server = initialise_server(); + +beforeAll(() => server.listen()); +afterEach(() => server.resetHandlers()); +afterAll(() => server.close()); + +describe("upload_files", () => { + it("should upload files successfully", async () => { + const root_url = "https://hmb-hello-world.hf.space"; + + const client = await Client.connect("hmb/hello_world", { + hf_token: "hf_token" + }); + + const files = [new Blob([], { type: "image/jpeg" })]; + + const response = await client.upload_files(root_url, files); + + if (!response.files) { + throw new Error("No files returned"); + } + + expect(response.files).toHaveLength(1); + expect(response.files[0]).toBe("lion.jpg"); + }); + + it.skip("should handle a server error when connected to a running app and uploading files", async () => { + const client = await Client.connect("hmb/server_test"); + + const root_url = "https://hmb-server-test.hf.space"; + const files = [new Blob([""], { type: "text/plain" })]; + + await expect(client.upload_files(root_url, files)).rejects.toThrow( + "Connection errored out. Failed to fetch" + ); + }); +}); diff --git a/node_modules/@gradio/client/src/test/view_api.test.ts b/node_modules/@gradio/client/src/test/view_api.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..c137be6e2d553f17f72ed41f5e85e6985f060226 --- /dev/null +++ b/node_modules/@gradio/client/src/test/view_api.test.ts @@ -0,0 +1,53 @@ +import { describe, beforeAll, afterEach, afterAll, test, expect } from "vitest"; + +import { Client, client, duplicate } from ".."; +import { transformed_api_info, config_response } from "./test_data"; +import { initialise_server } from "./server"; + +const app_reference = "hmb/hello_world"; +const secret_app_reference = "hmb/secret_world"; +const secret_direct_app_reference = "https://hmb-secret-world.hf.space"; + +const server = initialise_server(); + +beforeAll(() => server.listen()); +afterEach(() => server.resetHandlers()); +afterAll(() => server.close()); + +describe("view_api", () => { + test("viewing the api of a running, public app", async () => { + const app = await Client.connect(app_reference); + + expect(await app.view_api()).toEqual(transformed_api_info); + }); + + test("viewing the api of a running, private app", async () => { + const app = await Client.connect(secret_app_reference, { + hf_token: "hf_123" + }); + + expect(app.config).toEqual({ + ...config_response, + root: secret_direct_app_reference + }); + + expect(await app.view_api()).toEqual({ + ...transformed_api_info + }); + }); + + test("viewing the api of a running, private app with a direct app URL", async () => { + const app = await Client.connect(secret_direct_app_reference, { + hf_token: "hf_123" + }); + + expect(app.config).toEqual({ + ...config_response, + root: secret_direct_app_reference + }); + + expect(await app.view_api()).toEqual({ + ...transformed_api_info + }); + }); +}); diff --git a/node_modules/@gradio/client/src/types.ts b/node_modules/@gradio/client/src/types.ts index 2b1869855ef0a7d40d9fcda86bfc98197e733478..8e2d33c27fb388d3ba078bfb7aec421675bfd802 100644 --- a/node_modules/@gradio/client/src/types.ts +++ b/node_modules/@gradio/client/src/types.ts @@ -1,13 +1,163 @@ +// API Data Types + +import { hardware_types } from "./helpers/spaces"; +import type { SvelteComponent } from "svelte"; +import type { ComponentType } from "svelte"; + +export interface ApiData { + label: string; + parameter_name: string; + parameter_default?: any; + parameter_has_default?: boolean; + type: { + type: any; + description: string; + }; + component: string; + example_input?: any; + python_type: { type: string; description: string }; + serializer: string; +} + +export interface JsApiData { + label: string; + parameter_name: string; + parameter_default?: any; + parameter_has_default?: boolean; + type: string; + description: string; + component: string; + example_input?: any; + serializer: string; + python_type: { type: string; description: string }; +} + +export interface EndpointInfo { + parameters: T[]; + returns: T[]; + type?: DependencyTypes; +} + +export interface ApiInfo { + named_endpoints: Record>; + unnamed_endpoints: Record>; +} + +export interface BlobRef { + path: string[]; + type: string | undefined; + blob: Blob | File | false; +} + +export type DataType = string | Buffer | Record | any[]; + +// custom class used for uploading local files +export class Command { + type: string; + command: string; + meta: { + path: string; + name: string; + orig_path: string; + }; + fileData?: FileData; + + constructor( + command: string, + meta: { path: string; name: string; orig_path: string } + ) { + this.type = "command"; + this.command = command; + this.meta = meta; + } +} + +// Function Signature Types + +export type SubmitFunction = ( + endpoint: string | number, + data: unknown[] | Record, + event_data?: unknown, + trigger_id?: number | null +) => SubmitIterable; + +export type PredictFunction = ( + endpoint: string | number, + data: unknown[] | Record, + event_data?: unknown +) => Promise; + +export type client_return = { + config: Config | undefined; + predict: PredictFunction; + submit: SubmitFunction; + component_server: ( + component_id: number, + fn_name: string, + data: unknown[] + ) => any; + view_api: (_fetch: typeof fetch) => Promise>; +}; + +export interface SubmitIterable extends AsyncIterable { + [Symbol.asyncIterator](): AsyncIterator; + cancel: () => Promise; +} + +export type PredictReturn = { + type: EventType; + time: Date; + data: unknown; + endpoint: string; + fn_index: number; +}; + +// Space Status Types + +export type SpaceStatus = SpaceStatusNormal | SpaceStatusError; + +export interface SpaceStatusNormal { + status: "sleeping" | "running" | "building" | "error" | "stopped"; + detail: + | "SLEEPING" + | "RUNNING" + | "RUNNING_BUILDING" + | "BUILDING" + | "NOT_FOUND"; + load_status: "pending" | "error" | "complete" | "generating"; + message: string; +} + +export interface SpaceStatusError { + status: "space_error" | "paused"; + detail: + | "NO_APP_FILE" + | "CONFIG_ERROR" + | "BUILD_ERROR" + | "RUNTIME_ERROR" + | "PAUSED"; + load_status: "error"; + message: string; + discussions_enabled: boolean; +} + +export type SpaceStatusCallback = (a: SpaceStatus) => void; + +// Configuration and Response Types +// -------------------------------- export interface Config { - auth_required: boolean | undefined; + auth_required: boolean; + analytics_enabled: boolean; + connect_heartbeat: boolean; auth_message: string; - components: any[]; + components: ComponentMeta[]; css: string | null; js: string | null; head: string | null; - dependencies: any[]; + dependencies: Dependency[]; dev_mode: boolean; enable_queue: boolean; + show_error: boolean; layout: any; mode: "blocks" | "interface"; root: string; @@ -16,29 +166,164 @@ export interface Config { title: string; version: string; space_id: string | null; + is_space: boolean; is_colab: boolean; show_api: boolean; stylesheets: string[]; path: string; - protocol?: "sse_v1" | "sse" | "ws"; + protocol: "sse_v3" | "sse_v2.1" | "sse_v2" | "sse_v1" | "sse" | "ws"; + max_file_size?: number; + theme_hash?: number; +} + +// todo: DRY up types +export interface ComponentMeta { + type: string; + id: number; + has_modes: boolean; + props: SharedProps; + instance: SvelteComponent; + component: ComponentType; + documentation?: Documentation; + children?: ComponentMeta[]; + parent?: ComponentMeta; + value?: any; + component_class_id: string; + key: string | number | null; + rendered_in?: number; +} + +interface SharedProps { + elem_id?: string; + elem_classes?: string[]; + components?: string[]; + server_fns?: string[]; + interactive: boolean; + [key: string]: unknown; + root_url?: string; +} + +export interface Documentation { + type?: TypeDescription; + description?: TypeDescription; + example_data?: string; +} + +interface TypeDescription { + input_payload?: string; + response_object?: string; + payload?: string; +} + +export interface Dependency { + id: number; + targets: [number, string][]; + inputs: number[]; + outputs: number[]; + backend_fn: boolean; + js: string | null; + scroll_to_output: boolean; + trigger: "click" | "load" | string; + max_batch_size: number; + show_progress: "full" | "minimal" | "hidden"; + frontend_fn: ((...args: unknown[]) => Promise) | null; + status?: string; + queue: boolean | null; + every: number | null; + batch: boolean; + api_name: string | null; + cancels: number[]; + types: DependencyTypes; + collects_event_data: boolean; + pending_request?: boolean; + trigger_after?: number; + trigger_only_on_success?: boolean; + trigger_mode: "once" | "multiple" | "always_last"; + final_event: Payload | null; + show_api: boolean; + zerogpu?: boolean; + rendered_in: number | null; +} + +export interface DependencyTypes { + continuous: boolean; + generator: boolean; + cancel: boolean; } export interface Payload { + fn_index: number; data: unknown[]; - fn_index?: number; - event_data?: unknown; time?: Date; + event_data?: unknown; + trigger_id?: number | null; } export interface PostResponse { error?: string; [x: string]: any; } + export interface UploadResponse { error?: string; files?: string[]; } +// Client and File Handling Types + +export interface DuplicateOptions extends ClientOptions { + private?: boolean; + hardware?: (typeof hardware_types)[number]; + timeout?: number; +} + +export interface ClientOptions { + hf_token?: `hf_${string}`; + status_callback?: SpaceStatusCallback | null; + auth?: [string, string] | null; + with_null_state?: boolean; + events?: EventType[]; +} + +export interface FileData { + name: string; + orig_name?: string; + size?: number; + data: string; + blob?: File; + is_file?: boolean; + mime_type?: string; + alt_text?: string; +} + +// Event and Listener Types + +export type EventType = "data" | "status" | "log" | "render"; + +export interface EventMap { + data: PayloadMessage; + status: StatusMessage; + log: LogMessage; + render: RenderMessage; +} + +export type GradioEvent = { + [P in EventType]: EventMap[P]; +}[EventType]; + +export interface Log { + log: string; + level: "warning" | "info"; +} +export interface Render { + data: { + components: any[]; + layout: any; + dependencies: Dependency[]; + render_id: number; + }; +} + export interface Status { queue: boolean; code?: string; @@ -57,63 +342,29 @@ export interface Status { desc: string | null; }[]; time?: Date; + changed_state_ids?: number[]; } -export interface LogMessage { - log: string; - level: "warning" | "info"; +export interface StatusMessage extends Status { + type: "status"; + endpoint: string; + fn_index: number; } -export interface SpaceStatusNormal { - status: "sleeping" | "running" | "building" | "error" | "stopped"; - detail: - | "SLEEPING" - | "RUNNING" - | "RUNNING_BUILDING" - | "BUILDING" - | "NOT_FOUND"; - load_status: "pending" | "error" | "complete" | "generating"; - message: string; +export interface PayloadMessage extends Payload { + type: "data"; + endpoint: string; + fn_index: number; } -export interface SpaceStatusError { - status: "space_error" | "paused"; - detail: - | "NO_APP_FILE" - | "CONFIG_ERROR" - | "BUILD_ERROR" - | "RUNTIME_ERROR" - | "PAUSED"; - load_status: "error"; - message: string; - discussions_enabled: boolean; -} -export type SpaceStatus = SpaceStatusNormal | SpaceStatusError; - -export type status_callback_function = (a: Status) => void; -export type SpaceStatusCallback = (a: SpaceStatus) => void; - -export type EventType = "data" | "status" | "log"; -export interface EventMap { - data: Payload; - status: Status; - log: LogMessage; +export interface LogMessage extends Log { + type: "log"; + endpoint: string; + fn_index: number; } -export type Event = { - [P in K]: EventMap[P] & { type: P; endpoint: string; fn_index: number }; -}[K]; -export type EventListener = (event: Event) => void; -export type ListenerMap = { - [P in K]?: EventListener[]; -}; -export interface FileData { - name: string; - orig_name?: string; - size?: number; - data: string; - blob?: File; - is_file?: boolean; - mime_type?: string; - alt_text?: string; +export interface RenderMessage extends Render { + type: "render"; + endpoint: string; + fn_index: number; } diff --git a/node_modules/@gradio/client/src/upload.ts b/node_modules/@gradio/client/src/upload.ts index f5011710ae69b994c3dedd6f43402e6f630a15c8..0dfe714f7da6ad8e2743ecd895cbd3e1d937c25a 100644 --- a/node_modules/@gradio/client/src/upload.ts +++ b/node_modules/@gradio/client/src/upload.ts @@ -1,111 +1,42 @@ -import { upload_files } from "./client"; - -export function normalise_file( - file: FileData | null, - server_url: string, - proxy_url: string | null -): FileData | null; - -export function normalise_file( - file: FileData[] | null, - server_url: string, - proxy_url: string | null -): FileData[] | null; - -export function normalise_file( - file: FileData[] | FileData | null, - server_url: string, // root: string, - proxy_url: string | null // root_url: string | null -): FileData[] | FileData | null; - -export function normalise_file( - file: FileData[] | FileData | null, - server_url: string, // root: string, - proxy_url: string | null // root_url: string | null -): FileData[] | FileData | null { - if (file == null) { - return null; - } - - if (Array.isArray(file)) { - const normalized_file: (FileData | null)[] = []; - - for (const x of file) { - if (x == null) { - normalized_file.push(null); - } else { - normalized_file.push(normalise_file(x, server_url, proxy_url)); - } - } - - return normalized_file as FileData[]; - } - - if (file.is_stream) { - if (proxy_url == null) { - return new FileData({ - ...file, - url: server_url + "/stream/" + file.path - }); - } - return new FileData({ - ...file, - url: "/proxy=" + proxy_url + "stream/" + file.path - }); - } - - return new FileData({ - ...file, - url: get_fetchable_url_or_file(file.path, server_url, proxy_url) - }); -} - -function is_url(str: string): boolean { - try { - const url = new URL(str); - return url.protocol === "http:" || url.protocol === "https:"; - } catch { - return false; - } -} - -export function get_fetchable_url_or_file( - path: string | null, - server_url: string, - proxy_url: string | null -): string { - if (path == null) { - return proxy_url ? `/proxy=${proxy_url}file=` : `${server_url}/file=`; - } - if (is_url(path)) { - return path; - } - return proxy_url - ? `/proxy=${proxy_url}file=${path}` - : `${server_url}/file=${path}`; -} +import type { UploadResponse } from "./types"; +import type { Client } from "./client"; export async function upload( + this: Client, file_data: FileData[], - root: string, + root_url: string, upload_id?: string, - upload_fn: typeof upload_files = upload_files + max_file_size?: number ): Promise<(FileData | null)[] | null> { let files = (Array.isArray(file_data) ? file_data : [file_data]).map( (file_data) => file_data.blob! ); + const oversized_files = files.filter( + (f) => f.size > (max_file_size ?? Infinity) + ); + if (oversized_files.length) { + throw new Error( + `File size exceeds the maximum allowed size of ${max_file_size} bytes: ${oversized_files + .map((f) => f.name) + .join(", ")}` + ); + } + return await Promise.all( - await upload_fn(root, files, undefined, upload_id).then( + await this.upload_files(root_url, files, upload_id).then( async (response: { files?: string[]; error?: string }) => { if (response.error) { throw new Error(response.error); } else { if (response.files) { return response.files.map((f, i) => { - const file = new FileData({ ...file_data[i], path: f }); - - return normalise_file(file, root, null); + const file = new FileData({ + ...file_data[i], + path: f, + url: root_url + "/file=" + f + }); + return file; }); } @@ -121,7 +52,7 @@ export async function prepare_files( is_stream?: boolean ): Promise { return files.map( - (f, i) => + (f) => new FileData({ path: f.name, orig_name: f.name, @@ -142,6 +73,7 @@ export class FileData { is_stream?: boolean; mime_type?: string; alt_text?: string; + readonly meta = { _type: "gradio.FileData" }; constructor({ path, diff --git a/node_modules/@gradio/client/src/utils.ts b/node_modules/@gradio/client/src/utils.ts deleted file mode 100644 index 5883cfe0b16c9cc0920c25efabe232ad5529a70c..0000000000000000000000000000000000000000 --- a/node_modules/@gradio/client/src/utils.ts +++ /dev/null @@ -1,241 +0,0 @@ -import type { Config } from "./types.js"; - -/** - * This function is used to resolve the URL for making requests when the app has a root path. - * The root path could be a path suffix like "/app" which is appended to the end of the base URL. Or - * it could be a full URL like "https://abidlabs-test-client-replica--gqf2x.hf.space" which is used when hosting - * Gradio apps on Hugging Face Spaces. - * @param {string} base_url The base URL at which the Gradio server is hosted - * @param {string} root_path The root path, which could be a path suffix (e.g. mounted in FastAPI app) or a full URL (e.g. hosted on Hugging Face Spaces) - * @param {boolean} prioritize_base Whether to prioritize the base URL over the root path. This is used when both the base path and root paths are full URLs. For example, for fetching files the root path should be prioritized, but for making requests, the base URL should be prioritized. - * @returns {string} the resolved URL - */ -export function resolve_root( - base_url: string, - root_path: string, - prioritize_base: boolean -): string { - if (root_path.startsWith("http://") || root_path.startsWith("https://")) { - return prioritize_base ? base_url : root_path; - } - return base_url + root_path; -} - -export function determine_protocol(endpoint: string): { - ws_protocol: "ws" | "wss"; - http_protocol: "http:" | "https:"; - host: string; -} { - if (endpoint.startsWith("http")) { - const { protocol, host } = new URL(endpoint); - - if (host.endsWith("hf.space")) { - return { - ws_protocol: "wss", - host: host, - http_protocol: protocol as "http:" | "https:" - }; - } - return { - ws_protocol: protocol === "https:" ? "wss" : "ws", - http_protocol: protocol as "http:" | "https:", - host - }; - } else if (endpoint.startsWith("file:")) { - // This case is only expected to be used for the Wasm mode (Gradio-lite), - // where users can create a local HTML file using it and open the page in a browser directly via the `file:` protocol. - return { - ws_protocol: "ws", - http_protocol: "http:", - host: "lite.local" // Special fake hostname only used for this case. This matches the hostname allowed in `is_self_host()` in `js/wasm/network/host.ts`. - }; - } - - // default to secure if no protocol is provided - return { - ws_protocol: "wss", - http_protocol: "https:", - host: endpoint - }; -} - -export const RE_SPACE_NAME = /^[^\/]*\/[^\/]*$/; -export const RE_SPACE_DOMAIN = /.*hf\.space\/{0,1}$/; -export async function process_endpoint( - app_reference: string, - token?: `hf_${string}` -): Promise<{ - space_id: string | false; - host: string; - ws_protocol: "ws" | "wss"; - http_protocol: "http:" | "https:"; -}> { - const headers: { Authorization?: string } = {}; - if (token) { - headers.Authorization = `Bearer ${token}`; - } - - const _app_reference = app_reference.trim(); - - if (RE_SPACE_NAME.test(_app_reference)) { - try { - const res = await fetch( - `https://huggingface.co/api/spaces/${_app_reference}/host`, - { headers } - ); - - if (res.status !== 200) - throw new Error("Space metadata could not be loaded."); - const _host = (await res.json()).host; - - return { - space_id: app_reference, - ...determine_protocol(_host) - }; - } catch (e: any) { - throw new Error("Space metadata could not be loaded." + e.message); - } - } - - if (RE_SPACE_DOMAIN.test(_app_reference)) { - const { ws_protocol, http_protocol, host } = - determine_protocol(_app_reference); - - return { - space_id: host.replace(".hf.space", ""), - ws_protocol, - http_protocol, - host - }; - } - - return { - space_id: false, - ...determine_protocol(_app_reference) - }; -} - -export function map_names_to_ids( - fns: Config["dependencies"] -): Record { - let apis: Record = {}; - - fns.forEach(({ api_name }, i) => { - if (api_name) apis[api_name] = i; - }); - - return apis; -} - -const RE_DISABLED_DISCUSSION = - /^(?=[^]*\b[dD]iscussions{0,1}\b)(?=[^]*\b[dD]isabled\b)[^]*$/; -export async function discussions_enabled(space_id: string): Promise { - try { - const r = await fetch( - `https://huggingface.co/api/spaces/${space_id}/discussions`, - { - method: "HEAD" - } - ); - const error = r.headers.get("x-error-message"); - - if (error && RE_DISABLED_DISCUSSION.test(error)) return false; - return true; - } catch (e) { - return false; - } -} - -export async function get_space_hardware( - space_id: string, - token: `hf_${string}` -): Promise<(typeof hardware_types)[number]> { - const headers: { Authorization?: string } = {}; - if (token) { - headers.Authorization = `Bearer ${token}`; - } - - try { - const res = await fetch( - `https://huggingface.co/api/spaces/${space_id}/runtime`, - { headers } - ); - - if (res.status !== 200) - throw new Error("Space hardware could not be obtained."); - - const { hardware } = await res.json(); - - return hardware; - } catch (e: any) { - throw new Error(e.message); - } -} - -export async function set_space_hardware( - space_id: string, - new_hardware: (typeof hardware_types)[number], - token: `hf_${string}` -): Promise<(typeof hardware_types)[number]> { - const headers: { Authorization?: string } = {}; - if (token) { - headers.Authorization = `Bearer ${token}`; - } - - try { - const res = await fetch( - `https://huggingface.co/api/spaces/${space_id}/hardware`, - { headers, body: JSON.stringify(new_hardware) } - ); - - if (res.status !== 200) - throw new Error( - "Space hardware could not be set. Please ensure the space hardware provided is valid and that a Hugging Face token is passed in." - ); - - const { hardware } = await res.json(); - - return hardware; - } catch (e: any) { - throw new Error(e.message); - } -} - -export async function set_space_timeout( - space_id: string, - timeout: number, - token: `hf_${string}` -): Promise { - const headers: { Authorization?: string } = {}; - if (token) { - headers.Authorization = `Bearer ${token}`; - } - - try { - const res = await fetch( - `https://huggingface.co/api/spaces/${space_id}/hardware`, - { headers, body: JSON.stringify({ seconds: timeout }) } - ); - - if (res.status !== 200) - throw new Error( - "Space hardware could not be set. Please ensure the space hardware provided is valid and that a Hugging Face token is passed in." - ); - - const { hardware } = await res.json(); - - return hardware; - } catch (e: any) { - throw new Error(e.message); - } -} - -export const hardware_types = [ - "cpu-basic", - "cpu-upgrade", - "t4-small", - "t4-medium", - "a10g-small", - "a10g-large", - "a100-large" -] as const; diff --git a/node_modules/@gradio/client/src/utils/duplicate.ts b/node_modules/@gradio/client/src/utils/duplicate.ts new file mode 100644 index 0000000000000000000000000000000000000000..27cecd3ffbce98b52a9f04b744012fb5ea291ba5 --- /dev/null +++ b/node_modules/@gradio/client/src/utils/duplicate.ts @@ -0,0 +1,129 @@ +import { + get_space_hardware, + hardware_types, + set_space_timeout +} from "../helpers/spaces"; +import type { DuplicateOptions } from "../types"; +import { Client } from "../client"; +import { SPACE_METADATA_ERROR_MSG } from "../constants"; +import { + get_cookie_header, + parse_and_set_cookies +} from "../helpers/init_helpers"; +import { process_endpoint } from "../helpers/api_info"; + +export async function duplicate( + app_reference: string, + options: DuplicateOptions +): Promise { + const { hf_token, private: _private, hardware, timeout, auth } = options; + + if (hardware && !hardware_types.includes(hardware)) { + throw new Error( + `Invalid hardware type provided. Valid types are: ${hardware_types + .map((v) => `"${v}"`) + .join(",")}.` + ); + } + + const { http_protocol, host } = await process_endpoint( + app_reference, + hf_token + ); + + let cookies: string[] | null = null; + + if (auth) { + const cookie_header = await get_cookie_header( + http_protocol, + host, + auth, + fetch + ); + + if (cookie_header) cookies = parse_and_set_cookies(cookie_header); + } + + const headers = { + Authorization: `Bearer ${hf_token}`, + "Content-Type": "application/json", + ...(cookies ? { Cookie: cookies.join("; ") } : {}) + }; + + const user = ( + await ( + await fetch(`https://huggingface.co/api/whoami-v2`, { + headers + }) + ).json() + ).name; + + const space_name = app_reference.split("/")[1]; + const body: { + repository: string; + private?: boolean; + hardware?: string; + } = { + repository: `${user}/${space_name}` + }; + + if (_private) { + body.private = true; + } + + let original_hardware; + + try { + if (!hardware) { + original_hardware = await get_space_hardware(app_reference, hf_token); + } + } catch (e) { + throw Error(SPACE_METADATA_ERROR_MSG + (e as Error).message); + } + + const requested_hardware = hardware || original_hardware || "cpu-basic"; + + body.hardware = requested_hardware; + + try { + const response = await fetch( + `https://huggingface.co/api/spaces/${app_reference}/duplicate`, + { + method: "POST", + headers, + body: JSON.stringify(body) + } + ); + + if (response.status === 409) { + try { + const client = await Client.connect(`${user}/${space_name}`, options); + return client; + } catch (error) { + console.error("Failed to connect Client instance:", error); + throw error; + } + } else if (response.status !== 200) { + throw new Error(response.statusText); + } + + const duplicated_space = await response.json(); + + await set_space_timeout(`${user}/${space_name}`, timeout || 300, hf_token); + + return await Client.connect( + get_space_reference(duplicated_space.url), + options + ); + } catch (e: any) { + throw new Error(e); + } +} + +function get_space_reference(url: string): any { + const regex = /https:\/\/huggingface.co\/spaces\/([^/]+\/[^/]+)/; + const match = url.match(regex); + if (match) { + return match[1]; + } +} diff --git a/node_modules/@gradio/client/src/utils/handle_blob.ts b/node_modules/@gradio/client/src/utils/handle_blob.ts new file mode 100644 index 0000000000000000000000000000000000000000..54c164887b84c492c47aca30d4d2733254e10c37 --- /dev/null +++ b/node_modules/@gradio/client/src/utils/handle_blob.ts @@ -0,0 +1,137 @@ +import { update_object, walk_and_store_blobs } from "../helpers/data"; +import { + Command, + type ApiData, + type EndpointInfo, + type JsApiData +} from "../types"; +import { FileData } from "../upload"; +import type { Client } from ".."; +import { + FILE_PROCESSING_ERROR_MSG, + NODEJS_FS_ERROR_MSG, + ROOT_URL_ERROR_MSG +} from "../constants"; + +export async function handle_blob( + this: Client, + endpoint: string, + data: unknown[], + api_info: EndpointInfo +): Promise { + const self = this; + + await process_local_file_commands(self, data); + + const blobRefs = await walk_and_store_blobs( + data, + undefined, + [], + true, + api_info + ); + + const results = await Promise.all( + blobRefs.map(async ({ path, blob, type }) => { + if (!blob) return { path, type }; + + const response = await self.upload_files(endpoint, [blob]); + const file_url = response.files && response.files[0]; + return { + path, + file_url, + type, + name: blob instanceof File ? blob?.name : undefined + }; + }) + ); + + results.forEach(({ path, file_url, type, name }) => { + if (type === "Gallery") { + update_object(data, file_url, path); + } else if (file_url) { + const file = new FileData({ path: file_url, orig_name: name }); + update_object(data, file, path); + } + }); + + return data; +} + +export async function process_local_file_commands( + client: Client, + data: unknown[] +): Promise { + const root = client.config?.root || client.config?.root_url; + + if (!root) { + throw new Error(ROOT_URL_ERROR_MSG); + } + + await recursively_process_commands(client, data); +} + +async function recursively_process_commands( + client: Client, + data: any, + path: string[] = [] +): Promise { + for (const key in data) { + if (data[key] instanceof Command) { + await process_single_command(client, data, key); + } else if (typeof data[key] === "object" && data[key] !== null) { + await recursively_process_commands(client, data[key], [...path, key]); + } + } +} + +async function process_single_command( + client: Client, + data: any, + key: string +): Promise { + let cmd_item = data[key] as Command; + const root = client.config?.root || client.config?.root_url; + + if (!root) { + throw new Error(ROOT_URL_ERROR_MSG); + } + + try { + let fileBuffer: Buffer; + let fullPath: string; + + // check if running in a Node.js environment + if ( + typeof process !== "undefined" && + process.versions && + process.versions.node + ) { + const fs = await import("fs/promises"); + const path = await import("path"); + + fullPath = path.resolve(process.cwd(), cmd_item.meta.path); + fileBuffer = await fs.readFile(fullPath); // Read file from disk + } else { + throw new Error(NODEJS_FS_ERROR_MSG); + } + + const file = new Blob([fileBuffer], { type: "application/octet-stream" }); + + const response = await client.upload_files(root, [file]); + + const file_url = response.files && response.files[0]; + + if (file_url) { + const fileData = new FileData({ + path: file_url, + orig_name: cmd_item.meta.name || "" + }); + + // replace the command object with the fileData object + data[key] = fileData; + } + } catch (error) { + console.error(FILE_PROCESSING_ERROR_MSG, error); + } +} diff --git a/node_modules/@gradio/client/src/utils/post_data.ts b/node_modules/@gradio/client/src/utils/post_data.ts new file mode 100644 index 0000000000000000000000000000000000000000..53264a3c86f3083df3ff336c867b697e20a3f69e --- /dev/null +++ b/node_modules/@gradio/client/src/utils/post_data.ts @@ -0,0 +1,38 @@ +import { BROKEN_CONNECTION_MSG } from "../constants"; +import type { PostResponse } from "../types"; +import { Client } from ".."; + +export async function post_data( + this: Client, + url: string, + body: unknown, + additional_headers?: any +): Promise<[PostResponse, number]> { + const headers: { + Authorization?: string; + "Content-Type": "application/json"; + } = { "Content-Type": "application/json" }; + if (this.options.hf_token) { + headers.Authorization = `Bearer ${this.options.hf_token}`; + } + try { + var response = await this.fetch(url, { + method: "POST", + body: JSON.stringify(body), + headers: { ...headers, ...additional_headers }, + credentials: "include" + }); + } catch (e) { + return [{ error: BROKEN_CONNECTION_MSG }, 500]; + } + let output: PostResponse; + let status: number; + try { + output = await response.json(); + status = response.status; + } catch (e) { + output = { error: `Could not parse server response: ${e}` }; + status = 500; + } + return [output, status]; +} diff --git a/node_modules/@gradio/client/src/utils/predict.ts b/node_modules/@gradio/client/src/utils/predict.ts new file mode 100644 index 0000000000000000000000000000000000000000..0d5121123cc3e08b4008ae9099321e7ba81b2cc0 --- /dev/null +++ b/node_modules/@gradio/client/src/utils/predict.ts @@ -0,0 +1,57 @@ +import { Client } from "../client"; +import type { Dependency, PredictReturn } from "../types"; + +export async function predict( + this: Client, + endpoint: string | number, + data: unknown[] | Record +): Promise { + let data_returned = false; + let status_complete = false; + let dependency: Dependency; + + if (!this.config) { + throw new Error("Could not resolve app config"); + } + + if (typeof endpoint === "number") { + dependency = this.config.dependencies.find((dep) => dep.id == endpoint)!; + } else { + const trimmed_endpoint = endpoint.replace(/^\//, ""); + dependency = this.config.dependencies.find( + (dep) => dep.id == this.api_map[trimmed_endpoint] + )!; + } + + if (dependency?.types.continuous) { + throw new Error( + "Cannot call predict on this function as it may run forever. Use submit instead" + ); + } + + return new Promise(async (resolve, reject) => { + const app = this.submit(endpoint, data, null, null, true); + let result: unknown; + + for await (const message of app) { + if (message.type === "data") { + if (status_complete) { + resolve(result as PredictReturn); + } + data_returned = true; + result = message; + } + + if (message.type === "status") { + if (message.stage === "error") reject(message); + if (message.stage === "complete") { + status_complete = true; + // if complete message comes after data, resolve here + if (data_returned) { + resolve(result as PredictReturn); + } + } + } + } + }); +} diff --git a/node_modules/@gradio/client/src/utils/stream.ts b/node_modules/@gradio/client/src/utils/stream.ts new file mode 100644 index 0000000000000000000000000000000000000000..e47bb6fad5268270d6e52e601213d304b9701d77 --- /dev/null +++ b/node_modules/@gradio/client/src/utils/stream.ts @@ -0,0 +1,228 @@ +import { BROKEN_CONNECTION_MSG } from "../constants"; +import type { Client } from "../client"; +import { stream } from "fetch-event-stream"; + +export async function open_stream(this: Client): Promise { + let { + event_callbacks, + unclosed_events, + pending_stream_messages, + stream_status, + config, + jwt + } = this; + + const that = this; + + if (!config) { + throw new Error("Could not resolve app config"); + } + + stream_status.open = true; + + let stream: EventSource | null = null; + let params = new URLSearchParams({ + session_hash: this.session_hash + }).toString(); + + let url = new URL(`${config.root}/queue/data?${params}`); + + if (jwt) { + url.searchParams.set("__sign", jwt); + } + + stream = this.stream(url); + + if (!stream) { + console.warn("Cannot connect to SSE endpoint: " + url.toString()); + return; + } + + stream.onmessage = async function (event: MessageEvent) { + let _data = JSON.parse(event.data); + if (_data.msg === "close_stream") { + close_stream(stream_status, that.abort_controller); + return; + } + const event_id = _data.event_id; + if (!event_id) { + await Promise.all( + Object.keys(event_callbacks).map((event_id) => + event_callbacks[event_id](_data) + ) + ); + } else if (event_callbacks[event_id] && config) { + if ( + _data.msg === "process_completed" && + ["sse", "sse_v1", "sse_v2", "sse_v2.1", "sse_v3"].includes( + config.protocol + ) + ) { + unclosed_events.delete(event_id); + } + let fn: (data: any) => void = event_callbacks[event_id]; + + if (typeof window !== "undefined" && typeof document !== "undefined") { + // fn(_data); // need to do this to put the event on the end of the event loop, so the browser can refresh between callbacks and not freeze in case of quick generations. See + setTimeout(fn, 0, _data); // need to do this to put the event on the end of the event loop, so the browser can refresh between callbacks and not freeze in case of quick generations. See https://github.com/gradio-app/gradio/pull/7055 + } else { + fn(_data); + } + } else { + if (!pending_stream_messages[event_id]) { + pending_stream_messages[event_id] = []; + } + pending_stream_messages[event_id].push(_data); + } + }; + stream.onerror = async function () { + await Promise.all( + Object.keys(event_callbacks).map((event_id) => + event_callbacks[event_id]({ + msg: "unexpected_error", + message: BROKEN_CONNECTION_MSG + }) + ) + ); + }; +} + +export function close_stream( + stream_status: { open: boolean }, + abort_controller: AbortController | null +): void { + if (stream_status) { + stream_status.open = false; + abort_controller?.abort(); + } +} + +export function apply_diff_stream( + pending_diff_streams: Record, + event_id: string, + data: any +): void { + let is_first_generation = !pending_diff_streams[event_id]; + if (is_first_generation) { + pending_diff_streams[event_id] = []; + data.data.forEach((value: any, i: number) => { + pending_diff_streams[event_id][i] = value; + }); + } else { + data.data.forEach((value: any, i: number) => { + let new_data = apply_diff(pending_diff_streams[event_id][i], value); + pending_diff_streams[event_id][i] = new_data; + data.data[i] = new_data; + }); + } +} + +export function apply_diff( + obj: any, + diff: [string, (number | string)[], any][] +): any { + diff.forEach(([action, path, value]) => { + obj = apply_edit(obj, path, action, value); + }); + + return obj; +} + +function apply_edit( + target: any, + path: (number | string)[], + action: string, + value: any +): any { + if (path.length === 0) { + if (action === "replace") { + return value; + } else if (action === "append") { + return target + value; + } + throw new Error(`Unsupported action: ${action}`); + } + + let current = target; + for (let i = 0; i < path.length - 1; i++) { + current = current[path[i]]; + } + + const last_path = path[path.length - 1]; + switch (action) { + case "replace": + current[last_path] = value; + break; + case "append": + current[last_path] += value; + break; + case "add": + if (Array.isArray(current)) { + current.splice(Number(last_path), 0, value); + } else { + current[last_path] = value; + } + break; + case "delete": + if (Array.isArray(current)) { + current.splice(Number(last_path), 1); + } else { + delete current[last_path]; + } + break; + default: + throw new Error(`Unknown action: ${action}`); + } + return target; +} + +export function readable_stream( + input: RequestInfo | URL, + init: RequestInit = {} +): EventSource { + const instance: EventSource & { readyState: number } = { + close: () => { + throw new Error("Method not implemented."); + }, + onerror: null, + onmessage: null, + onopen: null, + readyState: 0, + url: input.toString(), + withCredentials: false, + CONNECTING: 0, + OPEN: 1, + CLOSED: 2, + addEventListener: () => { + throw new Error("Method not implemented."); + }, + dispatchEvent: () => { + throw new Error("Method not implemented."); + }, + removeEventListener: () => { + throw new Error("Method not implemented."); + } + }; + + stream(input, init) + .then(async (res) => { + instance.readyState = instance.OPEN; + try { + for await (const chunk of res) { + //@ts-ignore + instance.onmessage && instance.onmessage(chunk); + } + instance.readyState = instance.CLOSED; + } catch (e) { + instance.onerror && instance.onerror(e as Event); + instance.readyState = instance.CLOSED; + } + }) + .catch((e) => { + console.error(e); + instance.onerror && instance.onerror(e as Event); + instance.readyState = instance.CLOSED; + }); + + return instance as EventSource; +} diff --git a/node_modules/@gradio/client/src/utils/submit.ts b/node_modules/@gradio/client/src/utils/submit.ts new file mode 100644 index 0000000000000000000000000000000000000000..b2c02b314932abba420d965708a2e87cf79245ff --- /dev/null +++ b/node_modules/@gradio/client/src/utils/submit.ts @@ -0,0 +1,838 @@ +/* eslint-disable complexity */ +import type { + Status, + Payload, + GradioEvent, + JsApiData, + EndpointInfo, + ApiInfo, + Config, + Dependency, + SubmitIterable +} from "../types"; + +import { skip_queue, post_message, handle_payload } from "../helpers/data"; +import { resolve_root } from "../helpers/init_helpers"; +import { + handle_message, + map_data_to_params, + process_endpoint +} from "../helpers/api_info"; +import semiver from "semiver"; +import { BROKEN_CONNECTION_MSG, QUEUE_FULL_MSG } from "../constants"; +import { apply_diff_stream, close_stream } from "./stream"; +import { Client } from "../client"; + +export function submit( + this: Client, + endpoint: string | number, + data: unknown[] | Record, + event_data?: unknown, + trigger_id?: number | null, + all_events?: boolean +): SubmitIterable { + try { + const { hf_token } = this.options; + const { + fetch, + app_reference, + config, + session_hash, + api_info, + api_map, + stream_status, + pending_stream_messages, + pending_diff_streams, + event_callbacks, + unclosed_events, + post_data, + options + } = this; + + const that = this; + + if (!api_info) throw new Error("No API found"); + if (!config) throw new Error("Could not resolve app config"); + + let { fn_index, endpoint_info, dependency } = get_endpoint_info( + api_info, + endpoint, + api_map, + config + ); + + let resolved_data = map_data_to_params(data, api_info); + + let websocket: WebSocket; + let stream: EventSource | null; + let protocol = config.protocol ?? "ws"; + + const _endpoint = typeof endpoint === "number" ? "/predict" : endpoint; + let payload: Payload; + let event_id: string | null = null; + let complete: Status | undefined | false = false; + let last_status: Record = {}; + let url_params = + typeof window !== "undefined" && typeof document !== "undefined" + ? new URLSearchParams(window.location.search).toString() + : ""; + + const events_to_publish = + options?.events?.reduce( + (acc, event) => { + acc[event] = true; + return acc; + }, + {} as Record + ) || {}; + + // event subscription methods + function fire_event(event: GradioEvent): void { + if (all_events || events_to_publish[event.type]) { + push_event(event); + } + } + + async function cancel(): Promise { + const _status: Status = { + stage: "complete", + queue: false, + time: new Date() + }; + complete = _status; + fire_event({ + ..._status, + type: "status", + endpoint: _endpoint, + fn_index: fn_index + }); + + let reset_request = {}; + let cancel_request = {}; + if (protocol === "ws") { + if (websocket && websocket.readyState === 0) { + websocket.addEventListener("open", () => { + websocket.close(); + }); + } else { + websocket.close(); + } + reset_request = { fn_index, session_hash }; + } else { + close_stream(stream_status, that.abort_controller); + close(); + reset_request = { event_id }; + cancel_request = { event_id, session_hash, fn_index }; + } + + try { + if (!config) { + throw new Error("Could not resolve app config"); + } + + if ("event_id" in cancel_request) { + await fetch(`${config.root}/cancel`, { + headers: { "Content-Type": "application/json" }, + method: "POST", + body: JSON.stringify(cancel_request) + }); + } + + await fetch(`${config.root}/reset`, { + headers: { "Content-Type": "application/json" }, + method: "POST", + body: JSON.stringify(reset_request) + }); + } catch (e) { + console.warn( + "The `/reset` endpoint could not be called. Subsequent endpoint results may be unreliable." + ); + } + } + + const resolve_heartbeat = async (config: Config): Promise => { + await this._resolve_hearbeat(config); + }; + + async function handle_render_config(render_config: any): Promise { + if (!config) return; + let render_id: number = render_config.render_id; + config.components = [ + ...config.components.filter((c) => c.props.rendered_in !== render_id), + ...render_config.components + ]; + config.dependencies = [ + ...config.dependencies.filter((d) => d.rendered_in !== render_id), + ...render_config.dependencies + ]; + const any_state = config.components.some((c) => c.type === "state"); + const any_unload = config.dependencies.some((d) => + d.targets.some((t) => t[1] === "unload") + ); + config.connect_heartbeat = any_state || any_unload; + await resolve_heartbeat(config); + fire_event({ + type: "render", + data: render_config, + endpoint: _endpoint, + fn_index + }); + } + + this.handle_blob(config.root, resolved_data, endpoint_info).then( + async (_payload) => { + let input_data = handle_payload( + _payload, + dependency, + config.components, + "input", + true + ); + payload = { + data: input_data || [], + event_data, + fn_index, + trigger_id + }; + if (skip_queue(fn_index, config)) { + fire_event({ + type: "status", + endpoint: _endpoint, + stage: "pending", + queue: false, + fn_index, + time: new Date() + }); + + post_data( + `${config.root}/run${ + _endpoint.startsWith("/") ? _endpoint : `/${_endpoint}` + }${url_params ? "?" + url_params : ""}`, + { + ...payload, + session_hash + } + ) + .then(([output, status_code]: any) => { + const data = output.data; + if (status_code == 200) { + fire_event({ + type: "data", + endpoint: _endpoint, + fn_index, + data: handle_payload( + data, + dependency, + config.components, + "output", + options.with_null_state + ), + time: new Date(), + event_data, + trigger_id + }); + if (output.render_config) { + handle_render_config(output.render_config); + } + + fire_event({ + type: "status", + endpoint: _endpoint, + fn_index, + stage: "complete", + eta: output.average_duration, + queue: false, + time: new Date() + }); + } else { + fire_event({ + type: "status", + stage: "error", + endpoint: _endpoint, + fn_index, + message: output.error, + queue: false, + time: new Date() + }); + } + }) + .catch((e) => { + fire_event({ + type: "status", + stage: "error", + message: e.message, + endpoint: _endpoint, + fn_index, + queue: false, + time: new Date() + }); + }); + } else if (protocol == "ws") { + const { ws_protocol, host } = await process_endpoint( + app_reference, + hf_token + ); + + fire_event({ + type: "status", + stage: "pending", + queue: true, + endpoint: _endpoint, + fn_index, + time: new Date() + }); + + let url = new URL( + `${ws_protocol}://${resolve_root( + host, + config.path as string, + true + )}/queue/join${url_params ? "?" + url_params : ""}` + ); + + if (this.jwt) { + url.searchParams.set("__sign", this.jwt); + } + + websocket = new WebSocket(url); + + websocket.onclose = (evt) => { + if (!evt.wasClean) { + fire_event({ + type: "status", + stage: "error", + broken: true, + message: BROKEN_CONNECTION_MSG, + queue: true, + endpoint: _endpoint, + fn_index, + time: new Date() + }); + } + }; + + websocket.onmessage = function (event) { + const _data = JSON.parse(event.data); + const { type, status, data } = handle_message( + _data, + last_status[fn_index] + ); + + if (type === "update" && status && !complete) { + // call 'status' listeners + fire_event({ + type: "status", + endpoint: _endpoint, + fn_index, + time: new Date(), + ...status + }); + if (status.stage === "error") { + websocket.close(); + } + } else if (type === "hash") { + websocket.send(JSON.stringify({ fn_index, session_hash })); + return; + } else if (type === "data") { + websocket.send(JSON.stringify({ ...payload, session_hash })); + } else if (type === "complete") { + complete = status; + } else if (type === "log") { + fire_event({ + type: "log", + log: data.log, + level: data.level, + endpoint: _endpoint, + fn_index + }); + } else if (type === "generating") { + fire_event({ + type: "status", + time: new Date(), + ...status, + stage: status?.stage!, + queue: true, + endpoint: _endpoint, + fn_index + }); + } + if (data) { + fire_event({ + type: "data", + time: new Date(), + data: handle_payload( + data.data, + dependency, + config.components, + "output", + options.with_null_state + ), + endpoint: _endpoint, + fn_index, + event_data, + trigger_id + }); + + if (complete) { + fire_event({ + type: "status", + time: new Date(), + ...complete, + stage: status?.stage!, + queue: true, + endpoint: _endpoint, + fn_index + }); + websocket.close(); + } + } + }; + + // different ws contract for gradio versions older than 3.6.0 + //@ts-ignore + if (semiver(config.version || "2.0.0", "3.6") < 0) { + addEventListener("open", () => + websocket.send(JSON.stringify({ hash: session_hash })) + ); + } + } else if (protocol == "sse") { + fire_event({ + type: "status", + stage: "pending", + queue: true, + endpoint: _endpoint, + fn_index, + time: new Date() + }); + var params = new URLSearchParams({ + fn_index: fn_index.toString(), + session_hash: session_hash + }).toString(); + let url = new URL( + `${config.root}/queue/join?${ + url_params ? url_params + "&" : "" + }${params}` + ); + + if (this.jwt) { + url.searchParams.set("__sign", this.jwt); + } + + stream = this.stream(url); + + if (!stream) { + return Promise.reject( + new Error("Cannot connect to SSE endpoint: " + url.toString()) + ); + } + + stream.onmessage = async function (event: MessageEvent) { + const _data = JSON.parse(event.data); + const { type, status, data } = handle_message( + _data, + last_status[fn_index] + ); + + if (type === "update" && status && !complete) { + // call 'status' listeners + fire_event({ + type: "status", + endpoint: _endpoint, + fn_index, + time: new Date(), + ...status + }); + if (status.stage === "error") { + stream?.close(); + close(); + } + } else if (type === "data") { + event_id = _data.event_id as string; + let [_, status] = await post_data(`${config.root}/queue/data`, { + ...payload, + session_hash, + event_id + }); + if (status !== 200) { + fire_event({ + type: "status", + stage: "error", + message: BROKEN_CONNECTION_MSG, + queue: true, + endpoint: _endpoint, + fn_index, + time: new Date() + }); + stream?.close(); + close(); + } + } else if (type === "complete") { + complete = status; + } else if (type === "log") { + fire_event({ + type: "log", + log: data.log, + level: data.level, + endpoint: _endpoint, + fn_index + }); + } else if (type === "generating") { + fire_event({ + type: "status", + time: new Date(), + ...status, + stage: status?.stage!, + queue: true, + endpoint: _endpoint, + fn_index + }); + } + if (data) { + fire_event({ + type: "data", + time: new Date(), + data: handle_payload( + data.data, + dependency, + config.components, + "output", + options.with_null_state + ), + endpoint: _endpoint, + fn_index, + event_data, + trigger_id + }); + + if (complete) { + fire_event({ + type: "status", + time: new Date(), + ...complete, + stage: status?.stage!, + queue: true, + endpoint: _endpoint, + fn_index + }); + stream?.close(); + close(); + } + } + }; + } else if ( + protocol == "sse_v1" || + protocol == "sse_v2" || + protocol == "sse_v2.1" || + protocol == "sse_v3" + ) { + // latest API format. v2 introduces sending diffs for intermediate outputs in generative functions, which makes payloads lighter. + // v3 only closes the stream when the backend sends the close stream message. + fire_event({ + type: "status", + stage: "pending", + queue: true, + endpoint: _endpoint, + fn_index, + time: new Date() + }); + let hostname = ""; + if ( + typeof window !== "undefined" && + typeof document !== "undefined" + ) { + hostname = window?.location?.hostname; + } + + let hfhubdev = "dev.spaces.huggingface.tech"; + const origin = hostname.includes(".dev.") + ? `https://moon-${hostname.split(".")[1]}.${hfhubdev}` + : `https://huggingface.co`; + + const is_iframe = + typeof window !== "undefined" && + typeof document !== "undefined" && + window.parent != window; + const is_zerogpu_space = dependency.zerogpu && config.space_id; + const zerogpu_auth_promise = + is_iframe && is_zerogpu_space + ? post_message("zerogpu-headers", origin) + : Promise.resolve(null); + const post_data_promise = zerogpu_auth_promise.then((headers) => { + return post_data( + `${config.root}/queue/join?${url_params}`, + { + ...payload, + session_hash + }, + headers + ); + }); + post_data_promise.then(async ([response, status]: any) => { + if (status === 503) { + fire_event({ + type: "status", + stage: "error", + message: QUEUE_FULL_MSG, + queue: true, + endpoint: _endpoint, + fn_index, + time: new Date() + }); + } else if (status !== 200) { + fire_event({ + type: "status", + stage: "error", + message: BROKEN_CONNECTION_MSG, + queue: true, + endpoint: _endpoint, + fn_index, + time: new Date() + }); + } else { + event_id = response.event_id as string; + let callback = async function (_data: object): Promise { + try { + const { type, status, data } = handle_message( + _data, + last_status[fn_index] + ); + + if (type == "heartbeat") { + return; + } + + if (type === "update" && status && !complete) { + // call 'status' listeners + fire_event({ + type: "status", + endpoint: _endpoint, + fn_index, + time: new Date(), + ...status + }); + } else if (type === "complete") { + complete = status; + } else if (type == "unexpected_error") { + console.error("Unexpected error", status?.message); + fire_event({ + type: "status", + stage: "error", + message: + status?.message || "An Unexpected Error Occurred!", + queue: true, + endpoint: _endpoint, + fn_index, + time: new Date() + }); + } else if (type === "log") { + fire_event({ + type: "log", + log: data.log, + level: data.level, + endpoint: _endpoint, + fn_index + }); + return; + } else if (type === "generating") { + fire_event({ + type: "status", + time: new Date(), + ...status, + stage: status?.stage!, + queue: true, + endpoint: _endpoint, + fn_index + }); + if ( + data && + ["sse_v2", "sse_v2.1", "sse_v3"].includes(protocol) + ) { + apply_diff_stream(pending_diff_streams, event_id!, data); + } + } + if (data) { + fire_event({ + type: "data", + time: new Date(), + data: handle_payload( + data.data, + dependency, + config.components, + "output", + options.with_null_state + ), + endpoint: _endpoint, + fn_index + }); + if (data.render_config) { + await handle_render_config(data.render_config); + } + + if (complete) { + fire_event({ + type: "status", + time: new Date(), + ...complete, + stage: status?.stage!, + queue: true, + endpoint: _endpoint, + fn_index + }); + } + } + + if ( + status?.stage === "complete" || + status?.stage === "error" + ) { + if (event_callbacks[event_id!]) { + delete event_callbacks[event_id!]; + } + if (event_id! in pending_diff_streams) { + delete pending_diff_streams[event_id!]; + } + } + } catch (e) { + console.error("Unexpected client exception", e); + fire_event({ + type: "status", + stage: "error", + message: "An Unexpected Error Occurred!", + queue: true, + endpoint: _endpoint, + fn_index, + time: new Date() + }); + if (["sse_v2", "sse_v2.1", "sse_v3"].includes(protocol)) { + close_stream(stream_status, that.abort_controller); + stream_status.open = false; + close(); + } + } + }; + + if (event_id in pending_stream_messages) { + pending_stream_messages[event_id].forEach((msg) => + callback(msg) + ); + delete pending_stream_messages[event_id]; + } + // @ts-ignore + event_callbacks[event_id] = callback; + unclosed_events.add(event_id); + if (!stream_status.open) { + await this.open_stream(); + } + } + }); + } + } + ); + + let done = false; + const values: (IteratorResult | PromiseLike)[] = []; + const resolvers: (( + value: IteratorResult | PromiseLike + ) => void)[] = []; + + function close(): void { + done = true; + while (resolvers.length > 0) + (resolvers.shift() as (typeof resolvers)[0])({ + value: undefined, + done: true + }); + } + + function push( + data: { value: GradioEvent; done: boolean } | PromiseLike + ): void { + if (done) return; + if (resolvers.length > 0) { + (resolvers.shift() as (typeof resolvers)[0])(data); + } else { + values.push(data); + } + } + + function push_error(error: unknown): void { + push(thenable_reject(error)); + close(); + } + + function push_event(event: GradioEvent): void { + push({ value: event, done: false }); + } + + function next(): Promise> { + if (values.length > 0) + return Promise.resolve(values.shift() as (typeof values)[0]); + if (done) return Promise.resolve({ value: undefined, done: true }); + return new Promise((resolve) => resolvers.push(resolve)); + } + + const iterator = { + [Symbol.asyncIterator]: () => iterator, + next, + throw: async (value: unknown) => { + push_error(value); + return next(); + }, + return: async () => { + close(); + return next(); + }, + cancel + }; + + return iterator; + } catch (error) { + console.error("Submit function encountered an error:", error); + throw error; + } +} + +function thenable_reject(error: T): PromiseLike { + return { + then: ( + resolve: (value: never) => PromiseLike, + reject: (error: T) => PromiseLike + ) => reject(error) + }; +} + +function get_endpoint_info( + api_info: ApiInfo, + endpoint: string | number, + api_map: Record, + config: Config +): { + fn_index: number; + endpoint_info: EndpointInfo; + dependency: Dependency; +} { + let fn_index: number; + let endpoint_info: EndpointInfo; + let dependency: Dependency; + + if (typeof endpoint === "number") { + fn_index = endpoint; + endpoint_info = api_info.unnamed_endpoints[fn_index]; + dependency = config.dependencies.find((dep) => dep.id == endpoint)!; + } else { + const trimmed_endpoint = endpoint.replace(/^\//, ""); + + fn_index = api_map[trimmed_endpoint]; + endpoint_info = api_info.named_endpoints[endpoint.trim()]; + dependency = config.dependencies.find( + (dep) => dep.id == api_map[trimmed_endpoint] + )!; + } + + if (typeof fn_index !== "number") { + throw new Error( + "There is no endpoint matching that name of fn_index matching that number." + ); + } + return { fn_index, endpoint_info, dependency }; +} diff --git a/node_modules/@gradio/client/src/utils/upload_files.ts b/node_modules/@gradio/client/src/utils/upload_files.ts new file mode 100644 index 0000000000000000000000000000000000000000..db2f55729d933216b11b8122148d57a93b259f6f --- /dev/null +++ b/node_modules/@gradio/client/src/utils/upload_files.ts @@ -0,0 +1,52 @@ +import type { Client } from ".."; +import { BROKEN_CONNECTION_MSG, UPLOAD_URL } from "../constants"; +import type { UploadResponse } from "../types"; + +export async function upload_files( + this: Client, + root_url: string, + files: (Blob | File)[], + upload_id?: string +): Promise { + const headers: { + Authorization?: string; + } = {}; + if (this?.options?.hf_token) { + headers.Authorization = `Bearer ${this.options.hf_token}`; + } + + const chunkSize = 1000; + const uploadResponses = []; + let response: Response; + + for (let i = 0; i < files.length; i += chunkSize) { + const chunk = files.slice(i, i + chunkSize); + const formData = new FormData(); + chunk.forEach((file) => { + formData.append("files", file); + }); + try { + const upload_url = upload_id + ? `${root_url}/${UPLOAD_URL}?upload_id=${upload_id}` + : `${root_url}/${UPLOAD_URL}`; + + response = await this.fetch(upload_url, { + method: "POST", + body: formData, + headers, + credentials: "include" + }); + } catch (e) { + throw new Error(BROKEN_CONNECTION_MSG + (e as Error).message); + } + if (!response.ok) { + const error_text = await response.text(); + return { error: `HTTP ${response.status}: ${error_text}` }; + } + const output: UploadResponse["files"] = await response.json(); + if (output) { + uploadResponses.push(...output); + } + } + return { files: uploadResponses }; +} diff --git a/node_modules/@gradio/client/src/utils/view_api.ts b/node_modules/@gradio/client/src/utils/view_api.ts new file mode 100644 index 0000000000000000000000000000000000000000..bb65bc2d428df13d509436c167203452f65685cd --- /dev/null +++ b/node_modules/@gradio/client/src/utils/view_api.ts @@ -0,0 +1,70 @@ +import type { ApiInfo, ApiData } from "../types"; +import semiver from "semiver"; +import { API_INFO_URL, BROKEN_CONNECTION_MSG } from "../constants"; +import { Client } from "../client"; +import { SPACE_FETCHER_URL } from "../constants"; +import { join_urls, transform_api_info } from "../helpers/api_info"; + +export async function view_api(this: Client): Promise { + if (this.api_info) return this.api_info; + + const { hf_token } = this.options; + const { config } = this; + + const headers: { + Authorization?: string; + "Content-Type": "application/json"; + } = { "Content-Type": "application/json" }; + + if (hf_token) { + headers.Authorization = `Bearer ${hf_token}`; + } + + if (!config) { + return; + } + + try { + let response: Response; + + if (semiver(config?.version || "2.0.0", "3.30") < 0) { + response = await this.fetch(SPACE_FETCHER_URL, { + method: "POST", + body: JSON.stringify({ + serialize: false, + config: JSON.stringify(config) + }), + headers, + credentials: "include" + }); + } else { + const url = join_urls(config.root, API_INFO_URL); + response = await this.fetch(url, { + headers, + credentials: "include" + }); + } + + if (!response.ok) { + throw new Error(BROKEN_CONNECTION_MSG); + } + + let api_info = (await response.json()) as + | ApiInfo + | { api: ApiInfo }; + if ("api" in api_info) { + api_info = api_info.api; + } + + if ( + api_info.named_endpoints["/predict"] && + !api_info.unnamed_endpoints["0"] + ) { + api_info.unnamed_endpoints[0] = api_info.named_endpoints["/predict"]; + } + + return transform_api_info(api_info, config, this.api_map); + } catch (e) { + "Could not get API info. " + (e as Error).message; + } +} diff --git a/node_modules/@gradio/client/src/vite-env.d.ts b/node_modules/@gradio/client/src/vite-env.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..11f02fe2a0061d6e6e1f271b21da95423b448b32 --- /dev/null +++ b/node_modules/@gradio/client/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/node_modules/@gradio/client/tsconfig.json b/node_modules/@gradio/client/tsconfig.json index 132b1c6b4a220486e7d34b5f664fb8a89874be3c..ddee6c503883f8c697dfd6e464a8cfbab3df3743 100644 --- a/node_modules/@gradio/client/tsconfig.json +++ b/node_modules/@gradio/client/tsconfig.json @@ -7,8 +7,21 @@ "emitDeclarationOnly": true, "outDir": "dist", "declarationMap": true, - "module": "es2020", + "module": "ESNext", + "target": "ES2020", + "useDefineForClassFields": true, + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "skipLibCheck": true, + + /* Bundler */ "moduleResolution": "bundler", - "skipDefaultLibCheck": true + "skipDefaultLibCheck": true, + "allowImportingTsExtensions": true, + "esModuleInterop": true, + "resolveJsonModule": true, + "isolatedModules": true, + + /* Linting */ + "strict": true } } diff --git a/node_modules/@gradio/client/vite.config.js b/node_modules/@gradio/client/vite.config.js index 985554d9e5f20520c5858119392222f52f67475a..257b9baded27725aa23acb8164e824635eaed908 100644 --- a/node_modules/@gradio/client/vite.config.js +++ b/node_modules/@gradio/client/vite.config.js @@ -1,38 +1,45 @@ import { defineConfig } from "vite"; import { svelte } from "@sveltejs/vite-plugin-svelte"; -import { fileURLToPath } from "url"; -import path from "path"; -const __dirname = fileURLToPath(new URL(".", import.meta.url)); -export default defineConfig({ - build: { - lib: { - entry: "src/index.ts", - formats: ["es"] - }, - rollupOptions: { - input: "src/index.ts", - output: { - dir: "dist" - } - } - }, - plugins: [ - svelte() - // { - // name: "resolve-gradio-client", - // enforce: "pre", - // resolveId(id) { - // if (id === "@gradio/client") { - // return path.join(__dirname, "src", "index.ts"); - // } - // } - // } - ], +const TEST_MODE = process.env.TEST_MODE || "happy-dom"; - ssr: { - target: "node", - format: "esm", - noExternal: ["ws", "semiver", "@gradio/upload"] +export default defineConfig(({ mode }) => { + if (mode === "preview") { + return { + entry: "index.html" + }; } + return { + build: { + lib: { + entry: "src/index.ts", + formats: ["es"], + fileName: (format) => `index.${format}.js` + }, + rollupOptions: { + input: "src/index.ts", + output: { + dir: "dist" + } + } + }, + plugins: [svelte()], + + mode: process.env.MODE || "development", + test: { + include: ["./src/test/*.test.*"], + environment: TEST_MODE + }, + ssr: { + target: "node", + format: "esm", + noExternal: [ + "ws", + "semiver", + "bufferutil", + "@gradio/upload", + "fetch-event-stream" + ] + } + }; }); diff --git a/node_modules/@inquirer/confirm/LICENSE b/node_modules/@inquirer/confirm/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..6a10a8efe516e142e0f1cd556830460b2cc89d02 --- /dev/null +++ b/node_modules/@inquirer/confirm/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2023 Simon Boudrias + +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/node_modules/@inquirer/confirm/README.md b/node_modules/@inquirer/confirm/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4d4371d600f99823e5d12d79492c8cfe83baa855 --- /dev/null +++ b/node_modules/@inquirer/confirm/README.md @@ -0,0 +1,54 @@ +# `@inquirer/confirm` + +Simple interactive command line prompt to gather boolean input from users. + +![Confirm prompt](https://cdn.rawgit.com/SBoudrias/Inquirer.js/28ae8337ba51d93e359ef4f7ee24e79b69898962/assets/screenshots/confirm.svg) + +# Installation + +```sh +npm install @inquirer/confirm + +yarn add @inquirer/confirm +``` + +# Usage + +```js +import confirm from '@inquirer/confirm'; + +const answer = await confirm({ message: 'Continue?' }); +``` + +## Options + +| Property | Type | Required | Description | +| ----------- | ----------------------- | -------- | ------------------------------------------------------- | +| message | `string` | yes | The question to ask | +| default | `boolean` | no | Default answer (true or false) | +| transformer | `(boolean) => string` | no | Transform the prompt printed message to a custom string | +| theme | [See Theming](#Theming) | no | Customize look of the prompt. | + +## Theming + +You can theme a prompt by passing a `theme` object option. The theme object only need to includes the keys you wish to modify, we'll fallback on the defaults for the rest. + +```ts +type Theme = { + prefix: string; + spinner: { + interval: number; + frames: string[]; + }; + style: { + answer: (text: string) => string; + message: (text: string) => string; + defaultAnswer: (text: string) => string; + }; +}; +``` + +# License + +Copyright (c) 2023 Simon Boudrias (twitter: [@vaxilart](https://twitter.com/Vaxilart))
+Licensed under the MIT license. diff --git a/node_modules/@inquirer/confirm/dist/cjs/index.js b/node_modules/@inquirer/confirm/dist/cjs/index.js new file mode 100644 index 0000000000000000000000000000000000000000..08874ff0b18b63304f20077dd2fa0075bc2c768f --- /dev/null +++ b/node_modules/@inquirer/confirm/dist/cjs/index.js @@ -0,0 +1,35 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const core_1 = require("@inquirer/core"); +exports.default = (0, core_1.createPrompt)((config, done) => { + const { transformer = (answer) => (answer ? 'yes' : 'no') } = config; + const [status, setStatus] = (0, core_1.useState)('pending'); + const [value, setValue] = (0, core_1.useState)(''); + const theme = (0, core_1.makeTheme)(config.theme); + const prefix = (0, core_1.usePrefix)({ theme }); + (0, core_1.useKeypress)((key, rl) => { + if ((0, core_1.isEnterKey)(key)) { + let answer = config.default !== false; + if (/^(y|yes)/i.test(value)) + answer = true; + else if (/^(n|no)/i.test(value)) + answer = false; + setValue(transformer(answer)); + setStatus('done'); + done(answer); + } + else { + setValue(rl.line); + } + }); + let formattedValue = value; + let defaultValue = ''; + if (status === 'done') { + formattedValue = theme.style.answer(value); + } + else { + defaultValue = ` ${theme.style.defaultAnswer(config.default === false ? 'y/N' : 'Y/n')}`; + } + const message = theme.style.message(config.message); + return `${prefix} ${message}${defaultValue} ${formattedValue}`; +}); diff --git a/node_modules/@inquirer/confirm/dist/cjs/types/index.d.ts b/node_modules/@inquirer/confirm/dist/cjs/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d3d323add1e962e96e7547ceaae4d3208ef92360 --- /dev/null +++ b/node_modules/@inquirer/confirm/dist/cjs/types/index.d.ts @@ -0,0 +1,10 @@ +import { type Theme } from '@inquirer/core'; +import type { PartialDeep } from '@inquirer/type'; +type ConfirmConfig = { + message: string; + default?: boolean; + transformer?: (value: boolean) => string; + theme?: PartialDeep; +}; +declare const _default: import("@inquirer/type").Prompt; +export default _default; diff --git a/node_modules/@inquirer/confirm/dist/esm/index.mjs b/node_modules/@inquirer/confirm/dist/esm/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6e5058beea73b83ef13d8cb67712eb0605c7a0d1 --- /dev/null +++ b/node_modules/@inquirer/confirm/dist/esm/index.mjs @@ -0,0 +1,33 @@ +import { createPrompt, useState, useKeypress, isEnterKey, usePrefix, makeTheme, } from '@inquirer/core'; +export default createPrompt((config, done) => { + const { transformer = (answer) => (answer ? 'yes' : 'no') } = config; + const [status, setStatus] = useState('pending'); + const [value, setValue] = useState(''); + const theme = makeTheme(config.theme); + const prefix = usePrefix({ theme }); + useKeypress((key, rl) => { + if (isEnterKey(key)) { + let answer = config.default !== false; + if (/^(y|yes)/i.test(value)) + answer = true; + else if (/^(n|no)/i.test(value)) + answer = false; + setValue(transformer(answer)); + setStatus('done'); + done(answer); + } + else { + setValue(rl.line); + } + }); + let formattedValue = value; + let defaultValue = ''; + if (status === 'done') { + formattedValue = theme.style.answer(value); + } + else { + defaultValue = ` ${theme.style.defaultAnswer(config.default === false ? 'y/N' : 'Y/n')}`; + } + const message = theme.style.message(config.message); + return `${prefix} ${message}${defaultValue} ${formattedValue}`; +}); diff --git a/node_modules/@inquirer/confirm/dist/esm/types/index.d.mts b/node_modules/@inquirer/confirm/dist/esm/types/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..d3d323add1e962e96e7547ceaae4d3208ef92360 --- /dev/null +++ b/node_modules/@inquirer/confirm/dist/esm/types/index.d.mts @@ -0,0 +1,10 @@ +import { type Theme } from '@inquirer/core'; +import type { PartialDeep } from '@inquirer/type'; +type ConfirmConfig = { + message: string; + default?: boolean; + transformer?: (value: boolean) => string; + theme?: PartialDeep; +}; +declare const _default: import("@inquirer/type").Prompt; +export default _default; diff --git a/node_modules/@inquirer/confirm/package.json b/node_modules/@inquirer/confirm/package.json new file mode 100644 index 0000000000000000000000000000000000000000..eabd5a0db23ac52f21ea958e6ec31390c03d9a8a --- /dev/null +++ b/node_modules/@inquirer/confirm/package.json @@ -0,0 +1,131 @@ +{ + "_from": "@inquirer/confirm@^3.0.0", + "_id": "@inquirer/confirm@3.1.10", + "_inBundle": false, + "_integrity": "sha512-/aAHu83Njy6yf44T+ZrRPUkMcUqprrOiIKsyMvf9jOV+vF5BNb2ja1aLP33MK36W8eaf91MTL/mU/e6METuENg==", + "_location": "/@inquirer/confirm", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@inquirer/confirm@^3.0.0", + "name": "@inquirer/confirm", + "escapedName": "@inquirer%2fconfirm", + "scope": "@inquirer", + "rawSpec": "^3.0.0", + "saveSpec": null, + "fetchSpec": "^3.0.0" + }, + "_requiredBy": [ + "/msw" + ], + "_resolved": "https://registry.npmjs.org/@inquirer/confirm/-/confirm-3.1.10.tgz", + "_shasum": "8e8b36b1e41d6736d6ac90d1221c9e1ec948eb7a", + "_spec": "@inquirer/confirm@^3.0.0", + "_where": "/Users/sylvainfiloni/Documents/HuggingFace_Projects/live-vision/node_modules/msw", + "author": { + "name": "Simon Boudrias", + "email": "admin@simonboudrias.com" + }, + "bugs": { + "url": "https://github.com/SBoudrias/Inquirer.js/issues" + }, + "bundleDependencies": false, + "dependencies": { + "@inquirer/core": "^8.2.3", + "@inquirer/type": "^1.3.3" + }, + "deprecated": false, + "description": "Inquirer confirm prompt", + "devDependencies": { + "@inquirer/testing": "^2.1.22" + }, + "engines": { + "node": ">=18" + }, + "exports": { + ".": { + "import": { + "types": "./dist/esm/types/index.d.mts", + "default": "./dist/esm/index.mjs" + }, + "require": { + "types": "./dist/cjs/types/index.d.ts", + "default": "./dist/cjs/index.js" + } + } + }, + "files": [ + "dist/**/*" + ], + "gitHead": "cc52a353abb1b7f3b3dc81b9e6da7ed478099dbf", + "homepage": "https://github.com/SBoudrias/Inquirer.js/blob/master/packages/confirm/README.md", + "keywords": [ + "answer", + "answers", + "ask", + "base", + "cli", + "command", + "command-line", + "confirm", + "enquirer", + "generate", + "generator", + "hyper", + "input", + "inquire", + "inquirer", + "interface", + "iterm", + "javascript", + "menu", + "node", + "nodejs", + "prompt", + "promptly", + "prompts", + "question", + "readline", + "scaffold", + "scaffolder", + "scaffolding", + "stdin", + "stdout", + "terminal", + "tty", + "ui", + "yeoman", + "yo", + "zsh" + ], + "license": "MIT", + "main": "./dist/cjs/index.js", + "name": "@inquirer/confirm", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/SBoudrias/Inquirer.js.git" + }, + "scripts": { + "attw": "attw --pack", + "dev": "tsc -p ./tsconfig.json --watch", + "tsc": "yarn run tsc:esm && yarn run tsc:cjs", + "tsc:cjs": "rm -rf dist/cjs && tsc -p ./tsconfig.cjs.json && node ../../tools/fix-ext.mjs", + "tsc:esm": "rm -rf dist/esm && tsc -p ./tsconfig.json" + }, + "sideEffects": false, + "typings": "./dist/cjs/types/index.d.ts", + "version": "3.1.10", + "warnings": [ + { + "code": "ENOTSUP", + "required": { + "node": ">=18" + }, + "pkgid": "@inquirer/confirm@3.1.10" + } + ] +} diff --git a/node_modules/@inquirer/core/LICENSE b/node_modules/@inquirer/core/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..6a10a8efe516e142e0f1cd556830460b2cc89d02 --- /dev/null +++ b/node_modules/@inquirer/core/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2023 Simon Boudrias + +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/node_modules/@inquirer/core/README.md b/node_modules/@inquirer/core/README.md new file mode 100644 index 0000000000000000000000000000000000000000..90e11cc96ae9ad99b3ef89ec58164faf1550dae7 --- /dev/null +++ b/node_modules/@inquirer/core/README.md @@ -0,0 +1,222 @@ +# `@inquirer/core` + +The `@inquirer/core` package is the library enabling the creation of Inquirer prompts. + +It aims to implements a lightweight API similar to React hooks - but without JSX. + +# Installation + +```sh +npm install @inquirer/core + +yarn add @inquirer/core +``` + +# Usage + +```ts +import chalk from 'chalk'; +import { + createPrompt, + useState, + useKeypress, + isEnterKey, + usePrefix, +} from '@inquirer/core'; + +const confirm = createPrompt( + (config, done) => { + const [status, setStatus] = useState('pending'); + const [value, setValue] = useState(''); + const prefix = usePrefix({}); + + useKeypress((key, rl) => { + if (isEnterKey(key)) { + const answer = value ? /^y(es)?/i.test(value) : config.default !== false; + setValue(answer ? 'yes' : 'no'); + setStatus('done'); + done(answer); + } else { + setValue(rl.line); + } + }); + + let formattedValue = value; + let defaultValue = ''; + if (status === 'done') { + formattedValue = chalk.cyan(value); + } else { + defaultValue = chalk.dim(config.default === false ? ' (y/N)' : ' (Y/n)'); + } + + const message = chalk.bold(config.message); + return `${prefix} ${message}${defaultValue} ${formattedValue}`; + }, +); + +/** + * Which then can be used like this: + */ +const answer = await confirm({ message: 'Do you want to continue?' }); +``` + +See more examples: + +- [Confirm Prompt](https://github.com/SBoudrias/Inquirer.js/blob/master/packages/confirm/src/index.mts) +- [Input Prompt](https://github.com/SBoudrias/Inquirer.js/blob/master/packages/input/src/index.mts) +- [Password Prompt](https://github.com/SBoudrias/Inquirer.js/blob/master/packages/password/src/index.mts) +- [Editor Prompt](https://github.com/SBoudrias/Inquirer.js/blob/master/packages/editor/src/index.mts) +- [Select Prompt](https://github.com/SBoudrias/Inquirer.js/blob/master/packages/select/src/index.mts) +- [Checkbox Prompt](https://github.com/SBoudrias/Inquirer.js/blob/master/packages/checkbox/src/index.mts) +- [Rawlist Prompt](https://github.com/SBoudrias/Inquirer.js/blob/master/packages/rawlist/src/index.mts) +- [Expand Prompt](https://github.com/SBoudrias/Inquirer.js/blob/master/packages/expand/src/index.mts) + +## API + +### `createPrompt(viewFn)` + +The `createPrompt` function returns an asynchronous function that returns a cancelable promise resolving to the valid answer a user submit. This prompt function takes the prompt configuration as its first argument (this is defined by each prompt), and the context options as a second argument. + +The prompt configuration is unique to each prompt. The context options are: + +| Property | Type | Required | Description | +| ----------------- | ----------------------- | -------- | ------------------------------------------------------------ | +| input | `NodeJS.ReadableStream` | no | The stdin stream (defaults to `process.stdin`) | +| output | `NodeJS.WritableStream` | no | The stdout stream (defaults to `process.stdout`) | +| clearPromptOnDone | `boolean` | no | If true, we'll clear the screen after the prompt is answered | + +The cancelable promise exposes a `cancel` method that'll exit the prompt and reject the promise. + +#### Typescript + +If using typescript, `createPrompt` takes 2 generic arguments (ex `createPrompt()`) + +The first one is the type of the resolved value; `function createPrompt(): Promise {}` + +The second one is the type of the prompt config; in other words the interface the created prompt will provide to users. + +### Hooks + +Hooks can only be called within the prompt function and are used to handle state and events. + +Those hooks are matching the React hooks API: + +- `useState` +- `useRef` +- `useEffect` +- `useMemo` + +And those are custom utilities from Inquirer: + +- `useKeypress` +- `usePagination` +- `usePrefix` + +### Key utilities + +Listening for keypress events inside an inquirer prompt is a very common pattern. To ease this, we export a few utility functions taking in the keypress event object and return a boolean: + +- `isEnterKey()` +- `isBackspaceKey()` +- `isSpaceKey()` +- `isUpKey()` - Note: this utility will handle vim and emacs keybindings (up, `k`, and `ctrl+p`) +- `isDownKey()` - Note: this utility will handle vim and emacs keybindings (down, `j`, and `ctrl+n`) +- `isNumberKey()` one of 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 + +### `usePagination` + +When looping through a long list of options (like in the `select` prompt), paginating the results appearing on the screen at once can be necessary. The `usePagination` hook is the utility used within the `select` and `checkbox` prompts to cycle through the list of options. + +Pagination works by taking in the list of options and returning a subset of the rendered items that fit within the page. The hook takes in a few options. It needs a list of options (`items`), and a `pageSize` which is the number of lines to be rendered. The `active` index is the index of the currently selected/selectable item. The `loop` option is a boolean that indicates if the list should loop around when reaching the end: this is the default behavior. The pagination hook renders items only as necessary, so it takes a function that can render an item at an index, including an `active` state, called `renderItem`. + +```js +export default createPrompt((config, done) => { + const [active, setActive] = useState(0); + + const allChoices = config.choices.map((choice) => choice.name); + + const page = usePagination({ + items: allChoices, + active: active, + renderItem: ({ item, index, isActive }) => `${isActive ? ">" : " "}${index}. ${item.toString()}` + pageSize: config.pageSize, + loop: config.loop, + }); + + return `... ${page}`; +}); +``` + +### Theming + +Theming utilities will allow you to expose customization of the prompt style. Inquirer also has a few standard theme values shared across all the official prompts. + +To allow standard customization: + +```ts +import { createPrompt, usePrefix, makeTheme, type Theme } from '@inquirer/core'; +import type { PartialDeep } from '@inquirer/type'; + +type PromptConfig = { + theme?: PartialDeep; +}; + +export default createPrompt((config, done) => { + const theme = makeTheme(config.theme); + + const prefix = usePrefix({ isLoading, theme }); + + return `${prefix} ${theme.style.highlight('hello')}`; +}); +``` + +To setup a custom theme: + +```ts +import { createPrompt, makeTheme, type Theme } from '@inquirer/core'; +import type { PartialDeep } from '@inquirer/type'; + +type PromptTheme = {}; + +const promptTheme: PromptTheme = { + icon: '!', +}; + +type PromptConfig = { + theme?: PartialDeep>; +}; + +export default createPrompt((config, done) => { + const theme = makeTheme(promptTheme, config.theme); + + const prefix = usePrefix({ isLoading, theme }); + + return `${prefix} ${theme.icon}`; +}); +``` + +The [default theme keys cover](https://github.com/SBoudrias/Inquirer.js/blob/theme/packages/core/src/lib/theme.mts): + +```ts +type DefaultTheme = { + prefix: string; + spinner: { + interval: number; + frames: string[]; + }; + style: { + answer: (text: string) => string; + message: (text: string) => string; + error: (text: string) => string; + defaultAnswer: (text: string) => string; + help: (text: string) => string; + highlight: (text: string) => string; + key: (text: string) => string; + }; +}; +``` + +# License + +Copyright (c) 2023 Simon Boudrias (twitter: [@vaxilart](https://twitter.com/Vaxilart))
+Licensed under the MIT license. diff --git a/node_modules/@inquirer/core/dist/cjs/index.js b/node_modules/@inquirer/core/dist/cjs/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1196a96dd4f784fc284111d927ba49456f78002f --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/index.js @@ -0,0 +1,39 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __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.Separator = exports.createPrompt = exports.usePagination = exports.makeTheme = exports.useKeypress = exports.useRef = exports.useMemo = exports.useEffect = exports.useState = exports.usePrefix = void 0; +__exportStar(require('./lib/key.js'), exports); +__exportStar(require('./lib/errors.js'), exports); +var use_prefix_mjs_1 = require('./lib/use-prefix.js'); +Object.defineProperty(exports, "usePrefix", { enumerable: true, get: function () { return use_prefix_mjs_1.usePrefix; } }); +var use_state_mjs_1 = require('./lib/use-state.js'); +Object.defineProperty(exports, "useState", { enumerable: true, get: function () { return use_state_mjs_1.useState; } }); +var use_effect_mjs_1 = require('./lib/use-effect.js'); +Object.defineProperty(exports, "useEffect", { enumerable: true, get: function () { return use_effect_mjs_1.useEffect; } }); +var use_memo_mjs_1 = require('./lib/use-memo.js'); +Object.defineProperty(exports, "useMemo", { enumerable: true, get: function () { return use_memo_mjs_1.useMemo; } }); +var use_ref_mjs_1 = require('./lib/use-ref.js'); +Object.defineProperty(exports, "useRef", { enumerable: true, get: function () { return use_ref_mjs_1.useRef; } }); +var use_keypress_mjs_1 = require('./lib/use-keypress.js'); +Object.defineProperty(exports, "useKeypress", { enumerable: true, get: function () { return use_keypress_mjs_1.useKeypress; } }); +var make_theme_mjs_1 = require('./lib/make-theme.js'); +Object.defineProperty(exports, "makeTheme", { enumerable: true, get: function () { return make_theme_mjs_1.makeTheme; } }); +var use_pagination_mjs_1 = require('./lib/pagination/use-pagination.js'); +Object.defineProperty(exports, "usePagination", { enumerable: true, get: function () { return use_pagination_mjs_1.usePagination; } }); +var create_prompt_mjs_1 = require('./lib/create-prompt.js'); +Object.defineProperty(exports, "createPrompt", { enumerable: true, get: function () { return create_prompt_mjs_1.createPrompt; } }); +var Separator_mjs_1 = require('./lib/Separator.js'); +Object.defineProperty(exports, "Separator", { enumerable: true, get: function () { return Separator_mjs_1.Separator; } }); diff --git a/node_modules/@inquirer/core/dist/cjs/lib/Separator.js b/node_modules/@inquirer/core/dist/cjs/lib/Separator.js new file mode 100644 index 0000000000000000000000000000000000000000..67af04bf07206caf35f656620df321bf136108c9 --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/lib/Separator.js @@ -0,0 +1,35 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Separator = void 0; +const chalk_1 = __importDefault(require("chalk")); +const figures_1 = __importDefault(require("@inquirer/figures")); +/** + * Separator object + * Used to space/separate choices group + */ +class Separator { + constructor(separator) { + Object.defineProperty(this, "separator", { + enumerable: true, + configurable: true, + writable: true, + value: chalk_1.default.dim(Array.from({ length: 15 }).join(figures_1.default.line)) + }); + Object.defineProperty(this, "type", { + enumerable: true, + configurable: true, + writable: true, + value: 'separator' + }); + if (separator) { + this.separator = separator; + } + } + static isSeparator(choice) { + return Boolean(choice && choice.type === 'separator'); + } +} +exports.Separator = Separator; diff --git a/node_modules/@inquirer/core/dist/cjs/lib/create-prompt.js b/node_modules/@inquirer/core/dist/cjs/lib/create-prompt.js new file mode 100644 index 0000000000000000000000000000000000000000..f3f9f5c464b1eb85047757c1971ada63219b74ac --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/lib/create-prompt.js @@ -0,0 +1,119 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createPrompt = void 0; +const readline = __importStar(require("node:readline")); +const type_1 = require("@inquirer/type"); +const mute_stream_1 = __importDefault(require("mute-stream")); +const signal_exit_1 = require("signal-exit"); +const screen_manager_mjs_1 = __importDefault(require('./screen-manager.js')); +const hook_engine_mjs_1 = require('./hook-engine.js'); +const errors_mjs_1 = require('./errors.js'); +function createPrompt(view) { + const prompt = (config, context) => { + var _a, _b; + // Default `input` to stdin + const input = (_a = context === null || context === void 0 ? void 0 : context.input) !== null && _a !== void 0 ? _a : process.stdin; + // Add mute capabilities to the output + const output = new mute_stream_1.default(); + output.pipe((_b = context === null || context === void 0 ? void 0 : context.output) !== null && _b !== void 0 ? _b : process.stdout); + const rl = readline.createInterface({ + terminal: true, + input, + output, + }); + const screen = new screen_manager_mjs_1.default(rl); + let cancel = () => { }; + const answer = new type_1.CancelablePromise((resolve, reject) => { + (0, hook_engine_mjs_1.withHooks)(rl, (store) => { + function checkCursorPos() { + screen.checkCursorPos(); + } + const removeExitListener = (0, signal_exit_1.onExit)((code, signal) => { + onExit(); + reject(new errors_mjs_1.ExitPromptError(`User force closed the prompt with ${code} ${signal}`)); + }); + function onExit() { + try { + store.hooksCleanup.forEach((cleanFn) => { + cleanFn === null || cleanFn === void 0 ? void 0 : cleanFn(); + }); + } + catch (error) { + reject(error); + } + if (context === null || context === void 0 ? void 0 : context.clearPromptOnDone) { + screen.clean(); + } + else { + screen.clearContent(); + } + screen.done(); + removeExitListener(); + store.rl.input.removeListener('keypress', checkCursorPos); + } + cancel = () => { + onExit(); + reject(new errors_mjs_1.CancelPromptError()); + }; + function done(value) { + // Delay execution to let time to the hookCleanup functions to registers. + setImmediate(() => { + onExit(); + // Finally we resolve our promise + resolve(value); + }); + } + function workLoop() { + store.index = 0; + try { + const nextView = view(config, done); + const [content, bottomContent] = typeof nextView === 'string' ? [nextView] : nextView; + screen.render(content, bottomContent); + hook_engine_mjs_1.effectScheduler.run(); + } + catch (error) { + onExit(); + reject(error); + } + } + store.handleChange = () => workLoop(); + workLoop(); + // Re-renders only happen when the state change; but the readline cursor could change position + // and that also requires a re-render (and a manual one because we mute the streams). + // We set the listener after the initial workLoop to avoid a double render if render triggered + // by a state change sets the cursor to the right position. + store.rl.input.on('keypress', checkCursorPos); + }); + }); + answer.cancel = cancel; + return answer; + }; + return prompt; +} +exports.createPrompt = createPrompt; diff --git a/node_modules/@inquirer/core/dist/cjs/lib/errors.js b/node_modules/@inquirer/core/dist/cjs/lib/errors.js new file mode 100644 index 0000000000000000000000000000000000000000..1df5b8244c2c987f160025c7da6d3672f313c38b --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/lib/errors.js @@ -0,0 +1,24 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ValidationError = exports.HookError = exports.ExitPromptError = exports.CancelPromptError = void 0; +class CancelPromptError extends Error { + constructor() { + super(...arguments); + Object.defineProperty(this, "message", { + enumerable: true, + configurable: true, + writable: true, + value: 'Prompt was canceled' + }); + } +} +exports.CancelPromptError = CancelPromptError; +class ExitPromptError extends Error { +} +exports.ExitPromptError = ExitPromptError; +class HookError extends Error { +} +exports.HookError = HookError; +class ValidationError extends Error { +} +exports.ValidationError = ValidationError; diff --git a/node_modules/@inquirer/core/dist/cjs/lib/hook-engine.js b/node_modules/@inquirer/core/dist/cjs/lib/hook-engine.js new file mode 100644 index 0000000000000000000000000000000000000000..3f1db0a45c30a24ce2d906d5e8a49c779f898b71 --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/lib/hook-engine.js @@ -0,0 +1,104 @@ +"use strict"; +/* eslint @typescript-eslint/no-explicit-any: ["off"] */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.effectScheduler = exports.handleChange = exports.withPointer = exports.withUpdates = exports.readline = exports.withHooks = void 0; +const node_async_hooks_1 = require("node:async_hooks"); +const errors_mjs_1 = require('./errors.js'); +const hookStorage = new node_async_hooks_1.AsyncLocalStorage(); +function createStore(rl) { + const store = { + rl, + hooks: [], + hooksCleanup: [], + hooksEffect: [], + index: 0, + handleChange() { }, + }; + return store; +} +// Run callback in with the hook engine setup. +function withHooks(rl, cb) { + const store = createStore(rl); + return hookStorage.run(store, () => { + cb(store); + }); +} +exports.withHooks = withHooks; +// Safe getStore utility that'll return the store or throw if undefined. +function getStore() { + const store = hookStorage.getStore(); + if (!store) { + throw new errors_mjs_1.HookError('[Inquirer] Hook functions can only be called from within a prompt'); + } + return store; +} +function readline() { + return getStore().rl; +} +exports.readline = readline; +// Merge state updates happening within the callback function to avoid multiple renders. +function withUpdates(fn) { + const wrapped = (...args) => { + const store = getStore(); + let shouldUpdate = false; + const oldHandleChange = store.handleChange; + store.handleChange = () => { + shouldUpdate = true; + }; + const returnValue = fn(...args); + if (shouldUpdate) { + oldHandleChange(); + } + store.handleChange = oldHandleChange; + return returnValue; + }; + return node_async_hooks_1.AsyncResource.bind(wrapped); +} +exports.withUpdates = withUpdates; +function withPointer(cb) { + const store = getStore(); + const { index } = store; + const pointer = { + get() { + return store.hooks[index]; + }, + set(value) { + store.hooks[index] = value; + }, + initialized: index in store.hooks, + }; + const returnValue = cb(pointer); + store.index++; + return returnValue; +} +exports.withPointer = withPointer; +function handleChange() { + getStore().handleChange(); +} +exports.handleChange = handleChange; +exports.effectScheduler = { + queue(cb) { + const store = getStore(); + const { index } = store; + store.hooksEffect.push(() => { + var _a, _b; + (_b = (_a = store.hooksCleanup)[index]) === null || _b === void 0 ? void 0 : _b.call(_a); + const cleanFn = cb(readline()); + if (cleanFn != null && typeof cleanFn !== 'function') { + throw new errors_mjs_1.ValidationError('useEffect return value must be a cleanup function or nothing.'); + } + store.hooksCleanup[index] = cleanFn; + }); + }, + run() { + const store = getStore(); + withUpdates(() => { + store.hooksEffect.forEach((effect) => { + effect(); + }); + // Warning: Clean the hooks before exiting the `withUpdates` block. + // Failure to do so means an updates would hit the same effects again. + store.hooksEffect.length = 0; + })(); + }, +}; diff --git a/node_modules/@inquirer/core/dist/cjs/lib/key.js b/node_modules/@inquirer/core/dist/cjs/lib/key.js new file mode 100644 index 0000000000000000000000000000000000000000..a6c0c20f461f3f4a961de3cbf589551c862b16d5 --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/lib/key.js @@ -0,0 +1,27 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isEnterKey = exports.isNumberKey = exports.isBackspaceKey = exports.isSpaceKey = exports.isDownKey = exports.isUpKey = void 0; +const isUpKey = (key) => +// The up key +key.name === 'up' || + // Vim keybinding + key.name === 'k' || + // Emacs keybinding + (key.ctrl && key.name === 'p'); +exports.isUpKey = isUpKey; +const isDownKey = (key) => +// The down key +key.name === 'down' || + // Vim keybinding + key.name === 'j' || + // Emacs keybinding + (key.ctrl && key.name === 'n'); +exports.isDownKey = isDownKey; +const isSpaceKey = (key) => key.name === 'space'; +exports.isSpaceKey = isSpaceKey; +const isBackspaceKey = (key) => key.name === 'backspace'; +exports.isBackspaceKey = isBackspaceKey; +const isNumberKey = (key) => '123456789'.includes(key.name); +exports.isNumberKey = isNumberKey; +const isEnterKey = (key) => key.name === 'enter' || key.name === 'return'; +exports.isEnterKey = isEnterKey; diff --git a/node_modules/@inquirer/core/dist/cjs/lib/make-theme.js b/node_modules/@inquirer/core/dist/cjs/lib/make-theme.js new file mode 100644 index 0000000000000000000000000000000000000000..96f6ed62c0d72d8fa6da1e65ddbab340d2cd9ddc --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/lib/make-theme.js @@ -0,0 +1,34 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.makeTheme = void 0; +const theme_mjs_1 = require('./theme.js'); +function isPlainObject(value) { + if (typeof value !== 'object' || value === null) + return false; + let proto = value; + while (Object.getPrototypeOf(proto) !== null) { + proto = Object.getPrototypeOf(proto); + } + return Object.getPrototypeOf(value) === proto; +} +function deepMerge(...objects) { + const output = {}; + for (const obj of objects) { + for (const [key, value] of Object.entries(obj)) { + const prevValue = output[key]; + output[key] = + isPlainObject(prevValue) && isPlainObject(value) + ? deepMerge(prevValue, value) + : value; + } + } + return output; +} +function makeTheme(...themes) { + const themesToMerge = [ + theme_mjs_1.defaultTheme, + ...themes.filter((theme) => theme != null), + ]; + return deepMerge(...themesToMerge); +} +exports.makeTheme = makeTheme; diff --git a/node_modules/@inquirer/core/dist/cjs/lib/pagination/lines.js b/node_modules/@inquirer/core/dist/cjs/lib/pagination/lines.js new file mode 100644 index 0000000000000000000000000000000000000000..5b417f68930f4ed9cf9e5b9c7345bf932151e8cd --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/lib/pagination/lines.js @@ -0,0 +1,63 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.lines = void 0; +const utils_mjs_1 = require('../utils.js'); +function split(content, width) { + return (0, utils_mjs_1.breakLines)(content, width).split('\n'); +} +/** + * Rotates an array of items by an integer number of positions. + * @param {number} count The number of positions to rotate by + * @param {T[]} items The items to rotate + */ +function rotate(count, items) { + const max = items.length; + const offset = ((count % max) + max) % max; + return [...items.slice(offset), ...items.slice(0, offset)]; +} +/** + * Renders a page of items as lines that fit within the given width ensuring + * that the number of lines is not greater than the page size, and the active + * item renders at the provided position, while prioritizing that as many lines + * of the active item get rendered as possible. + */ +function lines({ items, width, renderItem, active, position: requested, pageSize, }) { + const layouts = items.map((item, index) => ({ + item, + index, + isActive: index === active, + })); + const layoutsInPage = rotate(active - requested, layouts).slice(0, pageSize); + const renderItemAt = (index) => split(renderItem(layoutsInPage[index]), width); + // Create a blank array of lines for the page + const pageBuffer = Array.from({ length: pageSize }); + // Render the active item to decide the position + const activeItem = renderItemAt(requested).slice(0, pageSize); + const position = requested + activeItem.length <= pageSize ? requested : pageSize - activeItem.length; + // Add the lines of the active item into the page + pageBuffer.splice(position, activeItem.length, ...activeItem); + // Fill the page under the active item + let bufferPointer = position + activeItem.length; + let layoutPointer = requested + 1; + while (bufferPointer < pageSize && layoutPointer < layoutsInPage.length) { + for (const line of renderItemAt(layoutPointer)) { + pageBuffer[bufferPointer++] = line; + if (bufferPointer >= pageSize) + break; + } + layoutPointer++; + } + // Fill the page over the active item + bufferPointer = position - 1; + layoutPointer = requested - 1; + while (bufferPointer >= 0 && layoutPointer >= 0) { + for (const line of renderItemAt(layoutPointer).reverse()) { + pageBuffer[bufferPointer--] = line; + if (bufferPointer < 0) + break; + } + layoutPointer--; + } + return pageBuffer.filter((line) => typeof line === 'string'); +} +exports.lines = lines; diff --git a/node_modules/@inquirer/core/dist/cjs/lib/pagination/position.js b/node_modules/@inquirer/core/dist/cjs/lib/pagination/position.js new file mode 100644 index 0000000000000000000000000000000000000000..50b29a7bca1f684c691943305567c4ec0cd37ec3 --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/lib/pagination/position.js @@ -0,0 +1,32 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.infinite = exports.finite = void 0; +/** + * Creates the next position for the active item considering a finite list of + * items to be rendered on a page. + */ +function finite({ active, pageSize, total, }) { + const middle = Math.floor(pageSize / 2); + if (total <= pageSize || active < middle) + return active; + if (active >= total - middle) + return active + pageSize - total; + return middle; +} +exports.finite = finite; +/** + * Creates the next position for the active item considering an infinitely + * looping list of items to be rendered on the page. + */ +function infinite({ active, lastActive, total, pageSize, pointer, }) { + if (total <= pageSize) + return active; + // Move the position only when the user moves down, and when the + // navigation fits within a single page + if (lastActive < active && active - lastActive < pageSize) { + // Limit it to the middle of the list + return Math.min(Math.floor(pageSize / 2), pointer + active - lastActive); + } + return pointer; +} +exports.infinite = infinite; diff --git a/node_modules/@inquirer/core/dist/cjs/lib/pagination/use-pagination.js b/node_modules/@inquirer/core/dist/cjs/lib/pagination/use-pagination.js new file mode 100644 index 0000000000000000000000000000000000000000..b1bb8d957d98b2d3ad9872d7211152ef215cdc8a --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/lib/pagination/use-pagination.js @@ -0,0 +1,34 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.usePagination = void 0; +const use_ref_mjs_1 = require('../use-ref.js'); +const utils_mjs_1 = require('../utils.js'); +const lines_mjs_1 = require('./lines.js'); +const position_mjs_1 = require('./position.js'); +function usePagination({ items, active, renderItem, pageSize, loop = true, }) { + const state = (0, use_ref_mjs_1.useRef)({ position: 0, lastActive: 0 }); + const position = loop + ? (0, position_mjs_1.infinite)({ + active, + lastActive: state.current.lastActive, + total: items.length, + pageSize, + pointer: state.current.position, + }) + : (0, position_mjs_1.finite)({ + active, + total: items.length, + pageSize, + }); + state.current.position = position; + state.current.lastActive = active; + return (0, lines_mjs_1.lines)({ + items, + width: (0, utils_mjs_1.readlineWidth)(), + renderItem, + active, + position, + pageSize, + }).join('\n'); +} +exports.usePagination = usePagination; diff --git a/node_modules/@inquirer/core/dist/cjs/lib/read-line.type.js b/node_modules/@inquirer/core/dist/cjs/lib/read-line.type.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/lib/read-line.type.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@inquirer/core/dist/cjs/lib/screen-manager.js b/node_modules/@inquirer/core/dist/cjs/lib/screen-manager.js new file mode 100644 index 0000000000000000000000000000000000000000..1e1534d3f31ee87555f6b27845ef6e18e3e6e3aa --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/lib/screen-manager.js @@ -0,0 +1,128 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const strip_ansi_1 = __importDefault(require("strip-ansi")); +const ansi_escapes_1 = __importDefault(require("ansi-escapes")); +const utils_mjs_1 = require('./utils.js'); +const height = (content) => content.split('\n').length; +const lastLine = (content) => { var _a; return (_a = content.split('\n').pop()) !== null && _a !== void 0 ? _a : ''; }; +class ScreenManager { + constructor(rl) { + Object.defineProperty(this, "rl", { + enumerable: true, + configurable: true, + writable: true, + value: rl + }); + // These variables are keeping information to allow correct prompt re-rendering + Object.defineProperty(this, "height", { + enumerable: true, + configurable: true, + writable: true, + value: 0 + }); + Object.defineProperty(this, "extraLinesUnderPrompt", { + enumerable: true, + configurable: true, + writable: true, + value: 0 + }); + Object.defineProperty(this, "cursorPos", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.rl = rl; + this.cursorPos = rl.getCursorPos(); + } + render(content, bottomContent = '') { + /** + * Write message to screen and setPrompt to control backspace + */ + const promptLine = lastLine(content); + const rawPromptLine = (0, strip_ansi_1.default)(promptLine); + // Remove the rl.line from our prompt. We can't rely on the content of + // rl.line (mainly because of the password prompt), so just rely on it's + // length. + let prompt = rawPromptLine; + if (this.rl.line.length > 0) { + prompt = prompt.slice(0, -this.rl.line.length); + } + this.rl.setPrompt(prompt); + // SetPrompt will change cursor position, now we can get correct value + this.cursorPos = this.rl.getCursorPos(); + const width = (0, utils_mjs_1.readlineWidth)(); + content = (0, utils_mjs_1.breakLines)(content, width); + bottomContent = (0, utils_mjs_1.breakLines)(bottomContent, width); + // Manually insert an extra line if we're at the end of the line. + // This prevent the cursor from appearing at the beginning of the + // current line. + if (rawPromptLine.length % width === 0) { + content += '\n'; + } + let output = content + (bottomContent ? '\n' + bottomContent : ''); + /** + * Re-adjust the cursor at the correct position. + */ + // We need to consider parts of the prompt under the cursor as part of the bottom + // content in order to correctly cleanup and re-render. + const promptLineUpDiff = Math.floor(rawPromptLine.length / width) - this.cursorPos.rows; + const bottomContentHeight = promptLineUpDiff + (bottomContent ? height(bottomContent) : 0); + // Return cursor to the input position (on top of the bottomContent) + if (bottomContentHeight > 0) + output += ansi_escapes_1.default.cursorUp(bottomContentHeight); + // Return cursor to the initial left offset. + output += ansi_escapes_1.default.cursorTo(this.cursorPos.cols); + this.clean(); + this.rl.output.unmute(); + /** + * Set up state for next re-rendering + */ + this.extraLinesUnderPrompt = bottomContentHeight; + this.height = height(output); + this.rl.output.write(output); + this.rl.output.mute(); + } + checkCursorPos() { + const cursorPos = this.rl.getCursorPos(); + if (cursorPos.cols !== this.cursorPos.cols) { + this.rl.output.unmute(); + this.rl.output.write(ansi_escapes_1.default.cursorTo(cursorPos.cols)); + this.rl.output.mute(); + this.cursorPos = cursorPos; + } + } + clean() { + this.rl.output.unmute(); + this.rl.output.write([ + this.extraLinesUnderPrompt > 0 + ? ansi_escapes_1.default.cursorDown(this.extraLinesUnderPrompt) + : '', + ansi_escapes_1.default.eraseLines(this.height), + ].join('')); + this.extraLinesUnderPrompt = 0; + this.rl.output.mute(); + } + clearContent() { + this.rl.output.unmute(); + // Reset the cursor at the end of the previously displayed content + this.rl.output.write([ + this.extraLinesUnderPrompt > 0 + ? ansi_escapes_1.default.cursorDown(this.extraLinesUnderPrompt) + : '', + '\n', + ].join('')); + this.rl.output.mute(); + } + done() { + this.rl.setPrompt(''); + this.rl.output.unmute(); + this.rl.output.write(ansi_escapes_1.default.cursorShow); + this.rl.output.end(); + this.rl.close(); + } +} +exports.default = ScreenManager; diff --git a/node_modules/@inquirer/core/dist/cjs/lib/theme.js b/node_modules/@inquirer/core/dist/cjs/lib/theme.js new file mode 100644 index 0000000000000000000000000000000000000000..3588e980b45515061503c9e0ba5df7c6d39bc0d6 --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/lib/theme.js @@ -0,0 +1,24 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defaultTheme = void 0; +const chalk_1 = __importDefault(require("chalk")); +const cli_spinners_1 = __importDefault(require("cli-spinners")); +exports.defaultTheme = { + prefix: chalk_1.default.green('?'), + spinner: { + interval: cli_spinners_1.default.dots.interval, + frames: cli_spinners_1.default.dots.frames.map((frame) => chalk_1.default.yellow(frame)), + }, + style: { + answer: chalk_1.default.cyan, + message: chalk_1.default.bold, + error: (text) => chalk_1.default.red(`> ${text}`), + defaultAnswer: (text) => chalk_1.default.dim(`(${text})`), + help: chalk_1.default.dim, + highlight: chalk_1.default.cyan, + key: (text) => chalk_1.default.cyan.bold(`<${text}>`), + }, +}; diff --git a/node_modules/@inquirer/core/dist/cjs/lib/use-effect.js b/node_modules/@inquirer/core/dist/cjs/lib/use-effect.js new file mode 100644 index 0000000000000000000000000000000000000000..cfbf8aaeff357ee114f4cc63d7e3a0b0ce1a0048 --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/lib/use-effect.js @@ -0,0 +1,15 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.useEffect = void 0; +const hook_engine_mjs_1 = require('./hook-engine.js'); +function useEffect(cb, depArray) { + (0, hook_engine_mjs_1.withPointer)((pointer) => { + const oldDeps = pointer.get(); + const hasChanged = !Array.isArray(oldDeps) || depArray.some((dep, i) => !Object.is(dep, oldDeps[i])); + if (hasChanged) { + hook_engine_mjs_1.effectScheduler.queue(cb); + } + pointer.set(depArray); + }); +} +exports.useEffect = useEffect; diff --git a/node_modules/@inquirer/core/dist/cjs/lib/use-keypress.js b/node_modules/@inquirer/core/dist/cjs/lib/use-keypress.js new file mode 100644 index 0000000000000000000000000000000000000000..3fa48c30a1cac1e659cd2b2dcfc80afec1bc25f7 --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/lib/use-keypress.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.useKeypress = void 0; +const use_ref_mjs_1 = require('./use-ref.js'); +const use_effect_mjs_1 = require('./use-effect.js'); +const hook_engine_mjs_1 = require('./hook-engine.js'); +function useKeypress(userHandler) { + const signal = (0, use_ref_mjs_1.useRef)(userHandler); + signal.current = userHandler; + (0, use_effect_mjs_1.useEffect)((rl) => { + const handler = (0, hook_engine_mjs_1.withUpdates)((_input, event) => { + signal.current(event, rl); + }); + rl.input.on('keypress', handler); + return () => { + rl.input.removeListener('keypress', handler); + }; + }, []); +} +exports.useKeypress = useKeypress; diff --git a/node_modules/@inquirer/core/dist/cjs/lib/use-memo.js b/node_modules/@inquirer/core/dist/cjs/lib/use-memo.js new file mode 100644 index 0000000000000000000000000000000000000000..2c9e4ac9c8245262a865d861441e79720d893c56 --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/lib/use-memo.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.useMemo = void 0; +const hook_engine_mjs_1 = require('./hook-engine.js'); +function useMemo(fn, dependencies) { + return (0, hook_engine_mjs_1.withPointer)((pointer) => { + const prev = pointer.get(); + if (!prev || + prev.dependencies.length !== dependencies.length || + prev.dependencies.some((dep, i) => dep !== dependencies[i])) { + const value = fn(); + pointer.set({ value, dependencies }); + return value; + } + return prev.value; + }); +} +exports.useMemo = useMemo; diff --git a/node_modules/@inquirer/core/dist/cjs/lib/use-prefix.js b/node_modules/@inquirer/core/dist/cjs/lib/use-prefix.js new file mode 100644 index 0000000000000000000000000000000000000000..31647f8b30caf4982a00c0fe5f2d683834f48e0f --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/lib/use-prefix.js @@ -0,0 +1,38 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.usePrefix = void 0; +const node_async_hooks_1 = require("node:async_hooks"); +const use_state_mjs_1 = require('./use-state.js'); +const use_effect_mjs_1 = require('./use-effect.js'); +const make_theme_mjs_1 = require('./make-theme.js'); +function usePrefix({ isLoading = false, theme, }) { + const [showLoader, setShowLoader] = (0, use_state_mjs_1.useState)(false); + const [tick, setTick] = (0, use_state_mjs_1.useState)(0); + const { prefix, spinner } = (0, make_theme_mjs_1.makeTheme)(theme); + (0, use_effect_mjs_1.useEffect)(() => { + if (isLoading) { + let tickInterval; + let inc = -1; + // Delay displaying spinner by 300ms, to avoid flickering + const delayTimeout = setTimeout(node_async_hooks_1.AsyncResource.bind(() => { + setShowLoader(true); + tickInterval = setInterval(node_async_hooks_1.AsyncResource.bind(() => { + inc = inc + 1; + setTick(inc % spinner.frames.length); + }), spinner.interval); + }), 300); + return () => { + clearTimeout(delayTimeout); + clearInterval(tickInterval); + }; + } + else { + setShowLoader(false); + } + }, [isLoading]); + if (showLoader) { + return spinner.frames[tick]; + } + return prefix; +} +exports.usePrefix = usePrefix; diff --git a/node_modules/@inquirer/core/dist/cjs/lib/use-ref.js b/node_modules/@inquirer/core/dist/cjs/lib/use-ref.js new file mode 100644 index 0000000000000000000000000000000000000000..6db596360fbaa2ce6fdb669222d0f1d0dfe5455d --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/lib/use-ref.js @@ -0,0 +1,8 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.useRef = void 0; +const use_state_mjs_1 = require('./use-state.js'); +function useRef(val) { + return (0, use_state_mjs_1.useState)({ current: val })[0]; +} +exports.useRef = useRef; diff --git a/node_modules/@inquirer/core/dist/cjs/lib/use-state.js b/node_modules/@inquirer/core/dist/cjs/lib/use-state.js new file mode 100644 index 0000000000000000000000000000000000000000..ff6804f3d6d9500cbec053b130a50077a47ccb73 --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/lib/use-state.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.useState = void 0; +const hook_engine_mjs_1 = require('./hook-engine.js'); +function useState(defaultValue) { + return (0, hook_engine_mjs_1.withPointer)((pointer) => { + const setFn = (newValue) => { + // Noop if the value is still the same. + if (pointer.get() !== newValue) { + pointer.set(newValue); + // Trigger re-render + (0, hook_engine_mjs_1.handleChange)(); + } + }; + if (pointer.initialized) { + return [pointer.get(), setFn]; + } + const value = typeof defaultValue === 'function' ? defaultValue() : defaultValue; + pointer.set(value); + return [value, setFn]; + }); +} +exports.useState = useState; diff --git a/node_modules/@inquirer/core/dist/cjs/lib/utils.js b/node_modules/@inquirer/core/dist/cjs/lib/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..11da23e1693e97481e7261d063d17463a0a73b66 --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/lib/utils.js @@ -0,0 +1,33 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.readlineWidth = exports.breakLines = void 0; +const cli_width_1 = __importDefault(require("cli-width")); +const wrap_ansi_1 = __importDefault(require("wrap-ansi")); +const hook_engine_mjs_1 = require('./hook-engine.js'); +/** + * Force line returns at specific width. This function is ANSI code friendly and it'll + * ignore invisible codes during width calculation. + * @param {string} content + * @param {number} width + * @return {string} + */ +function breakLines(content, width) { + return content + .split('\n') + .flatMap((line) => (0, wrap_ansi_1.default)(line, width, { trim: false, hard: true }) + .split('\n') + .map((str) => str.trimEnd())) + .join('\n'); +} +exports.breakLines = breakLines; +/** + * Returns the width of the active readline, or 80 as default value. + * @returns {number} + */ +function readlineWidth() { + return (0, cli_width_1.default)({ defaultWidth: 80, output: (0, hook_engine_mjs_1.readline)().output }); +} +exports.readlineWidth = readlineWidth; diff --git a/node_modules/@inquirer/core/dist/cjs/types/index.d.ts b/node_modules/@inquirer/core/dist/cjs/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2346b0e38fd9506ed60686537059c262dd97d239 --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/types/index.d.ts @@ -0,0 +1,14 @@ +export * from './lib/key.js'; +export * from './lib/errors.js'; +export { usePrefix } from './lib/use-prefix.js'; +export { useState } from './lib/use-state.js'; +export { useEffect } from './lib/use-effect.js'; +export { useMemo } from './lib/use-memo.js'; +export { useRef } from './lib/use-ref.js'; +export { useKeypress } from './lib/use-keypress.js'; +export { makeTheme } from './lib/make-theme.js'; +export type { Theme } from './lib/theme.js'; +export { usePagination } from './lib/pagination/use-pagination.js'; +export { createPrompt } from './lib/create-prompt.js'; +export { Separator } from './lib/Separator.js'; +export { type InquirerReadline } from './lib/read-line.type.js'; diff --git a/node_modules/@inquirer/core/dist/cjs/types/lib/Separator.d.ts b/node_modules/@inquirer/core/dist/cjs/types/lib/Separator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..59330d5cf8a2d8d6601a1d2c0294ff1a6499fd7f --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/types/lib/Separator.d.ts @@ -0,0 +1,10 @@ +/** + * Separator object + * Used to space/separate choices group + */ +export declare class Separator { + readonly separator: string; + readonly type = "separator"; + constructor(separator?: string); + static isSeparator(choice: undefined | Separator | Record): choice is Separator; +} diff --git a/node_modules/@inquirer/core/dist/cjs/types/lib/create-prompt.d.ts b/node_modules/@inquirer/core/dist/cjs/types/lib/create-prompt.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4414db45697e4e2d9dc2f0d3894b4891746cb4b3 --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/types/lib/create-prompt.d.ts @@ -0,0 +1,4 @@ +import { type Prompt, type Prettify } from '@inquirer/type'; +type ViewFunction = (config: Prettify, done: (value: Value) => void) => string | [string, string | undefined]; +export declare function createPrompt(view: ViewFunction): Prompt; +export {}; diff --git a/node_modules/@inquirer/core/dist/cjs/types/lib/errors.d.ts b/node_modules/@inquirer/core/dist/cjs/types/lib/errors.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dd4cebe31d86aa9c3ce9a5fcc74c6fc96a48d010 --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/types/lib/errors.d.ts @@ -0,0 +1,9 @@ +export declare class CancelPromptError extends Error { + message: string; +} +export declare class ExitPromptError extends Error { +} +export declare class HookError extends Error { +} +export declare class ValidationError extends Error { +} diff --git a/node_modules/@inquirer/core/dist/cjs/types/lib/hook-engine.d.ts b/node_modules/@inquirer/core/dist/cjs/types/lib/hook-engine.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fb5f968c7cdaeffecc49c7fff7e7d2870597552b --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/types/lib/hook-engine.d.ts @@ -0,0 +1,30 @@ +import type { InquirerReadline } from './read-line.type.js'; +type HookStore = { + rl: InquirerReadline; + hooks: any[]; + hooksCleanup: Array void)>; + hooksEffect: Array<() => void>; + index: number; + handleChange: () => void; +}; +export declare function withHooks(rl: InquirerReadline, cb: (store: HookStore) => void): void; +export declare function readline(): InquirerReadline; +export declare function withUpdates any>(fn: T): (...args: Parameters) => ReturnType; +type SetPointer = { + get(): Value; + set(value: Value): void; + initialized: true; +}; +type UnsetPointer = { + get(): void; + set(value: Value): void; + initialized: false; +}; +type Pointer = SetPointer | UnsetPointer; +export declare function withPointer(cb: (pointer: Pointer) => ReturnValue): ReturnValue; +export declare function handleChange(): void; +export declare const effectScheduler: { + queue(cb: (readline: InquirerReadline) => void): void; + run(): void; +}; +export {}; diff --git a/node_modules/@inquirer/core/dist/cjs/types/lib/key.d.ts b/node_modules/@inquirer/core/dist/cjs/types/lib/key.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e2ad3dc2aeb8372dd0c900c3408326339ae46045 --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/types/lib/key.d.ts @@ -0,0 +1,10 @@ +export type KeypressEvent = { + name: string; + ctrl: boolean; +}; +export declare const isUpKey: (key: KeypressEvent) => boolean; +export declare const isDownKey: (key: KeypressEvent) => boolean; +export declare const isSpaceKey: (key: KeypressEvent) => boolean; +export declare const isBackspaceKey: (key: KeypressEvent) => boolean; +export declare const isNumberKey: (key: KeypressEvent) => boolean; +export declare const isEnterKey: (key: KeypressEvent) => boolean; diff --git a/node_modules/@inquirer/core/dist/cjs/types/lib/make-theme.d.ts b/node_modules/@inquirer/core/dist/cjs/types/lib/make-theme.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..af6f3d643bce5219362b201bf43f2fc17dfc292f --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/types/lib/make-theme.d.ts @@ -0,0 +1,3 @@ +import type { Prettify, PartialDeep } from '@inquirer/type'; +import { type Theme } from './theme.js'; +export declare function makeTheme(...themes: ReadonlyArray>>): Prettify>; diff --git a/node_modules/@inquirer/core/dist/cjs/types/lib/pagination/lines.d.ts b/node_modules/@inquirer/core/dist/cjs/types/lib/pagination/lines.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8e2270ac865d94856c882c4a062811e136d92422 --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/types/lib/pagination/lines.d.ts @@ -0,0 +1,26 @@ +import { type Prettify } from '@inquirer/type'; +/** Represents an item that's part of a layout, about to be rendered */ +export type Layout = { + item: T; + index: number; + isActive: boolean; +}; +/** + * Renders a page of items as lines that fit within the given width ensuring + * that the number of lines is not greater than the page size, and the active + * item renders at the provided position, while prioritizing that as many lines + * of the active item get rendered as possible. + */ +export declare function lines({ items, width, renderItem, active, position: requested, pageSize, }: { + items: readonly T[]; + /** The width of a rendered line in characters. */ + width: number; + /** Renders an item as part of a page. */ + renderItem: (layout: Prettify>) => string; + /** The index of the active item in the list of items. */ + active: number; + /** The position on the page at which to render the active item. */ + position: number; + /** The number of lines to render per page. */ + pageSize: number; +}): string[]; diff --git a/node_modules/@inquirer/core/dist/cjs/types/lib/pagination/position.d.ts b/node_modules/@inquirer/core/dist/cjs/types/lib/pagination/position.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d74870e6c816b2a2b04d02ffa3b359f4d103ec8d --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/types/lib/pagination/position.d.ts @@ -0,0 +1,20 @@ +/** + * Creates the next position for the active item considering a finite list of + * items to be rendered on a page. + */ +export declare function finite({ active, pageSize, total, }: { + active: number; + pageSize: number; + total: number; +}): number; +/** + * Creates the next position for the active item considering an infinitely + * looping list of items to be rendered on the page. + */ +export declare function infinite({ active, lastActive, total, pageSize, pointer, }: { + active: number; + lastActive: number; + total: number; + pageSize: number; + pointer: number; +}): number; diff --git a/node_modules/@inquirer/core/dist/cjs/types/lib/pagination/use-pagination.d.ts b/node_modules/@inquirer/core/dist/cjs/types/lib/pagination/use-pagination.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..efa966592a3f00fabbb3671e280cedbbe3d05a9d --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/types/lib/pagination/use-pagination.d.ts @@ -0,0 +1,15 @@ +import type { Prettify } from '@inquirer/type'; +import { type Theme } from '../theme.js'; +import { type Layout } from './lines.js'; +export declare function usePagination({ items, active, renderItem, pageSize, loop, }: { + items: readonly T[]; + /** The index of the active item. */ + active: number; + /** Renders an item as part of a page. */ + renderItem: (layout: Prettify>) => string; + /** The size of the page. */ + pageSize: number; + /** Allows creating an infinitely looping list. `true` if unspecified. */ + loop?: boolean; + theme?: Theme; +}): string; diff --git a/node_modules/@inquirer/core/dist/cjs/types/lib/read-line.type.d.ts b/node_modules/@inquirer/core/dist/cjs/types/lib/read-line.type.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ecc8a206e500f5f8659c79732402f4ef6a0b81b1 --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/types/lib/read-line.type.d.ts @@ -0,0 +1,9 @@ +/// +/// +import * as readline from 'node:readline'; +import MuteStream from 'mute-stream'; +export type InquirerReadline = readline.ReadLine & { + output: MuteStream; + input: NodeJS.ReadableStream; + clearLine: (dir: 0 | 1 | -1) => void; +}; diff --git a/node_modules/@inquirer/core/dist/cjs/types/lib/screen-manager.d.ts b/node_modules/@inquirer/core/dist/cjs/types/lib/screen-manager.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fa0a765f0652aeb20cc865ff35b88454d8a73bb7 --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/types/lib/screen-manager.d.ts @@ -0,0 +1,13 @@ +import type { InquirerReadline } from './read-line.type.js'; +export default class ScreenManager { + private readonly rl; + private height; + private extraLinesUnderPrompt; + private cursorPos; + constructor(rl: InquirerReadline); + render(content: string, bottomContent?: string): void; + checkCursorPos(): void; + clean(): void; + clearContent(): void; + done(): void; +} diff --git a/node_modules/@inquirer/core/dist/cjs/types/lib/theme.d.ts b/node_modules/@inquirer/core/dist/cjs/types/lib/theme.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c319617267afc003b22dabe658d94315cbdb53c6 --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/types/lib/theme.d.ts @@ -0,0 +1,20 @@ +import type { Prettify } from '@inquirer/type'; +type DefaultTheme = { + prefix: string; + spinner: { + interval: number; + frames: string[]; + }; + style: { + answer: (text: string) => string; + message: (text: string) => string; + error: (text: string) => string; + defaultAnswer: (text: string) => string; + help: (text: string) => string; + highlight: (text: string) => string; + key: (text: string) => string; + }; +}; +export type Theme = Prettify; +export declare const defaultTheme: DefaultTheme; +export {}; diff --git a/node_modules/@inquirer/core/dist/cjs/types/lib/use-effect.d.ts b/node_modules/@inquirer/core/dist/cjs/types/lib/use-effect.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3ae19609bbdd0c1f9d10e12fa41f9993a3d3dce8 --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/types/lib/use-effect.d.ts @@ -0,0 +1,2 @@ +import type { InquirerReadline } from './read-line.type.js'; +export declare function useEffect(cb: (rl: InquirerReadline) => void | (() => void), depArray: unknown[]): void; diff --git a/node_modules/@inquirer/core/dist/cjs/types/lib/use-keypress.d.ts b/node_modules/@inquirer/core/dist/cjs/types/lib/use-keypress.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..daa4d09d3c0fccdba922a7c9f5c6abb73c2fb68c --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/types/lib/use-keypress.d.ts @@ -0,0 +1,3 @@ +import { type InquirerReadline } from './read-line.type.js'; +import { type KeypressEvent } from './key.js'; +export declare function useKeypress(userHandler: (event: KeypressEvent, rl: InquirerReadline) => void): void; diff --git a/node_modules/@inquirer/core/dist/cjs/types/lib/use-memo.d.ts b/node_modules/@inquirer/core/dist/cjs/types/lib/use-memo.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..989092c16a73868f09b467e1c9f0141e8330b825 --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/types/lib/use-memo.d.ts @@ -0,0 +1 @@ +export declare function useMemo(fn: () => Value, dependencies: unknown[]): Value; diff --git a/node_modules/@inquirer/core/dist/cjs/types/lib/use-prefix.d.ts b/node_modules/@inquirer/core/dist/cjs/types/lib/use-prefix.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0a1c41f041d4b46de11c32e0da69f9e658c4204c --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/types/lib/use-prefix.d.ts @@ -0,0 +1,5 @@ +import { type Theme } from './theme.js'; +export declare function usePrefix({ isLoading, theme, }: { + isLoading?: boolean; + theme?: Theme; +}): string; diff --git a/node_modules/@inquirer/core/dist/cjs/types/lib/use-ref.d.ts b/node_modules/@inquirer/core/dist/cjs/types/lib/use-ref.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..be7126b9e8784bebfe6526bdca70895a388a0c16 --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/types/lib/use-ref.d.ts @@ -0,0 +1,6 @@ +export declare function useRef(val: Value): { + current: Value; +}; +export declare function useRef(val?: Value): { + current: Value | undefined; +}; diff --git a/node_modules/@inquirer/core/dist/cjs/types/lib/use-state.d.ts b/node_modules/@inquirer/core/dist/cjs/types/lib/use-state.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7730aede4edb9504d4f00d6afad47cfa4c898d20 --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/types/lib/use-state.d.ts @@ -0,0 +1,4 @@ +type NotFunction = T extends Function ? never : T; +export declare function useState(defaultValue: NotFunction | (() => Value)): [Value, (newValue: Value) => void]; +export declare function useState(defaultValue?: NotFunction | (() => Value)): [Value | undefined, (newValue?: Value | undefined) => void]; +export {}; diff --git a/node_modules/@inquirer/core/dist/cjs/types/lib/utils.d.ts b/node_modules/@inquirer/core/dist/cjs/types/lib/utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..14f8fc438e8a481cf90a4c071b18751e26f9f4d0 --- /dev/null +++ b/node_modules/@inquirer/core/dist/cjs/types/lib/utils.d.ts @@ -0,0 +1,13 @@ +/** + * Force line returns at specific width. This function is ANSI code friendly and it'll + * ignore invisible codes during width calculation. + * @param {string} content + * @param {number} width + * @return {string} + */ +export declare function breakLines(content: string, width: number): string; +/** + * Returns the width of the active readline, or 80 as default value. + * @returns {number} + */ +export declare function readlineWidth(): number; diff --git a/node_modules/@inquirer/core/dist/esm/index.mjs b/node_modules/@inquirer/core/dist/esm/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..772ef6c09c94cc56a17087815049c7b1e912b9d3 --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/index.mjs @@ -0,0 +1,12 @@ +export * from './lib/key.mjs'; +export * from './lib/errors.mjs'; +export { usePrefix } from './lib/use-prefix.mjs'; +export { useState } from './lib/use-state.mjs'; +export { useEffect } from './lib/use-effect.mjs'; +export { useMemo } from './lib/use-memo.mjs'; +export { useRef } from './lib/use-ref.mjs'; +export { useKeypress } from './lib/use-keypress.mjs'; +export { makeTheme } from './lib/make-theme.mjs'; +export { usePagination } from './lib/pagination/use-pagination.mjs'; +export { createPrompt } from './lib/create-prompt.mjs'; +export { Separator } from './lib/Separator.mjs'; diff --git a/node_modules/@inquirer/core/dist/esm/lib/Separator.mjs b/node_modules/@inquirer/core/dist/esm/lib/Separator.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6df6a6dc0e96474917941fa191406a8e914fb468 --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/lib/Separator.mjs @@ -0,0 +1,18 @@ +import chalk from 'chalk'; +import figures from '@inquirer/figures'; +/** + * Separator object + * Used to space/separate choices group + */ +export class Separator { + separator = chalk.dim(Array.from({ length: 15 }).join(figures.line)); + type = 'separator'; + constructor(separator) { + if (separator) { + this.separator = separator; + } + } + static isSeparator(choice) { + return Boolean(choice && choice.type === 'separator'); + } +} diff --git a/node_modules/@inquirer/core/dist/esm/lib/create-prompt.mjs b/node_modules/@inquirer/core/dist/esm/lib/create-prompt.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d3a9c22ee6a725319d2121e44c18acacff18fd1f --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/lib/create-prompt.mjs @@ -0,0 +1,88 @@ +import * as readline from 'node:readline'; +import { CancelablePromise } from '@inquirer/type'; +import MuteStream from 'mute-stream'; +import { onExit as onSignalExit } from 'signal-exit'; +import ScreenManager from './screen-manager.mjs'; +import { withHooks, effectScheduler } from './hook-engine.mjs'; +import { CancelPromptError, ExitPromptError } from './errors.mjs'; +export function createPrompt(view) { + const prompt = (config, context) => { + // Default `input` to stdin + const input = context?.input ?? process.stdin; + // Add mute capabilities to the output + const output = new MuteStream(); + output.pipe(context?.output ?? process.stdout); + const rl = readline.createInterface({ + terminal: true, + input, + output, + }); + const screen = new ScreenManager(rl); + let cancel = () => { }; + const answer = new CancelablePromise((resolve, reject) => { + withHooks(rl, (store) => { + function checkCursorPos() { + screen.checkCursorPos(); + } + const removeExitListener = onSignalExit((code, signal) => { + onExit(); + reject(new ExitPromptError(`User force closed the prompt with ${code} ${signal}`)); + }); + function onExit() { + try { + store.hooksCleanup.forEach((cleanFn) => { + cleanFn?.(); + }); + } + catch (error) { + reject(error); + } + if (context?.clearPromptOnDone) { + screen.clean(); + } + else { + screen.clearContent(); + } + screen.done(); + removeExitListener(); + store.rl.input.removeListener('keypress', checkCursorPos); + } + cancel = () => { + onExit(); + reject(new CancelPromptError()); + }; + function done(value) { + // Delay execution to let time to the hookCleanup functions to registers. + setImmediate(() => { + onExit(); + // Finally we resolve our promise + resolve(value); + }); + } + function workLoop() { + store.index = 0; + try { + const nextView = view(config, done); + const [content, bottomContent] = typeof nextView === 'string' ? [nextView] : nextView; + screen.render(content, bottomContent); + effectScheduler.run(); + } + catch (error) { + onExit(); + reject(error); + } + } + store.handleChange = () => workLoop(); + workLoop(); + // Re-renders only happen when the state change; but the readline cursor could change position + // and that also requires a re-render (and a manual one because we mute the streams). + // We set the listener after the initial workLoop to avoid a double render if render triggered + // by a state change sets the cursor to the right position. + store.rl.input.on('keypress', checkCursorPos); + }); + }); + answer.cancel = cancel; + return answer; + }; + return prompt; +} diff --git a/node_modules/@inquirer/core/dist/esm/lib/errors.mjs b/node_modules/@inquirer/core/dist/esm/lib/errors.mjs new file mode 100644 index 0000000000000000000000000000000000000000..9d6532ac495187ea93519c7fb7a6e4a4a7ae4831 --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/lib/errors.mjs @@ -0,0 +1,9 @@ +export class CancelPromptError extends Error { + message = 'Prompt was canceled'; +} +export class ExitPromptError extends Error { +} +export class HookError extends Error { +} +export class ValidationError extends Error { +} diff --git a/node_modules/@inquirer/core/dist/esm/lib/hook-engine.mjs b/node_modules/@inquirer/core/dist/esm/lib/hook-engine.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3460402503f3fc322076fe88e496660d2be01c34 --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/lib/hook-engine.mjs @@ -0,0 +1,95 @@ +/* eslint @typescript-eslint/no-explicit-any: ["off"] */ +import { AsyncLocalStorage, AsyncResource } from 'node:async_hooks'; +import { HookError, ValidationError } from './errors.mjs'; +const hookStorage = new AsyncLocalStorage(); +function createStore(rl) { + const store = { + rl, + hooks: [], + hooksCleanup: [], + hooksEffect: [], + index: 0, + handleChange() { }, + }; + return store; +} +// Run callback in with the hook engine setup. +export function withHooks(rl, cb) { + const store = createStore(rl); + return hookStorage.run(store, () => { + cb(store); + }); +} +// Safe getStore utility that'll return the store or throw if undefined. +function getStore() { + const store = hookStorage.getStore(); + if (!store) { + throw new HookError('[Inquirer] Hook functions can only be called from within a prompt'); + } + return store; +} +export function readline() { + return getStore().rl; +} +// Merge state updates happening within the callback function to avoid multiple renders. +export function withUpdates(fn) { + const wrapped = (...args) => { + const store = getStore(); + let shouldUpdate = false; + const oldHandleChange = store.handleChange; + store.handleChange = () => { + shouldUpdate = true; + }; + const returnValue = fn(...args); + if (shouldUpdate) { + oldHandleChange(); + } + store.handleChange = oldHandleChange; + return returnValue; + }; + return AsyncResource.bind(wrapped); +} +export function withPointer(cb) { + const store = getStore(); + const { index } = store; + const pointer = { + get() { + return store.hooks[index]; + }, + set(value) { + store.hooks[index] = value; + }, + initialized: index in store.hooks, + }; + const returnValue = cb(pointer); + store.index++; + return returnValue; +} +export function handleChange() { + getStore().handleChange(); +} +export const effectScheduler = { + queue(cb) { + const store = getStore(); + const { index } = store; + store.hooksEffect.push(() => { + store.hooksCleanup[index]?.(); + const cleanFn = cb(readline()); + if (cleanFn != null && typeof cleanFn !== 'function') { + throw new ValidationError('useEffect return value must be a cleanup function or nothing.'); + } + store.hooksCleanup[index] = cleanFn; + }); + }, + run() { + const store = getStore(); + withUpdates(() => { + store.hooksEffect.forEach((effect) => { + effect(); + }); + // Warning: Clean the hooks before exiting the `withUpdates` block. + // Failure to do so means an updates would hit the same effects again. + store.hooksEffect.length = 0; + })(); + }, +}; diff --git a/node_modules/@inquirer/core/dist/esm/lib/key.mjs b/node_modules/@inquirer/core/dist/esm/lib/key.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a6f2512549ce5a979e6fdd234f2054dce888a407 --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/lib/key.mjs @@ -0,0 +1,18 @@ +export const isUpKey = (key) => +// The up key +key.name === 'up' || + // Vim keybinding + key.name === 'k' || + // Emacs keybinding + (key.ctrl && key.name === 'p'); +export const isDownKey = (key) => +// The down key +key.name === 'down' || + // Vim keybinding + key.name === 'j' || + // Emacs keybinding + (key.ctrl && key.name === 'n'); +export const isSpaceKey = (key) => key.name === 'space'; +export const isBackspaceKey = (key) => key.name === 'backspace'; +export const isNumberKey = (key) => '123456789'.includes(key.name); +export const isEnterKey = (key) => key.name === 'enter' || key.name === 'return'; diff --git a/node_modules/@inquirer/core/dist/esm/lib/make-theme.mjs b/node_modules/@inquirer/core/dist/esm/lib/make-theme.mjs new file mode 100644 index 0000000000000000000000000000000000000000..504da44ebc147f7f4dd35b034415c6357690dc9c --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/lib/make-theme.mjs @@ -0,0 +1,30 @@ +import { defaultTheme } from './theme.mjs'; +function isPlainObject(value) { + if (typeof value !== 'object' || value === null) + return false; + let proto = value; + while (Object.getPrototypeOf(proto) !== null) { + proto = Object.getPrototypeOf(proto); + } + return Object.getPrototypeOf(value) === proto; +} +function deepMerge(...objects) { + const output = {}; + for (const obj of objects) { + for (const [key, value] of Object.entries(obj)) { + const prevValue = output[key]; + output[key] = + isPlainObject(prevValue) && isPlainObject(value) + ? deepMerge(prevValue, value) + : value; + } + } + return output; +} +export function makeTheme(...themes) { + const themesToMerge = [ + defaultTheme, + ...themes.filter((theme) => theme != null), + ]; + return deepMerge(...themesToMerge); +} diff --git a/node_modules/@inquirer/core/dist/esm/lib/pagination/lines.mjs b/node_modules/@inquirer/core/dist/esm/lib/pagination/lines.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6b9a38f9207aa8c8a82522807bf471ccbcd396c4 --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/lib/pagination/lines.mjs @@ -0,0 +1,59 @@ +import { breakLines } from '../utils.mjs'; +function split(content, width) { + return breakLines(content, width).split('\n'); +} +/** + * Rotates an array of items by an integer number of positions. + * @param {number} count The number of positions to rotate by + * @param {T[]} items The items to rotate + */ +function rotate(count, items) { + const max = items.length; + const offset = ((count % max) + max) % max; + return [...items.slice(offset), ...items.slice(0, offset)]; +} +/** + * Renders a page of items as lines that fit within the given width ensuring + * that the number of lines is not greater than the page size, and the active + * item renders at the provided position, while prioritizing that as many lines + * of the active item get rendered as possible. + */ +export function lines({ items, width, renderItem, active, position: requested, pageSize, }) { + const layouts = items.map((item, index) => ({ + item, + index, + isActive: index === active, + })); + const layoutsInPage = rotate(active - requested, layouts).slice(0, pageSize); + const renderItemAt = (index) => split(renderItem(layoutsInPage[index]), width); + // Create a blank array of lines for the page + const pageBuffer = Array.from({ length: pageSize }); + // Render the active item to decide the position + const activeItem = renderItemAt(requested).slice(0, pageSize); + const position = requested + activeItem.length <= pageSize ? requested : pageSize - activeItem.length; + // Add the lines of the active item into the page + pageBuffer.splice(position, activeItem.length, ...activeItem); + // Fill the page under the active item + let bufferPointer = position + activeItem.length; + let layoutPointer = requested + 1; + while (bufferPointer < pageSize && layoutPointer < layoutsInPage.length) { + for (const line of renderItemAt(layoutPointer)) { + pageBuffer[bufferPointer++] = line; + if (bufferPointer >= pageSize) + break; + } + layoutPointer++; + } + // Fill the page over the active item + bufferPointer = position - 1; + layoutPointer = requested - 1; + while (bufferPointer >= 0 && layoutPointer >= 0) { + for (const line of renderItemAt(layoutPointer).reverse()) { + pageBuffer[bufferPointer--] = line; + if (bufferPointer < 0) + break; + } + layoutPointer--; + } + return pageBuffer.filter((line) => typeof line === 'string'); +} diff --git a/node_modules/@inquirer/core/dist/esm/lib/pagination/position.mjs b/node_modules/@inquirer/core/dist/esm/lib/pagination/position.mjs new file mode 100644 index 0000000000000000000000000000000000000000..9e3cc2eb8bacca63c209c17112b913e7ef9c665e --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/lib/pagination/position.mjs @@ -0,0 +1,27 @@ +/** + * Creates the next position for the active item considering a finite list of + * items to be rendered on a page. + */ +export function finite({ active, pageSize, total, }) { + const middle = Math.floor(pageSize / 2); + if (total <= pageSize || active < middle) + return active; + if (active >= total - middle) + return active + pageSize - total; + return middle; +} +/** + * Creates the next position for the active item considering an infinitely + * looping list of items to be rendered on the page. + */ +export function infinite({ active, lastActive, total, pageSize, pointer, }) { + if (total <= pageSize) + return active; + // Move the position only when the user moves down, and when the + // navigation fits within a single page + if (lastActive < active && active - lastActive < pageSize) { + // Limit it to the middle of the list + return Math.min(Math.floor(pageSize / 2), pointer + active - lastActive); + } + return pointer; +} diff --git a/node_modules/@inquirer/core/dist/esm/lib/pagination/use-pagination.mjs b/node_modules/@inquirer/core/dist/esm/lib/pagination/use-pagination.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b8459233d2906ddc51b5ec9383306609fea473b0 --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/lib/pagination/use-pagination.mjs @@ -0,0 +1,30 @@ +import { useRef } from '../use-ref.mjs'; +import { readlineWidth } from '../utils.mjs'; +import { lines } from './lines.mjs'; +import { finite, infinite } from './position.mjs'; +export function usePagination({ items, active, renderItem, pageSize, loop = true, }) { + const state = useRef({ position: 0, lastActive: 0 }); + const position = loop + ? infinite({ + active, + lastActive: state.current.lastActive, + total: items.length, + pageSize, + pointer: state.current.position, + }) + : finite({ + active, + total: items.length, + pageSize, + }); + state.current.position = position; + state.current.lastActive = active; + return lines({ + items, + width: readlineWidth(), + renderItem, + active, + position, + pageSize, + }).join('\n'); +} diff --git a/node_modules/@inquirer/core/dist/esm/lib/read-line.type.mjs b/node_modules/@inquirer/core/dist/esm/lib/read-line.type.mjs new file mode 100644 index 0000000000000000000000000000000000000000..cb0ff5c3b541f646105198ee23ac0fc3d805023e --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/lib/read-line.type.mjs @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/@inquirer/core/dist/esm/lib/screen-manager.mjs b/node_modules/@inquirer/core/dist/esm/lib/screen-manager.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e63db9d15c8b0586303a877ee1a7867ee45a43bf --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/lib/screen-manager.mjs @@ -0,0 +1,103 @@ +import stripAnsi from 'strip-ansi'; +import ansiEscapes from 'ansi-escapes'; +import { breakLines, readlineWidth } from './utils.mjs'; +const height = (content) => content.split('\n').length; +const lastLine = (content) => content.split('\n').pop() ?? ''; +export default class ScreenManager { + rl; + // These variables are keeping information to allow correct prompt re-rendering + height = 0; + extraLinesUnderPrompt = 0; + cursorPos; + constructor(rl) { + this.rl = rl; + this.rl = rl; + this.cursorPos = rl.getCursorPos(); + } + render(content, bottomContent = '') { + /** + * Write message to screen and setPrompt to control backspace + */ + const promptLine = lastLine(content); + const rawPromptLine = stripAnsi(promptLine); + // Remove the rl.line from our prompt. We can't rely on the content of + // rl.line (mainly because of the password prompt), so just rely on it's + // length. + let prompt = rawPromptLine; + if (this.rl.line.length > 0) { + prompt = prompt.slice(0, -this.rl.line.length); + } + this.rl.setPrompt(prompt); + // SetPrompt will change cursor position, now we can get correct value + this.cursorPos = this.rl.getCursorPos(); + const width = readlineWidth(); + content = breakLines(content, width); + bottomContent = breakLines(bottomContent, width); + // Manually insert an extra line if we're at the end of the line. + // This prevent the cursor from appearing at the beginning of the + // current line. + if (rawPromptLine.length % width === 0) { + content += '\n'; + } + let output = content + (bottomContent ? '\n' + bottomContent : ''); + /** + * Re-adjust the cursor at the correct position. + */ + // We need to consider parts of the prompt under the cursor as part of the bottom + // content in order to correctly cleanup and re-render. + const promptLineUpDiff = Math.floor(rawPromptLine.length / width) - this.cursorPos.rows; + const bottomContentHeight = promptLineUpDiff + (bottomContent ? height(bottomContent) : 0); + // Return cursor to the input position (on top of the bottomContent) + if (bottomContentHeight > 0) + output += ansiEscapes.cursorUp(bottomContentHeight); + // Return cursor to the initial left offset. + output += ansiEscapes.cursorTo(this.cursorPos.cols); + this.clean(); + this.rl.output.unmute(); + /** + * Set up state for next re-rendering + */ + this.extraLinesUnderPrompt = bottomContentHeight; + this.height = height(output); + this.rl.output.write(output); + this.rl.output.mute(); + } + checkCursorPos() { + const cursorPos = this.rl.getCursorPos(); + if (cursorPos.cols !== this.cursorPos.cols) { + this.rl.output.unmute(); + this.rl.output.write(ansiEscapes.cursorTo(cursorPos.cols)); + this.rl.output.mute(); + this.cursorPos = cursorPos; + } + } + clean() { + this.rl.output.unmute(); + this.rl.output.write([ + this.extraLinesUnderPrompt > 0 + ? ansiEscapes.cursorDown(this.extraLinesUnderPrompt) + : '', + ansiEscapes.eraseLines(this.height), + ].join('')); + this.extraLinesUnderPrompt = 0; + this.rl.output.mute(); + } + clearContent() { + this.rl.output.unmute(); + // Reset the cursor at the end of the previously displayed content + this.rl.output.write([ + this.extraLinesUnderPrompt > 0 + ? ansiEscapes.cursorDown(this.extraLinesUnderPrompt) + : '', + '\n', + ].join('')); + this.rl.output.mute(); + } + done() { + this.rl.setPrompt(''); + this.rl.output.unmute(); + this.rl.output.write(ansiEscapes.cursorShow); + this.rl.output.end(); + this.rl.close(); + } +} diff --git a/node_modules/@inquirer/core/dist/esm/lib/theme.mjs b/node_modules/@inquirer/core/dist/esm/lib/theme.mjs new file mode 100644 index 0000000000000000000000000000000000000000..66ea4f74afa4a3fd2755abd2f56a0204c859ea21 --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/lib/theme.mjs @@ -0,0 +1,18 @@ +import chalk from 'chalk'; +import spinners from 'cli-spinners'; +export const defaultTheme = { + prefix: chalk.green('?'), + spinner: { + interval: spinners.dots.interval, + frames: spinners.dots.frames.map((frame) => chalk.yellow(frame)), + }, + style: { + answer: chalk.cyan, + message: chalk.bold, + error: (text) => chalk.red(`> ${text}`), + defaultAnswer: (text) => chalk.dim(`(${text})`), + help: chalk.dim, + highlight: chalk.cyan, + key: (text) => chalk.cyan.bold(`<${text}>`), + }, +}; diff --git a/node_modules/@inquirer/core/dist/esm/lib/use-effect.mjs b/node_modules/@inquirer/core/dist/esm/lib/use-effect.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8c30102e81d6e9edca6ea1cbfe156d431b644bc6 --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/lib/use-effect.mjs @@ -0,0 +1,11 @@ +import { withPointer, effectScheduler } from './hook-engine.mjs'; +export function useEffect(cb, depArray) { + withPointer((pointer) => { + const oldDeps = pointer.get(); + const hasChanged = !Array.isArray(oldDeps) || depArray.some((dep, i) => !Object.is(dep, oldDeps[i])); + if (hasChanged) { + effectScheduler.queue(cb); + } + pointer.set(depArray); + }); +} diff --git a/node_modules/@inquirer/core/dist/esm/lib/use-keypress.mjs b/node_modules/@inquirer/core/dist/esm/lib/use-keypress.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8daee8531d5c7b0adf2a58d6d1e2decd9d61c228 --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/lib/use-keypress.mjs @@ -0,0 +1,16 @@ +import { useRef } from './use-ref.mjs'; +import { useEffect } from './use-effect.mjs'; +import { withUpdates } from './hook-engine.mjs'; +export function useKeypress(userHandler) { + const signal = useRef(userHandler); + signal.current = userHandler; + useEffect((rl) => { + const handler = withUpdates((_input, event) => { + signal.current(event, rl); + }); + rl.input.on('keypress', handler); + return () => { + rl.input.removeListener('keypress', handler); + }; + }, []); +} diff --git a/node_modules/@inquirer/core/dist/esm/lib/use-memo.mjs b/node_modules/@inquirer/core/dist/esm/lib/use-memo.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a6558e82415123b9bbd3241b0e35ac9b720099f6 --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/lib/use-memo.mjs @@ -0,0 +1,14 @@ +import { withPointer } from './hook-engine.mjs'; +export function useMemo(fn, dependencies) { + return withPointer((pointer) => { + const prev = pointer.get(); + if (!prev || + prev.dependencies.length !== dependencies.length || + prev.dependencies.some((dep, i) => dep !== dependencies[i])) { + const value = fn(); + pointer.set({ value, dependencies }); + return value; + } + return prev.value; + }); +} diff --git a/node_modules/@inquirer/core/dist/esm/lib/use-prefix.mjs b/node_modules/@inquirer/core/dist/esm/lib/use-prefix.mjs new file mode 100644 index 0000000000000000000000000000000000000000..cae4b6dd839f557ab3afa098fc11ef59cc616c66 --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/lib/use-prefix.mjs @@ -0,0 +1,34 @@ +import { AsyncResource } from 'node:async_hooks'; +import { useState } from './use-state.mjs'; +import { useEffect } from './use-effect.mjs'; +import { makeTheme } from './make-theme.mjs'; +export function usePrefix({ isLoading = false, theme, }) { + const [showLoader, setShowLoader] = useState(false); + const [tick, setTick] = useState(0); + const { prefix, spinner } = makeTheme(theme); + useEffect(() => { + if (isLoading) { + let tickInterval; + let inc = -1; + // Delay displaying spinner by 300ms, to avoid flickering + const delayTimeout = setTimeout(AsyncResource.bind(() => { + setShowLoader(true); + tickInterval = setInterval(AsyncResource.bind(() => { + inc = inc + 1; + setTick(inc % spinner.frames.length); + }), spinner.interval); + }), 300); + return () => { + clearTimeout(delayTimeout); + clearInterval(tickInterval); + }; + } + else { + setShowLoader(false); + } + }, [isLoading]); + if (showLoader) { + return spinner.frames[tick]; + } + return prefix; +} diff --git a/node_modules/@inquirer/core/dist/esm/lib/use-ref.mjs b/node_modules/@inquirer/core/dist/esm/lib/use-ref.mjs new file mode 100644 index 0000000000000000000000000000000000000000..69ecc68c85c810574644dfb29fc42185bdd4c0d1 --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/lib/use-ref.mjs @@ -0,0 +1,4 @@ +import { useState } from './use-state.mjs'; +export function useRef(val) { + return useState({ current: val })[0]; +} diff --git a/node_modules/@inquirer/core/dist/esm/lib/use-state.mjs b/node_modules/@inquirer/core/dist/esm/lib/use-state.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3629bf091fea62ad7af08efa190d167314e4d07c --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/lib/use-state.mjs @@ -0,0 +1,19 @@ +import { withPointer, handleChange } from './hook-engine.mjs'; +export function useState(defaultValue) { + return withPointer((pointer) => { + const setFn = (newValue) => { + // Noop if the value is still the same. + if (pointer.get() !== newValue) { + pointer.set(newValue); + // Trigger re-render + handleChange(); + } + }; + if (pointer.initialized) { + return [pointer.get(), setFn]; + } + const value = typeof defaultValue === 'function' ? defaultValue() : defaultValue; + pointer.set(value); + return [value, setFn]; + }); +} diff --git a/node_modules/@inquirer/core/dist/esm/lib/utils.mjs b/node_modules/@inquirer/core/dist/esm/lib/utils.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1e7ae89d5682e9a47e2ec9da10f0f5601c74b0d1 --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/lib/utils.mjs @@ -0,0 +1,25 @@ +import cliWidth from 'cli-width'; +import wrapAnsi from 'wrap-ansi'; +import { readline } from './hook-engine.mjs'; +/** + * Force line returns at specific width. This function is ANSI code friendly and it'll + * ignore invisible codes during width calculation. + * @param {string} content + * @param {number} width + * @return {string} + */ +export function breakLines(content, width) { + return content + .split('\n') + .flatMap((line) => wrapAnsi(line, width, { trim: false, hard: true }) + .split('\n') + .map((str) => str.trimEnd())) + .join('\n'); +} +/** + * Returns the width of the active readline, or 80 as default value. + * @returns {number} + */ +export function readlineWidth() { + return cliWidth({ defaultWidth: 80, output: readline().output }); +} diff --git a/node_modules/@inquirer/core/dist/esm/types/index.d.mts b/node_modules/@inquirer/core/dist/esm/types/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..c1b08513c0a216a1f62713a75e19ca0a8a882e17 --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/types/index.d.mts @@ -0,0 +1,14 @@ +export * from './lib/key.mjs'; +export * from './lib/errors.mjs'; +export { usePrefix } from './lib/use-prefix.mjs'; +export { useState } from './lib/use-state.mjs'; +export { useEffect } from './lib/use-effect.mjs'; +export { useMemo } from './lib/use-memo.mjs'; +export { useRef } from './lib/use-ref.mjs'; +export { useKeypress } from './lib/use-keypress.mjs'; +export { makeTheme } from './lib/make-theme.mjs'; +export type { Theme } from './lib/theme.mjs'; +export { usePagination } from './lib/pagination/use-pagination.mjs'; +export { createPrompt } from './lib/create-prompt.mjs'; +export { Separator } from './lib/Separator.mjs'; +export { type InquirerReadline } from './lib/read-line.type.mjs'; diff --git a/node_modules/@inquirer/core/dist/esm/types/lib/Separator.d.mts b/node_modules/@inquirer/core/dist/esm/types/lib/Separator.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..59330d5cf8a2d8d6601a1d2c0294ff1a6499fd7f --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/types/lib/Separator.d.mts @@ -0,0 +1,10 @@ +/** + * Separator object + * Used to space/separate choices group + */ +export declare class Separator { + readonly separator: string; + readonly type = "separator"; + constructor(separator?: string); + static isSeparator(choice: undefined | Separator | Record): choice is Separator; +} diff --git a/node_modules/@inquirer/core/dist/esm/types/lib/create-prompt.d.mts b/node_modules/@inquirer/core/dist/esm/types/lib/create-prompt.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..4414db45697e4e2d9dc2f0d3894b4891746cb4b3 --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/types/lib/create-prompt.d.mts @@ -0,0 +1,4 @@ +import { type Prompt, type Prettify } from '@inquirer/type'; +type ViewFunction = (config: Prettify, done: (value: Value) => void) => string | [string, string | undefined]; +export declare function createPrompt(view: ViewFunction): Prompt; +export {}; diff --git a/node_modules/@inquirer/core/dist/esm/types/lib/errors.d.mts b/node_modules/@inquirer/core/dist/esm/types/lib/errors.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..dd4cebe31d86aa9c3ce9a5fcc74c6fc96a48d010 --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/types/lib/errors.d.mts @@ -0,0 +1,9 @@ +export declare class CancelPromptError extends Error { + message: string; +} +export declare class ExitPromptError extends Error { +} +export declare class HookError extends Error { +} +export declare class ValidationError extends Error { +} diff --git a/node_modules/@inquirer/core/dist/esm/types/lib/hook-engine.d.mts b/node_modules/@inquirer/core/dist/esm/types/lib/hook-engine.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..735e33b0a3ec568225bbb5fb71cbef539a7c8ecd --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/types/lib/hook-engine.d.mts @@ -0,0 +1,30 @@ +import type { InquirerReadline } from './read-line.type.mjs'; +type HookStore = { + rl: InquirerReadline; + hooks: any[]; + hooksCleanup: Array void)>; + hooksEffect: Array<() => void>; + index: number; + handleChange: () => void; +}; +export declare function withHooks(rl: InquirerReadline, cb: (store: HookStore) => void): void; +export declare function readline(): InquirerReadline; +export declare function withUpdates any>(fn: T): (...args: Parameters) => ReturnType; +type SetPointer = { + get(): Value; + set(value: Value): void; + initialized: true; +}; +type UnsetPointer = { + get(): void; + set(value: Value): void; + initialized: false; +}; +type Pointer = SetPointer | UnsetPointer; +export declare function withPointer(cb: (pointer: Pointer) => ReturnValue): ReturnValue; +export declare function handleChange(): void; +export declare const effectScheduler: { + queue(cb: (readline: InquirerReadline) => void): void; + run(): void; +}; +export {}; diff --git a/node_modules/@inquirer/core/dist/esm/types/lib/key.d.mts b/node_modules/@inquirer/core/dist/esm/types/lib/key.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..e2ad3dc2aeb8372dd0c900c3408326339ae46045 --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/types/lib/key.d.mts @@ -0,0 +1,10 @@ +export type KeypressEvent = { + name: string; + ctrl: boolean; +}; +export declare const isUpKey: (key: KeypressEvent) => boolean; +export declare const isDownKey: (key: KeypressEvent) => boolean; +export declare const isSpaceKey: (key: KeypressEvent) => boolean; +export declare const isBackspaceKey: (key: KeypressEvent) => boolean; +export declare const isNumberKey: (key: KeypressEvent) => boolean; +export declare const isEnterKey: (key: KeypressEvent) => boolean; diff --git a/node_modules/@inquirer/core/dist/esm/types/lib/make-theme.d.mts b/node_modules/@inquirer/core/dist/esm/types/lib/make-theme.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..acd459c2532cf727fe3330a202f1764845ad0829 --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/types/lib/make-theme.d.mts @@ -0,0 +1,3 @@ +import type { Prettify, PartialDeep } from '@inquirer/type'; +import { type Theme } from './theme.mjs'; +export declare function makeTheme(...themes: ReadonlyArray>>): Prettify>; diff --git a/node_modules/@inquirer/core/dist/esm/types/lib/pagination/lines.d.mts b/node_modules/@inquirer/core/dist/esm/types/lib/pagination/lines.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..8e2270ac865d94856c882c4a062811e136d92422 --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/types/lib/pagination/lines.d.mts @@ -0,0 +1,26 @@ +import { type Prettify } from '@inquirer/type'; +/** Represents an item that's part of a layout, about to be rendered */ +export type Layout = { + item: T; + index: number; + isActive: boolean; +}; +/** + * Renders a page of items as lines that fit within the given width ensuring + * that the number of lines is not greater than the page size, and the active + * item renders at the provided position, while prioritizing that as many lines + * of the active item get rendered as possible. + */ +export declare function lines({ items, width, renderItem, active, position: requested, pageSize, }: { + items: readonly T[]; + /** The width of a rendered line in characters. */ + width: number; + /** Renders an item as part of a page. */ + renderItem: (layout: Prettify>) => string; + /** The index of the active item in the list of items. */ + active: number; + /** The position on the page at which to render the active item. */ + position: number; + /** The number of lines to render per page. */ + pageSize: number; +}): string[]; diff --git a/node_modules/@inquirer/core/dist/esm/types/lib/pagination/position.d.mts b/node_modules/@inquirer/core/dist/esm/types/lib/pagination/position.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..d74870e6c816b2a2b04d02ffa3b359f4d103ec8d --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/types/lib/pagination/position.d.mts @@ -0,0 +1,20 @@ +/** + * Creates the next position for the active item considering a finite list of + * items to be rendered on a page. + */ +export declare function finite({ active, pageSize, total, }: { + active: number; + pageSize: number; + total: number; +}): number; +/** + * Creates the next position for the active item considering an infinitely + * looping list of items to be rendered on the page. + */ +export declare function infinite({ active, lastActive, total, pageSize, pointer, }: { + active: number; + lastActive: number; + total: number; + pageSize: number; + pointer: number; +}): number; diff --git a/node_modules/@inquirer/core/dist/esm/types/lib/pagination/use-pagination.d.mts b/node_modules/@inquirer/core/dist/esm/types/lib/pagination/use-pagination.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..810918135efbab5f1930da549519ce286b6e9344 --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/types/lib/pagination/use-pagination.d.mts @@ -0,0 +1,15 @@ +import type { Prettify } from '@inquirer/type'; +import { type Theme } from '../theme.mjs'; +import { type Layout } from './lines.mjs'; +export declare function usePagination({ items, active, renderItem, pageSize, loop, }: { + items: readonly T[]; + /** The index of the active item. */ + active: number; + /** Renders an item as part of a page. */ + renderItem: (layout: Prettify>) => string; + /** The size of the page. */ + pageSize: number; + /** Allows creating an infinitely looping list. `true` if unspecified. */ + loop?: boolean; + theme?: Theme; +}): string; diff --git a/node_modules/@inquirer/core/dist/esm/types/lib/read-line.type.d.mts b/node_modules/@inquirer/core/dist/esm/types/lib/read-line.type.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..0046b74f8f78ca6de630ce991fbf16d854dc4ed6 --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/types/lib/read-line.type.d.mts @@ -0,0 +1,9 @@ +/// +/// +import * as readline from 'node:readline'; +import MuteStream from 'mute-stream'; +export type InquirerReadline = readline.ReadLine & { + output: MuteStream; + input: NodeJS.ReadableStream; + clearLine: (dir: 0 | 1 | -1) => void; +}; diff --git a/node_modules/@inquirer/core/dist/esm/types/lib/screen-manager.d.mts b/node_modules/@inquirer/core/dist/esm/types/lib/screen-manager.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..67db5bb0744ef99336240d2cc7b505984e9d4b2f --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/types/lib/screen-manager.d.mts @@ -0,0 +1,13 @@ +import type { InquirerReadline } from './read-line.type.mjs'; +export default class ScreenManager { + private readonly rl; + private height; + private extraLinesUnderPrompt; + private cursorPos; + constructor(rl: InquirerReadline); + render(content: string, bottomContent?: string): void; + checkCursorPos(): void; + clean(): void; + clearContent(): void; + done(): void; +} diff --git a/node_modules/@inquirer/core/dist/esm/types/lib/theme.d.mts b/node_modules/@inquirer/core/dist/esm/types/lib/theme.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..c319617267afc003b22dabe658d94315cbdb53c6 --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/types/lib/theme.d.mts @@ -0,0 +1,20 @@ +import type { Prettify } from '@inquirer/type'; +type DefaultTheme = { + prefix: string; + spinner: { + interval: number; + frames: string[]; + }; + style: { + answer: (text: string) => string; + message: (text: string) => string; + error: (text: string) => string; + defaultAnswer: (text: string) => string; + help: (text: string) => string; + highlight: (text: string) => string; + key: (text: string) => string; + }; +}; +export type Theme = Prettify; +export declare const defaultTheme: DefaultTheme; +export {}; diff --git a/node_modules/@inquirer/core/dist/esm/types/lib/use-effect.d.mts b/node_modules/@inquirer/core/dist/esm/types/lib/use-effect.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..24d91d5de11f06e37e2e3858c109fc590048ba73 --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/types/lib/use-effect.d.mts @@ -0,0 +1,2 @@ +import type { InquirerReadline } from './read-line.type.mjs'; +export declare function useEffect(cb: (rl: InquirerReadline) => void | (() => void), depArray: unknown[]): void; diff --git a/node_modules/@inquirer/core/dist/esm/types/lib/use-keypress.d.mts b/node_modules/@inquirer/core/dist/esm/types/lib/use-keypress.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..4e320a80a574601d989c5edfbd180f413683d39e --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/types/lib/use-keypress.d.mts @@ -0,0 +1,3 @@ +import { type InquirerReadline } from './read-line.type.mjs'; +import { type KeypressEvent } from './key.mjs'; +export declare function useKeypress(userHandler: (event: KeypressEvent, rl: InquirerReadline) => void): void; diff --git a/node_modules/@inquirer/core/dist/esm/types/lib/use-memo.d.mts b/node_modules/@inquirer/core/dist/esm/types/lib/use-memo.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..989092c16a73868f09b467e1c9f0141e8330b825 --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/types/lib/use-memo.d.mts @@ -0,0 +1 @@ +export declare function useMemo(fn: () => Value, dependencies: unknown[]): Value; diff --git a/node_modules/@inquirer/core/dist/esm/types/lib/use-prefix.d.mts b/node_modules/@inquirer/core/dist/esm/types/lib/use-prefix.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..4242eb3b7186a8333736338b3ee261bd5cd42db5 --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/types/lib/use-prefix.d.mts @@ -0,0 +1,5 @@ +import { type Theme } from './theme.mjs'; +export declare function usePrefix({ isLoading, theme, }: { + isLoading?: boolean; + theme?: Theme; +}): string; diff --git a/node_modules/@inquirer/core/dist/esm/types/lib/use-ref.d.mts b/node_modules/@inquirer/core/dist/esm/types/lib/use-ref.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..be7126b9e8784bebfe6526bdca70895a388a0c16 --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/types/lib/use-ref.d.mts @@ -0,0 +1,6 @@ +export declare function useRef(val: Value): { + current: Value; +}; +export declare function useRef(val?: Value): { + current: Value | undefined; +}; diff --git a/node_modules/@inquirer/core/dist/esm/types/lib/use-state.d.mts b/node_modules/@inquirer/core/dist/esm/types/lib/use-state.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..7730aede4edb9504d4f00d6afad47cfa4c898d20 --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/types/lib/use-state.d.mts @@ -0,0 +1,4 @@ +type NotFunction = T extends Function ? never : T; +export declare function useState(defaultValue: NotFunction | (() => Value)): [Value, (newValue: Value) => void]; +export declare function useState(defaultValue?: NotFunction | (() => Value)): [Value | undefined, (newValue?: Value | undefined) => void]; +export {}; diff --git a/node_modules/@inquirer/core/dist/esm/types/lib/utils.d.mts b/node_modules/@inquirer/core/dist/esm/types/lib/utils.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..14f8fc438e8a481cf90a4c071b18751e26f9f4d0 --- /dev/null +++ b/node_modules/@inquirer/core/dist/esm/types/lib/utils.d.mts @@ -0,0 +1,13 @@ +/** + * Force line returns at specific width. This function is ANSI code friendly and it'll + * ignore invisible codes during width calculation. + * @param {string} content + * @param {number} width + * @return {string} + */ +export declare function breakLines(content: string, width: number): string; +/** + * Returns the width of the active readline, or 80 as default value. + * @returns {number} + */ +export declare function readlineWidth(): number; diff --git a/node_modules/@inquirer/core/package.json b/node_modules/@inquirer/core/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a0a14ae04ed4b61539c2b30755068da6671ee9f3 --- /dev/null +++ b/node_modules/@inquirer/core/package.json @@ -0,0 +1,142 @@ +{ + "_from": "@inquirer/core@^8.2.3", + "_id": "@inquirer/core@8.2.3", + "_inBundle": false, + "_integrity": "sha512-WrpDVPAaxJQjHid3Ra4FhUO70YBzkHSYVyW5X48L5zHYdudoPISJqTRRWSeamHfaXda7PNNaC5Py5MEo7QwBNA==", + "_location": "/@inquirer/core", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@inquirer/core@^8.2.3", + "name": "@inquirer/core", + "escapedName": "@inquirer%2fcore", + "scope": "@inquirer", + "rawSpec": "^8.2.3", + "saveSpec": null, + "fetchSpec": "^8.2.3" + }, + "_requiredBy": [ + "/@inquirer/confirm" + ], + "_resolved": "https://registry.npmjs.org/@inquirer/core/-/core-8.2.3.tgz", + "_shasum": "e1986ae0e7de4c1dee72d34dcf0f9a3587709eff", + "_spec": "@inquirer/core@^8.2.3", + "_where": "/Users/sylvainfiloni/Documents/HuggingFace_Projects/live-vision/node_modules/@inquirer/confirm", + "author": { + "name": "Simon Boudrias", + "email": "admin@simonboudrias.com" + }, + "bugs": { + "url": "https://github.com/SBoudrias/Inquirer.js/issues" + }, + "bundleDependencies": false, + "dependencies": { + "@inquirer/figures": "^1.0.3", + "@inquirer/type": "^1.3.3", + "@types/mute-stream": "^0.0.4", + "@types/node": "^20.14.6", + "@types/wrap-ansi": "^3.0.0", + "ansi-escapes": "^4.3.2", + "chalk": "^4.1.2", + "cli-spinners": "^2.9.2", + "cli-width": "^4.1.0", + "mute-stream": "^1.0.0", + "signal-exit": "^4.1.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^6.2.0" + }, + "deprecated": false, + "description": "Core Inquirer prompt API", + "devDependencies": { + "@inquirer/testing": "^2.1.22" + }, + "engines": { + "node": ">=18" + }, + "exports": { + ".": { + "import": { + "types": "./dist/esm/types/index.d.mts", + "default": "./dist/esm/index.mjs" + }, + "require": { + "types": "./dist/cjs/types/index.d.ts", + "default": "./dist/cjs/index.js" + } + } + }, + "files": [ + "dist/**/*" + ], + "gitHead": "cc52a353abb1b7f3b3dc81b9e6da7ed478099dbf", + "homepage": "https://github.com/SBoudrias/Inquirer.js/blob/master/packages/core/README.md", + "keywords": [ + "answer", + "answers", + "ask", + "base", + "cli", + "command", + "command-line", + "confirm", + "enquirer", + "generate", + "generator", + "hyper", + "input", + "inquire", + "inquirer", + "interface", + "iterm", + "javascript", + "menu", + "node", + "nodejs", + "prompt", + "promptly", + "prompts", + "question", + "readline", + "scaffold", + "scaffolder", + "scaffolding", + "stdin", + "stdout", + "terminal", + "tty", + "ui", + "yeoman", + "yo", + "zsh" + ], + "license": "MIT", + "main": "./dist/cjs/index.js", + "name": "@inquirer/core", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/SBoudrias/Inquirer.js.git" + }, + "scripts": { + "attw": "attw --pack", + "dev": "tsc -p ./tsconfig.json --watch", + "tsc": "yarn run tsc:esm && yarn run tsc:cjs", + "tsc:cjs": "rm -rf dist/cjs && tsc -p ./tsconfig.cjs.json && node ../../tools/fix-ext.mjs", + "tsc:esm": "rm -rf dist/esm && tsc -p ./tsconfig.json" + }, + "sideEffects": false, + "typings": "./dist/cjs/types/index.d.ts", + "version": "8.2.3", + "warnings": [ + { + "code": "ENOTSUP", + "required": { + "node": ">=18" + }, + "pkgid": "@inquirer/core@8.2.3" + } + ] +} diff --git a/node_modules/@inquirer/figures/LICENSE b/node_modules/@inquirer/figures/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..6a10a8efe516e142e0f1cd556830460b2cc89d02 --- /dev/null +++ b/node_modules/@inquirer/figures/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2023 Simon Boudrias + +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/node_modules/@inquirer/figures/dist/cjs/index.js b/node_modules/@inquirer/figures/dist/cjs/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0e86a45b826fc1e421a62686a58519c8e0bb1b79 --- /dev/null +++ b/node_modules/@inquirer/figures/dist/cjs/index.js @@ -0,0 +1,313 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.replaceSymbols = exports.fallbackSymbols = exports.mainSymbols = void 0; +// process.env dot-notation access prints: +// Property 'TERM' comes from an index signature, so it must be accessed with ['TERM'].ts(4111) +/* eslint dot-notation: ["off"] */ +const node_process_1 = __importDefault(require("node:process")); +// Ported from is-unicode-supported +function isUnicodeSupported() { + if (node_process_1.default.platform !== 'win32') { + return node_process_1.default.env['TERM'] !== 'linux'; // Linux console (kernel) + } + return (Boolean(node_process_1.default.env['WT_SESSION']) || // Windows Terminal + Boolean(node_process_1.default.env['TERMINUS_SUBLIME']) || // Terminus (<0.2.27) + node_process_1.default.env['ConEmuTask'] === '{cmd::Cmder}' || // ConEmu and cmder + node_process_1.default.env['TERM_PROGRAM'] === 'Terminus-Sublime' || + node_process_1.default.env['TERM_PROGRAM'] === 'vscode' || + node_process_1.default.env['TERM'] === 'xterm-256color' || + node_process_1.default.env['TERM'] === 'alacritty' || + node_process_1.default.env['TERMINAL_EMULATOR'] === 'JetBrains-JediTerm'); +} +// Ported from figures +const common = { + circleQuestionMark: '(?)', + questionMarkPrefix: '(?)', + square: '█', + squareDarkShade: '▓', + squareMediumShade: '▒', + squareLightShade: '░', + squareTop: '▀', + squareBottom: '▄', + squareLeft: '▌', + squareRight: '▐', + squareCenter: '■', + bullet: '●', + dot: '․', + ellipsis: '…', + pointerSmall: '›', + triangleUp: '▲', + triangleUpSmall: '▴', + triangleDown: '▼', + triangleDownSmall: '▾', + triangleLeftSmall: '◂', + triangleRightSmall: '▸', + home: '⌂', + heart: '♥', + musicNote: '♪', + musicNoteBeamed: '♫', + arrowUp: '↑', + arrowDown: '↓', + arrowLeft: '←', + arrowRight: '→', + arrowLeftRight: '↔', + arrowUpDown: '↕', + almostEqual: '≈', + notEqual: '≠', + lessOrEqual: '≤', + greaterOrEqual: '≥', + identical: '≡', + infinity: '∞', + subscriptZero: '₀', + subscriptOne: '₁', + subscriptTwo: '₂', + subscriptThree: '₃', + subscriptFour: '₄', + subscriptFive: '₅', + subscriptSix: '₆', + subscriptSeven: '₇', + subscriptEight: '₈', + subscriptNine: '₉', + oneHalf: '½', + oneThird: '⅓', + oneQuarter: '¼', + oneFifth: '⅕', + oneSixth: '⅙', + oneEighth: '⅛', + twoThirds: '⅔', + twoFifths: '⅖', + threeQuarters: '¾', + threeFifths: '⅗', + threeEighths: '⅜', + fourFifths: '⅘', + fiveSixths: '⅚', + fiveEighths: '⅝', + sevenEighths: '⅞', + line: '─', + lineBold: '━', + lineDouble: '═', + lineDashed0: '┄', + lineDashed1: '┅', + lineDashed2: '┈', + lineDashed3: '┉', + lineDashed4: '╌', + lineDashed5: '╍', + lineDashed6: '╴', + lineDashed7: '╶', + lineDashed8: '╸', + lineDashed9: '╺', + lineDashed10: '╼', + lineDashed11: '╾', + lineDashed12: '−', + lineDashed13: '–', + lineDashed14: '‐', + lineDashed15: '⁃', + lineVertical: '│', + lineVerticalBold: '┃', + lineVerticalDouble: '║', + lineVerticalDashed0: '┆', + lineVerticalDashed1: '┇', + lineVerticalDashed2: '┊', + lineVerticalDashed3: '┋', + lineVerticalDashed4: '╎', + lineVerticalDashed5: '╏', + lineVerticalDashed6: '╵', + lineVerticalDashed7: '╷', + lineVerticalDashed8: '╹', + lineVerticalDashed9: '╻', + lineVerticalDashed10: '╽', + lineVerticalDashed11: '╿', + lineDownLeft: '┐', + lineDownLeftArc: '╮', + lineDownBoldLeftBold: '┓', + lineDownBoldLeft: '┒', + lineDownLeftBold: '┑', + lineDownDoubleLeftDouble: '╗', + lineDownDoubleLeft: '╖', + lineDownLeftDouble: '╕', + lineDownRight: '┌', + lineDownRightArc: '╭', + lineDownBoldRightBold: '┏', + lineDownBoldRight: '┎', + lineDownRightBold: '┍', + lineDownDoubleRightDouble: '╔', + lineDownDoubleRight: '╓', + lineDownRightDouble: '╒', + lineUpLeft: '┘', + lineUpLeftArc: '╯', + lineUpBoldLeftBold: '┛', + lineUpBoldLeft: '┚', + lineUpLeftBold: '┙', + lineUpDoubleLeftDouble: '╝', + lineUpDoubleLeft: '╜', + lineUpLeftDouble: '╛', + lineUpRight: '└', + lineUpRightArc: '╰', + lineUpBoldRightBold: '┗', + lineUpBoldRight: '┖', + lineUpRightBold: '┕', + lineUpDoubleRightDouble: '╚', + lineUpDoubleRight: '╙', + lineUpRightDouble: '╘', + lineUpDownLeft: '┤', + lineUpBoldDownBoldLeftBold: '┫', + lineUpBoldDownBoldLeft: '┨', + lineUpDownLeftBold: '┥', + lineUpBoldDownLeftBold: '┩', + lineUpDownBoldLeftBold: '┪', + lineUpDownBoldLeft: '┧', + lineUpBoldDownLeft: '┦', + lineUpDoubleDownDoubleLeftDouble: '╣', + lineUpDoubleDownDoubleLeft: '╢', + lineUpDownLeftDouble: '╡', + lineUpDownRight: '├', + lineUpBoldDownBoldRightBold: '┣', + lineUpBoldDownBoldRight: '┠', + lineUpDownRightBold: '┝', + lineUpBoldDownRightBold: '┡', + lineUpDownBoldRightBold: '┢', + lineUpDownBoldRight: '┟', + lineUpBoldDownRight: '┞', + lineUpDoubleDownDoubleRightDouble: '╠', + lineUpDoubleDownDoubleRight: '╟', + lineUpDownRightDouble: '╞', + lineDownLeftRight: '┬', + lineDownBoldLeftBoldRightBold: '┳', + lineDownLeftBoldRightBold: '┯', + lineDownBoldLeftRight: '┰', + lineDownBoldLeftBoldRight: '┱', + lineDownBoldLeftRightBold: '┲', + lineDownLeftRightBold: '┮', + lineDownLeftBoldRight: '┭', + lineDownDoubleLeftDoubleRightDouble: '╦', + lineDownDoubleLeftRight: '╥', + lineDownLeftDoubleRightDouble: '╤', + lineUpLeftRight: '┴', + lineUpBoldLeftBoldRightBold: '┻', + lineUpLeftBoldRightBold: '┷', + lineUpBoldLeftRight: '┸', + lineUpBoldLeftBoldRight: '┹', + lineUpBoldLeftRightBold: '┺', + lineUpLeftRightBold: '┶', + lineUpLeftBoldRight: '┵', + lineUpDoubleLeftDoubleRightDouble: '╩', + lineUpDoubleLeftRight: '╨', + lineUpLeftDoubleRightDouble: '╧', + lineUpDownLeftRight: '┼', + lineUpBoldDownBoldLeftBoldRightBold: '╋', + lineUpDownBoldLeftBoldRightBold: '╈', + lineUpBoldDownLeftBoldRightBold: '╇', + lineUpBoldDownBoldLeftRightBold: '╊', + lineUpBoldDownBoldLeftBoldRight: '╉', + lineUpBoldDownLeftRight: '╀', + lineUpDownBoldLeftRight: '╁', + lineUpDownLeftBoldRight: '┽', + lineUpDownLeftRightBold: '┾', + lineUpBoldDownBoldLeftRight: '╂', + lineUpDownLeftBoldRightBold: '┿', + lineUpBoldDownLeftBoldRight: '╃', + lineUpBoldDownLeftRightBold: '╄', + lineUpDownBoldLeftBoldRight: '╅', + lineUpDownBoldLeftRightBold: '╆', + lineUpDoubleDownDoubleLeftDoubleRightDouble: '╬', + lineUpDoubleDownDoubleLeftRight: '╫', + lineUpDownLeftDoubleRightDouble: '╪', + lineCross: '╳', + lineBackslash: '╲', + lineSlash: '╱', +}; +const specialMainSymbols = { + tick: '✔', + info: 'ℹ', + warning: '⚠', + cross: '✘', + squareSmall: '◻', + squareSmallFilled: '◼', + circle: '◯', + circleFilled: '◉', + circleDotted: '◌', + circleDouble: '◎', + circleCircle: 'ⓞ', + circleCross: 'ⓧ', + circlePipe: 'Ⓘ', + radioOn: '◉', + radioOff: '◯', + checkboxOn: '☒', + checkboxOff: '☐', + checkboxCircleOn: 'ⓧ', + checkboxCircleOff: 'Ⓘ', + pointer: '❯', + triangleUpOutline: '△', + triangleLeft: '◀', + triangleRight: '▶', + lozenge: '◆', + lozengeOutline: '◇', + hamburger: '☰', + smiley: '㋡', + mustache: '෴', + star: '★', + play: '▶', + nodejs: '⬢', + oneSeventh: '⅐', + oneNinth: '⅑', + oneTenth: '⅒', +}; +const specialFallbackSymbols = { + tick: '√', + info: 'i', + warning: '‼', + cross: '×', + squareSmall: '□', + squareSmallFilled: '■', + circle: '( )', + circleFilled: '(*)', + circleDotted: '( )', + circleDouble: '( )', + circleCircle: '(○)', + circleCross: '(×)', + circlePipe: '(│)', + radioOn: '(*)', + radioOff: '( )', + checkboxOn: '[×]', + checkboxOff: '[ ]', + checkboxCircleOn: '(×)', + checkboxCircleOff: '( )', + pointer: '>', + triangleUpOutline: '∆', + triangleLeft: '◄', + triangleRight: '►', + lozenge: '♦', + lozengeOutline: '◊', + hamburger: '≡', + smiley: '☺', + mustache: '┌─┐', + star: '✶', + play: '►', + nodejs: '♦', + oneSeventh: '1/7', + oneNinth: '1/9', + oneTenth: '1/10', +}; +exports.mainSymbols = Object.assign(Object.assign({}, common), specialMainSymbols); +exports.fallbackSymbols = Object.assign(Object.assign({}, common), specialFallbackSymbols); +const shouldUseMain = isUnicodeSupported(); +const figures = shouldUseMain ? exports.mainSymbols : exports.fallbackSymbols; +exports.default = figures; +const replacements = Object.entries(specialMainSymbols); +// On terminals which do not support Unicode symbols, substitute them to other symbols +const replaceSymbols = (string, { useFallback = !shouldUseMain } = {}) => { + if (useFallback) { + for (const [key, mainSymbol] of replacements) { + const fallbackSymbol = exports.fallbackSymbols[key]; + if (!fallbackSymbol) { + throw new Error(`Unable to find fallback for ${key}`); + } + string = string.replaceAll(mainSymbol, fallbackSymbol); + } + } + return string; +}; +exports.replaceSymbols = replaceSymbols; diff --git a/node_modules/@inquirer/figures/dist/cjs/types/index.d.ts b/node_modules/@inquirer/figures/dist/cjs/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f8202e508b5f7c560c1c0ae5ad16bf4ecc93b877 --- /dev/null +++ b/node_modules/@inquirer/figures/dist/cjs/types/index.d.ts @@ -0,0 +1,465 @@ +export declare const mainSymbols: { + tick: string; + info: string; + warning: string; + cross: string; + squareSmall: string; + squareSmallFilled: string; + circle: string; + circleFilled: string; + circleDotted: string; + circleDouble: string; + circleCircle: string; + circleCross: string; + circlePipe: string; + radioOn: string; + radioOff: string; + checkboxOn: string; + checkboxOff: string; + checkboxCircleOn: string; + checkboxCircleOff: string; + pointer: string; + triangleUpOutline: string; + triangleLeft: string; + triangleRight: string; + lozenge: string; + lozengeOutline: string; + hamburger: string; + smiley: string; + mustache: string; + star: string; + play: string; + nodejs: string; + oneSeventh: string; + oneNinth: string; + oneTenth: string; + circleQuestionMark: string; + questionMarkPrefix: string; + square: string; + squareDarkShade: string; + squareMediumShade: string; + squareLightShade: string; + squareTop: string; + squareBottom: string; + squareLeft: string; + squareRight: string; + squareCenter: string; + bullet: string; + dot: string; + ellipsis: string; + pointerSmall: string; + triangleUp: string; + triangleUpSmall: string; + triangleDown: string; + triangleDownSmall: string; + triangleLeftSmall: string; + triangleRightSmall: string; + home: string; + heart: string; + musicNote: string; + musicNoteBeamed: string; + arrowUp: string; + arrowDown: string; + arrowLeft: string; + arrowRight: string; + arrowLeftRight: string; + arrowUpDown: string; + almostEqual: string; + notEqual: string; + lessOrEqual: string; + greaterOrEqual: string; + identical: string; + infinity: string; + subscriptZero: string; + subscriptOne: string; + subscriptTwo: string; + subscriptThree: string; + subscriptFour: string; + subscriptFive: string; + subscriptSix: string; + subscriptSeven: string; + subscriptEight: string; + subscriptNine: string; + oneHalf: string; + oneThird: string; + oneQuarter: string; + oneFifth: string; + oneSixth: string; + oneEighth: string; + twoThirds: string; + twoFifths: string; + threeQuarters: string; + threeFifths: string; + threeEighths: string; + fourFifths: string; + fiveSixths: string; + fiveEighths: string; + sevenEighths: string; + line: string; + lineBold: string; + lineDouble: string; + lineDashed0: string; + lineDashed1: string; + lineDashed2: string; + lineDashed3: string; + lineDashed4: string; + lineDashed5: string; + lineDashed6: string; + lineDashed7: string; + lineDashed8: string; + lineDashed9: string; + lineDashed10: string; + lineDashed11: string; + lineDashed12: string; + lineDashed13: string; + lineDashed14: string; + lineDashed15: string; + lineVertical: string; + lineVerticalBold: string; + lineVerticalDouble: string; + lineVerticalDashed0: string; + lineVerticalDashed1: string; + lineVerticalDashed2: string; + lineVerticalDashed3: string; + lineVerticalDashed4: string; + lineVerticalDashed5: string; + lineVerticalDashed6: string; + lineVerticalDashed7: string; + lineVerticalDashed8: string; + lineVerticalDashed9: string; + lineVerticalDashed10: string; + lineVerticalDashed11: string; + lineDownLeft: string; + lineDownLeftArc: string; + lineDownBoldLeftBold: string; + lineDownBoldLeft: string; + lineDownLeftBold: string; + lineDownDoubleLeftDouble: string; + lineDownDoubleLeft: string; + lineDownLeftDouble: string; + lineDownRight: string; + lineDownRightArc: string; + lineDownBoldRightBold: string; + lineDownBoldRight: string; + lineDownRightBold: string; + lineDownDoubleRightDouble: string; + lineDownDoubleRight: string; + lineDownRightDouble: string; + lineUpLeft: string; + lineUpLeftArc: string; + lineUpBoldLeftBold: string; + lineUpBoldLeft: string; + lineUpLeftBold: string; + lineUpDoubleLeftDouble: string; + lineUpDoubleLeft: string; + lineUpLeftDouble: string; + lineUpRight: string; + lineUpRightArc: string; + lineUpBoldRightBold: string; + lineUpBoldRight: string; + lineUpRightBold: string; + lineUpDoubleRightDouble: string; + lineUpDoubleRight: string; + lineUpRightDouble: string; + lineUpDownLeft: string; + lineUpBoldDownBoldLeftBold: string; + lineUpBoldDownBoldLeft: string; + lineUpDownLeftBold: string; + lineUpBoldDownLeftBold: string; + lineUpDownBoldLeftBold: string; + lineUpDownBoldLeft: string; + lineUpBoldDownLeft: string; + lineUpDoubleDownDoubleLeftDouble: string; + lineUpDoubleDownDoubleLeft: string; + lineUpDownLeftDouble: string; + lineUpDownRight: string; + lineUpBoldDownBoldRightBold: string; + lineUpBoldDownBoldRight: string; + lineUpDownRightBold: string; + lineUpBoldDownRightBold: string; + lineUpDownBoldRightBold: string; + lineUpDownBoldRight: string; + lineUpBoldDownRight: string; + lineUpDoubleDownDoubleRightDouble: string; + lineUpDoubleDownDoubleRight: string; + lineUpDownRightDouble: string; + lineDownLeftRight: string; + lineDownBoldLeftBoldRightBold: string; + lineDownLeftBoldRightBold: string; + lineDownBoldLeftRight: string; + lineDownBoldLeftBoldRight: string; + lineDownBoldLeftRightBold: string; + lineDownLeftRightBold: string; + lineDownLeftBoldRight: string; + lineDownDoubleLeftDoubleRightDouble: string; + lineDownDoubleLeftRight: string; + lineDownLeftDoubleRightDouble: string; + lineUpLeftRight: string; + lineUpBoldLeftBoldRightBold: string; + lineUpLeftBoldRightBold: string; + lineUpBoldLeftRight: string; + lineUpBoldLeftBoldRight: string; + lineUpBoldLeftRightBold: string; + lineUpLeftRightBold: string; + lineUpLeftBoldRight: string; + lineUpDoubleLeftDoubleRightDouble: string; + lineUpDoubleLeftRight: string; + lineUpLeftDoubleRightDouble: string; + lineUpDownLeftRight: string; + lineUpBoldDownBoldLeftBoldRightBold: string; + lineUpDownBoldLeftBoldRightBold: string; + lineUpBoldDownLeftBoldRightBold: string; + lineUpBoldDownBoldLeftRightBold: string; + lineUpBoldDownBoldLeftBoldRight: string; + lineUpBoldDownLeftRight: string; + lineUpDownBoldLeftRight: string; + lineUpDownLeftBoldRight: string; + lineUpDownLeftRightBold: string; + lineUpBoldDownBoldLeftRight: string; + lineUpDownLeftBoldRightBold: string; + lineUpBoldDownLeftBoldRight: string; + lineUpBoldDownLeftRightBold: string; + lineUpDownBoldLeftBoldRight: string; + lineUpDownBoldLeftRightBold: string; + lineUpDoubleDownDoubleLeftDoubleRightDouble: string; + lineUpDoubleDownDoubleLeftRight: string; + lineUpDownLeftDoubleRightDouble: string; + lineCross: string; + lineBackslash: string; + lineSlash: string; +}; +export declare const fallbackSymbols: Record; +declare const figures: { + tick: string; + info: string; + warning: string; + cross: string; + squareSmall: string; + squareSmallFilled: string; + circle: string; + circleFilled: string; + circleDotted: string; + circleDouble: string; + circleCircle: string; + circleCross: string; + circlePipe: string; + radioOn: string; + radioOff: string; + checkboxOn: string; + checkboxOff: string; + checkboxCircleOn: string; + checkboxCircleOff: string; + pointer: string; + triangleUpOutline: string; + triangleLeft: string; + triangleRight: string; + lozenge: string; + lozengeOutline: string; + hamburger: string; + smiley: string; + mustache: string; + star: string; + play: string; + nodejs: string; + oneSeventh: string; + oneNinth: string; + oneTenth: string; + circleQuestionMark: string; + questionMarkPrefix: string; + square: string; + squareDarkShade: string; + squareMediumShade: string; + squareLightShade: string; + squareTop: string; + squareBottom: string; + squareLeft: string; + squareRight: string; + squareCenter: string; + bullet: string; + dot: string; + ellipsis: string; + pointerSmall: string; + triangleUp: string; + triangleUpSmall: string; + triangleDown: string; + triangleDownSmall: string; + triangleLeftSmall: string; + triangleRightSmall: string; + home: string; + heart: string; + musicNote: string; + musicNoteBeamed: string; + arrowUp: string; + arrowDown: string; + arrowLeft: string; + arrowRight: string; + arrowLeftRight: string; + arrowUpDown: string; + almostEqual: string; + notEqual: string; + lessOrEqual: string; + greaterOrEqual: string; + identical: string; + infinity: string; + subscriptZero: string; + subscriptOne: string; + subscriptTwo: string; + subscriptThree: string; + subscriptFour: string; + subscriptFive: string; + subscriptSix: string; + subscriptSeven: string; + subscriptEight: string; + subscriptNine: string; + oneHalf: string; + oneThird: string; + oneQuarter: string; + oneFifth: string; + oneSixth: string; + oneEighth: string; + twoThirds: string; + twoFifths: string; + threeQuarters: string; + threeFifths: string; + threeEighths: string; + fourFifths: string; + fiveSixths: string; + fiveEighths: string; + sevenEighths: string; + line: string; + lineBold: string; + lineDouble: string; + lineDashed0: string; + lineDashed1: string; + lineDashed2: string; + lineDashed3: string; + lineDashed4: string; + lineDashed5: string; + lineDashed6: string; + lineDashed7: string; + lineDashed8: string; + lineDashed9: string; + lineDashed10: string; + lineDashed11: string; + lineDashed12: string; + lineDashed13: string; + lineDashed14: string; + lineDashed15: string; + lineVertical: string; + lineVerticalBold: string; + lineVerticalDouble: string; + lineVerticalDashed0: string; + lineVerticalDashed1: string; + lineVerticalDashed2: string; + lineVerticalDashed3: string; + lineVerticalDashed4: string; + lineVerticalDashed5: string; + lineVerticalDashed6: string; + lineVerticalDashed7: string; + lineVerticalDashed8: string; + lineVerticalDashed9: string; + lineVerticalDashed10: string; + lineVerticalDashed11: string; + lineDownLeft: string; + lineDownLeftArc: string; + lineDownBoldLeftBold: string; + lineDownBoldLeft: string; + lineDownLeftBold: string; + lineDownDoubleLeftDouble: string; + lineDownDoubleLeft: string; + lineDownLeftDouble: string; + lineDownRight: string; + lineDownRightArc: string; + lineDownBoldRightBold: string; + lineDownBoldRight: string; + lineDownRightBold: string; + lineDownDoubleRightDouble: string; + lineDownDoubleRight: string; + lineDownRightDouble: string; + lineUpLeft: string; + lineUpLeftArc: string; + lineUpBoldLeftBold: string; + lineUpBoldLeft: string; + lineUpLeftBold: string; + lineUpDoubleLeftDouble: string; + lineUpDoubleLeft: string; + lineUpLeftDouble: string; + lineUpRight: string; + lineUpRightArc: string; + lineUpBoldRightBold: string; + lineUpBoldRight: string; + lineUpRightBold: string; + lineUpDoubleRightDouble: string; + lineUpDoubleRight: string; + lineUpRightDouble: string; + lineUpDownLeft: string; + lineUpBoldDownBoldLeftBold: string; + lineUpBoldDownBoldLeft: string; + lineUpDownLeftBold: string; + lineUpBoldDownLeftBold: string; + lineUpDownBoldLeftBold: string; + lineUpDownBoldLeft: string; + lineUpBoldDownLeft: string; + lineUpDoubleDownDoubleLeftDouble: string; + lineUpDoubleDownDoubleLeft: string; + lineUpDownLeftDouble: string; + lineUpDownRight: string; + lineUpBoldDownBoldRightBold: string; + lineUpBoldDownBoldRight: string; + lineUpDownRightBold: string; + lineUpBoldDownRightBold: string; + lineUpDownBoldRightBold: string; + lineUpDownBoldRight: string; + lineUpBoldDownRight: string; + lineUpDoubleDownDoubleRightDouble: string; + lineUpDoubleDownDoubleRight: string; + lineUpDownRightDouble: string; + lineDownLeftRight: string; + lineDownBoldLeftBoldRightBold: string; + lineDownLeftBoldRightBold: string; + lineDownBoldLeftRight: string; + lineDownBoldLeftBoldRight: string; + lineDownBoldLeftRightBold: string; + lineDownLeftRightBold: string; + lineDownLeftBoldRight: string; + lineDownDoubleLeftDoubleRightDouble: string; + lineDownDoubleLeftRight: string; + lineDownLeftDoubleRightDouble: string; + lineUpLeftRight: string; + lineUpBoldLeftBoldRightBold: string; + lineUpLeftBoldRightBold: string; + lineUpBoldLeftRight: string; + lineUpBoldLeftBoldRight: string; + lineUpBoldLeftRightBold: string; + lineUpLeftRightBold: string; + lineUpLeftBoldRight: string; + lineUpDoubleLeftDoubleRightDouble: string; + lineUpDoubleLeftRight: string; + lineUpLeftDoubleRightDouble: string; + lineUpDownLeftRight: string; + lineUpBoldDownBoldLeftBoldRightBold: string; + lineUpDownBoldLeftBoldRightBold: string; + lineUpBoldDownLeftBoldRightBold: string; + lineUpBoldDownBoldLeftRightBold: string; + lineUpBoldDownBoldLeftBoldRight: string; + lineUpBoldDownLeftRight: string; + lineUpDownBoldLeftRight: string; + lineUpDownLeftBoldRight: string; + lineUpDownLeftRightBold: string; + lineUpBoldDownBoldLeftRight: string; + lineUpDownLeftBoldRightBold: string; + lineUpBoldDownLeftBoldRight: string; + lineUpBoldDownLeftRightBold: string; + lineUpDownBoldLeftBoldRight: string; + lineUpDownBoldLeftRightBold: string; + lineUpDoubleDownDoubleLeftDoubleRightDouble: string; + lineUpDoubleDownDoubleLeftRight: string; + lineUpDownLeftDoubleRightDouble: string; + lineCross: string; + lineBackslash: string; + lineSlash: string; +} | Record; +export default figures; +export declare const replaceSymbols: (string: string, { useFallback }?: { + useFallback?: boolean | undefined; +}) => string; diff --git a/node_modules/@inquirer/figures/dist/esm/index.mjs b/node_modules/@inquirer/figures/dist/esm/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d43b15e630fa12ec082806563fd405bc687ef012 --- /dev/null +++ b/node_modules/@inquirer/figures/dist/esm/index.mjs @@ -0,0 +1,309 @@ +// process.env dot-notation access prints: +// Property 'TERM' comes from an index signature, so it must be accessed with ['TERM'].ts(4111) +/* eslint dot-notation: ["off"] */ +import process from 'node:process'; +// Ported from is-unicode-supported +function isUnicodeSupported() { + if (process.platform !== 'win32') { + return process.env['TERM'] !== 'linux'; // Linux console (kernel) + } + return (Boolean(process.env['WT_SESSION']) || // Windows Terminal + Boolean(process.env['TERMINUS_SUBLIME']) || // Terminus (<0.2.27) + process.env['ConEmuTask'] === '{cmd::Cmder}' || // ConEmu and cmder + process.env['TERM_PROGRAM'] === 'Terminus-Sublime' || + process.env['TERM_PROGRAM'] === 'vscode' || + process.env['TERM'] === 'xterm-256color' || + process.env['TERM'] === 'alacritty' || + process.env['TERMINAL_EMULATOR'] === 'JetBrains-JediTerm'); +} +// Ported from figures +const common = { + circleQuestionMark: '(?)', + questionMarkPrefix: '(?)', + square: '█', + squareDarkShade: '▓', + squareMediumShade: '▒', + squareLightShade: '░', + squareTop: '▀', + squareBottom: '▄', + squareLeft: '▌', + squareRight: '▐', + squareCenter: '■', + bullet: '●', + dot: '․', + ellipsis: '…', + pointerSmall: '›', + triangleUp: '▲', + triangleUpSmall: '▴', + triangleDown: '▼', + triangleDownSmall: '▾', + triangleLeftSmall: '◂', + triangleRightSmall: '▸', + home: '⌂', + heart: '♥', + musicNote: '♪', + musicNoteBeamed: '♫', + arrowUp: '↑', + arrowDown: '↓', + arrowLeft: '←', + arrowRight: '→', + arrowLeftRight: '↔', + arrowUpDown: '↕', + almostEqual: '≈', + notEqual: '≠', + lessOrEqual: '≤', + greaterOrEqual: '≥', + identical: '≡', + infinity: '∞', + subscriptZero: '₀', + subscriptOne: '₁', + subscriptTwo: '₂', + subscriptThree: '₃', + subscriptFour: '₄', + subscriptFive: '₅', + subscriptSix: '₆', + subscriptSeven: '₇', + subscriptEight: '₈', + subscriptNine: '₉', + oneHalf: '½', + oneThird: '⅓', + oneQuarter: '¼', + oneFifth: '⅕', + oneSixth: '⅙', + oneEighth: '⅛', + twoThirds: '⅔', + twoFifths: '⅖', + threeQuarters: '¾', + threeFifths: '⅗', + threeEighths: '⅜', + fourFifths: '⅘', + fiveSixths: '⅚', + fiveEighths: '⅝', + sevenEighths: '⅞', + line: '─', + lineBold: '━', + lineDouble: '═', + lineDashed0: '┄', + lineDashed1: '┅', + lineDashed2: '┈', + lineDashed3: '┉', + lineDashed4: '╌', + lineDashed5: '╍', + lineDashed6: '╴', + lineDashed7: '╶', + lineDashed8: '╸', + lineDashed9: '╺', + lineDashed10: '╼', + lineDashed11: '╾', + lineDashed12: '−', + lineDashed13: '–', + lineDashed14: '‐', + lineDashed15: '⁃', + lineVertical: '│', + lineVerticalBold: '┃', + lineVerticalDouble: '║', + lineVerticalDashed0: '┆', + lineVerticalDashed1: '┇', + lineVerticalDashed2: '┊', + lineVerticalDashed3: '┋', + lineVerticalDashed4: '╎', + lineVerticalDashed5: '╏', + lineVerticalDashed6: '╵', + lineVerticalDashed7: '╷', + lineVerticalDashed8: '╹', + lineVerticalDashed9: '╻', + lineVerticalDashed10: '╽', + lineVerticalDashed11: '╿', + lineDownLeft: '┐', + lineDownLeftArc: '╮', + lineDownBoldLeftBold: '┓', + lineDownBoldLeft: '┒', + lineDownLeftBold: '┑', + lineDownDoubleLeftDouble: '╗', + lineDownDoubleLeft: '╖', + lineDownLeftDouble: '╕', + lineDownRight: '┌', + lineDownRightArc: '╭', + lineDownBoldRightBold: '┏', + lineDownBoldRight: '┎', + lineDownRightBold: '┍', + lineDownDoubleRightDouble: '╔', + lineDownDoubleRight: '╓', + lineDownRightDouble: '╒', + lineUpLeft: '┘', + lineUpLeftArc: '╯', + lineUpBoldLeftBold: '┛', + lineUpBoldLeft: '┚', + lineUpLeftBold: '┙', + lineUpDoubleLeftDouble: '╝', + lineUpDoubleLeft: '╜', + lineUpLeftDouble: '╛', + lineUpRight: '└', + lineUpRightArc: '╰', + lineUpBoldRightBold: '┗', + lineUpBoldRight: '┖', + lineUpRightBold: '┕', + lineUpDoubleRightDouble: '╚', + lineUpDoubleRight: '╙', + lineUpRightDouble: '╘', + lineUpDownLeft: '┤', + lineUpBoldDownBoldLeftBold: '┫', + lineUpBoldDownBoldLeft: '┨', + lineUpDownLeftBold: '┥', + lineUpBoldDownLeftBold: '┩', + lineUpDownBoldLeftBold: '┪', + lineUpDownBoldLeft: '┧', + lineUpBoldDownLeft: '┦', + lineUpDoubleDownDoubleLeftDouble: '╣', + lineUpDoubleDownDoubleLeft: '╢', + lineUpDownLeftDouble: '╡', + lineUpDownRight: '├', + lineUpBoldDownBoldRightBold: '┣', + lineUpBoldDownBoldRight: '┠', + lineUpDownRightBold: '┝', + lineUpBoldDownRightBold: '┡', + lineUpDownBoldRightBold: '┢', + lineUpDownBoldRight: '┟', + lineUpBoldDownRight: '┞', + lineUpDoubleDownDoubleRightDouble: '╠', + lineUpDoubleDownDoubleRight: '╟', + lineUpDownRightDouble: '╞', + lineDownLeftRight: '┬', + lineDownBoldLeftBoldRightBold: '┳', + lineDownLeftBoldRightBold: '┯', + lineDownBoldLeftRight: '┰', + lineDownBoldLeftBoldRight: '┱', + lineDownBoldLeftRightBold: '┲', + lineDownLeftRightBold: '┮', + lineDownLeftBoldRight: '┭', + lineDownDoubleLeftDoubleRightDouble: '╦', + lineDownDoubleLeftRight: '╥', + lineDownLeftDoubleRightDouble: '╤', + lineUpLeftRight: '┴', + lineUpBoldLeftBoldRightBold: '┻', + lineUpLeftBoldRightBold: '┷', + lineUpBoldLeftRight: '┸', + lineUpBoldLeftBoldRight: '┹', + lineUpBoldLeftRightBold: '┺', + lineUpLeftRightBold: '┶', + lineUpLeftBoldRight: '┵', + lineUpDoubleLeftDoubleRightDouble: '╩', + lineUpDoubleLeftRight: '╨', + lineUpLeftDoubleRightDouble: '╧', + lineUpDownLeftRight: '┼', + lineUpBoldDownBoldLeftBoldRightBold: '╋', + lineUpDownBoldLeftBoldRightBold: '╈', + lineUpBoldDownLeftBoldRightBold: '╇', + lineUpBoldDownBoldLeftRightBold: '╊', + lineUpBoldDownBoldLeftBoldRight: '╉', + lineUpBoldDownLeftRight: '╀', + lineUpDownBoldLeftRight: '╁', + lineUpDownLeftBoldRight: '┽', + lineUpDownLeftRightBold: '┾', + lineUpBoldDownBoldLeftRight: '╂', + lineUpDownLeftBoldRightBold: '┿', + lineUpBoldDownLeftBoldRight: '╃', + lineUpBoldDownLeftRightBold: '╄', + lineUpDownBoldLeftBoldRight: '╅', + lineUpDownBoldLeftRightBold: '╆', + lineUpDoubleDownDoubleLeftDoubleRightDouble: '╬', + lineUpDoubleDownDoubleLeftRight: '╫', + lineUpDownLeftDoubleRightDouble: '╪', + lineCross: '╳', + lineBackslash: '╲', + lineSlash: '╱', +}; +const specialMainSymbols = { + tick: '✔', + info: 'ℹ', + warning: '⚠', + cross: '✘', + squareSmall: '◻', + squareSmallFilled: '◼', + circle: '◯', + circleFilled: '◉', + circleDotted: '◌', + circleDouble: '◎', + circleCircle: 'ⓞ', + circleCross: 'ⓧ', + circlePipe: 'Ⓘ', + radioOn: '◉', + radioOff: '◯', + checkboxOn: '☒', + checkboxOff: '☐', + checkboxCircleOn: 'ⓧ', + checkboxCircleOff: 'Ⓘ', + pointer: '❯', + triangleUpOutline: '△', + triangleLeft: '◀', + triangleRight: '▶', + lozenge: '◆', + lozengeOutline: '◇', + hamburger: '☰', + smiley: '㋡', + mustache: '෴', + star: '★', + play: '▶', + nodejs: '⬢', + oneSeventh: '⅐', + oneNinth: '⅑', + oneTenth: '⅒', +}; +const specialFallbackSymbols = { + tick: '√', + info: 'i', + warning: '‼', + cross: '×', + squareSmall: '□', + squareSmallFilled: '■', + circle: '( )', + circleFilled: '(*)', + circleDotted: '( )', + circleDouble: '( )', + circleCircle: '(○)', + circleCross: '(×)', + circlePipe: '(│)', + radioOn: '(*)', + radioOff: '( )', + checkboxOn: '[×]', + checkboxOff: '[ ]', + checkboxCircleOn: '(×)', + checkboxCircleOff: '( )', + pointer: '>', + triangleUpOutline: '∆', + triangleLeft: '◄', + triangleRight: '►', + lozenge: '♦', + lozengeOutline: '◊', + hamburger: '≡', + smiley: '☺', + mustache: '┌─┐', + star: '✶', + play: '►', + nodejs: '♦', + oneSeventh: '1/7', + oneNinth: '1/9', + oneTenth: '1/10', +}; +export const mainSymbols = { ...common, ...specialMainSymbols }; +export const fallbackSymbols = { + ...common, + ...specialFallbackSymbols, +}; +const shouldUseMain = isUnicodeSupported(); +const figures = shouldUseMain ? mainSymbols : fallbackSymbols; +export default figures; +const replacements = Object.entries(specialMainSymbols); +// On terminals which do not support Unicode symbols, substitute them to other symbols +export const replaceSymbols = (string, { useFallback = !shouldUseMain } = {}) => { + if (useFallback) { + for (const [key, mainSymbol] of replacements) { + const fallbackSymbol = fallbackSymbols[key]; + if (!fallbackSymbol) { + throw new Error(`Unable to find fallback for ${key}`); + } + string = string.replaceAll(mainSymbol, fallbackSymbol); + } + } + return string; +}; diff --git a/node_modules/@inquirer/figures/dist/esm/types/index.d.mts b/node_modules/@inquirer/figures/dist/esm/types/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..f8202e508b5f7c560c1c0ae5ad16bf4ecc93b877 --- /dev/null +++ b/node_modules/@inquirer/figures/dist/esm/types/index.d.mts @@ -0,0 +1,465 @@ +export declare const mainSymbols: { + tick: string; + info: string; + warning: string; + cross: string; + squareSmall: string; + squareSmallFilled: string; + circle: string; + circleFilled: string; + circleDotted: string; + circleDouble: string; + circleCircle: string; + circleCross: string; + circlePipe: string; + radioOn: string; + radioOff: string; + checkboxOn: string; + checkboxOff: string; + checkboxCircleOn: string; + checkboxCircleOff: string; + pointer: string; + triangleUpOutline: string; + triangleLeft: string; + triangleRight: string; + lozenge: string; + lozengeOutline: string; + hamburger: string; + smiley: string; + mustache: string; + star: string; + play: string; + nodejs: string; + oneSeventh: string; + oneNinth: string; + oneTenth: string; + circleQuestionMark: string; + questionMarkPrefix: string; + square: string; + squareDarkShade: string; + squareMediumShade: string; + squareLightShade: string; + squareTop: string; + squareBottom: string; + squareLeft: string; + squareRight: string; + squareCenter: string; + bullet: string; + dot: string; + ellipsis: string; + pointerSmall: string; + triangleUp: string; + triangleUpSmall: string; + triangleDown: string; + triangleDownSmall: string; + triangleLeftSmall: string; + triangleRightSmall: string; + home: string; + heart: string; + musicNote: string; + musicNoteBeamed: string; + arrowUp: string; + arrowDown: string; + arrowLeft: string; + arrowRight: string; + arrowLeftRight: string; + arrowUpDown: string; + almostEqual: string; + notEqual: string; + lessOrEqual: string; + greaterOrEqual: string; + identical: string; + infinity: string; + subscriptZero: string; + subscriptOne: string; + subscriptTwo: string; + subscriptThree: string; + subscriptFour: string; + subscriptFive: string; + subscriptSix: string; + subscriptSeven: string; + subscriptEight: string; + subscriptNine: string; + oneHalf: string; + oneThird: string; + oneQuarter: string; + oneFifth: string; + oneSixth: string; + oneEighth: string; + twoThirds: string; + twoFifths: string; + threeQuarters: string; + threeFifths: string; + threeEighths: string; + fourFifths: string; + fiveSixths: string; + fiveEighths: string; + sevenEighths: string; + line: string; + lineBold: string; + lineDouble: string; + lineDashed0: string; + lineDashed1: string; + lineDashed2: string; + lineDashed3: string; + lineDashed4: string; + lineDashed5: string; + lineDashed6: string; + lineDashed7: string; + lineDashed8: string; + lineDashed9: string; + lineDashed10: string; + lineDashed11: string; + lineDashed12: string; + lineDashed13: string; + lineDashed14: string; + lineDashed15: string; + lineVertical: string; + lineVerticalBold: string; + lineVerticalDouble: string; + lineVerticalDashed0: string; + lineVerticalDashed1: string; + lineVerticalDashed2: string; + lineVerticalDashed3: string; + lineVerticalDashed4: string; + lineVerticalDashed5: string; + lineVerticalDashed6: string; + lineVerticalDashed7: string; + lineVerticalDashed8: string; + lineVerticalDashed9: string; + lineVerticalDashed10: string; + lineVerticalDashed11: string; + lineDownLeft: string; + lineDownLeftArc: string; + lineDownBoldLeftBold: string; + lineDownBoldLeft: string; + lineDownLeftBold: string; + lineDownDoubleLeftDouble: string; + lineDownDoubleLeft: string; + lineDownLeftDouble: string; + lineDownRight: string; + lineDownRightArc: string; + lineDownBoldRightBold: string; + lineDownBoldRight: string; + lineDownRightBold: string; + lineDownDoubleRightDouble: string; + lineDownDoubleRight: string; + lineDownRightDouble: string; + lineUpLeft: string; + lineUpLeftArc: string; + lineUpBoldLeftBold: string; + lineUpBoldLeft: string; + lineUpLeftBold: string; + lineUpDoubleLeftDouble: string; + lineUpDoubleLeft: string; + lineUpLeftDouble: string; + lineUpRight: string; + lineUpRightArc: string; + lineUpBoldRightBold: string; + lineUpBoldRight: string; + lineUpRightBold: string; + lineUpDoubleRightDouble: string; + lineUpDoubleRight: string; + lineUpRightDouble: string; + lineUpDownLeft: string; + lineUpBoldDownBoldLeftBold: string; + lineUpBoldDownBoldLeft: string; + lineUpDownLeftBold: string; + lineUpBoldDownLeftBold: string; + lineUpDownBoldLeftBold: string; + lineUpDownBoldLeft: string; + lineUpBoldDownLeft: string; + lineUpDoubleDownDoubleLeftDouble: string; + lineUpDoubleDownDoubleLeft: string; + lineUpDownLeftDouble: string; + lineUpDownRight: string; + lineUpBoldDownBoldRightBold: string; + lineUpBoldDownBoldRight: string; + lineUpDownRightBold: string; + lineUpBoldDownRightBold: string; + lineUpDownBoldRightBold: string; + lineUpDownBoldRight: string; + lineUpBoldDownRight: string; + lineUpDoubleDownDoubleRightDouble: string; + lineUpDoubleDownDoubleRight: string; + lineUpDownRightDouble: string; + lineDownLeftRight: string; + lineDownBoldLeftBoldRightBold: string; + lineDownLeftBoldRightBold: string; + lineDownBoldLeftRight: string; + lineDownBoldLeftBoldRight: string; + lineDownBoldLeftRightBold: string; + lineDownLeftRightBold: string; + lineDownLeftBoldRight: string; + lineDownDoubleLeftDoubleRightDouble: string; + lineDownDoubleLeftRight: string; + lineDownLeftDoubleRightDouble: string; + lineUpLeftRight: string; + lineUpBoldLeftBoldRightBold: string; + lineUpLeftBoldRightBold: string; + lineUpBoldLeftRight: string; + lineUpBoldLeftBoldRight: string; + lineUpBoldLeftRightBold: string; + lineUpLeftRightBold: string; + lineUpLeftBoldRight: string; + lineUpDoubleLeftDoubleRightDouble: string; + lineUpDoubleLeftRight: string; + lineUpLeftDoubleRightDouble: string; + lineUpDownLeftRight: string; + lineUpBoldDownBoldLeftBoldRightBold: string; + lineUpDownBoldLeftBoldRightBold: string; + lineUpBoldDownLeftBoldRightBold: string; + lineUpBoldDownBoldLeftRightBold: string; + lineUpBoldDownBoldLeftBoldRight: string; + lineUpBoldDownLeftRight: string; + lineUpDownBoldLeftRight: string; + lineUpDownLeftBoldRight: string; + lineUpDownLeftRightBold: string; + lineUpBoldDownBoldLeftRight: string; + lineUpDownLeftBoldRightBold: string; + lineUpBoldDownLeftBoldRight: string; + lineUpBoldDownLeftRightBold: string; + lineUpDownBoldLeftBoldRight: string; + lineUpDownBoldLeftRightBold: string; + lineUpDoubleDownDoubleLeftDoubleRightDouble: string; + lineUpDoubleDownDoubleLeftRight: string; + lineUpDownLeftDoubleRightDouble: string; + lineCross: string; + lineBackslash: string; + lineSlash: string; +}; +export declare const fallbackSymbols: Record; +declare const figures: { + tick: string; + info: string; + warning: string; + cross: string; + squareSmall: string; + squareSmallFilled: string; + circle: string; + circleFilled: string; + circleDotted: string; + circleDouble: string; + circleCircle: string; + circleCross: string; + circlePipe: string; + radioOn: string; + radioOff: string; + checkboxOn: string; + checkboxOff: string; + checkboxCircleOn: string; + checkboxCircleOff: string; + pointer: string; + triangleUpOutline: string; + triangleLeft: string; + triangleRight: string; + lozenge: string; + lozengeOutline: string; + hamburger: string; + smiley: string; + mustache: string; + star: string; + play: string; + nodejs: string; + oneSeventh: string; + oneNinth: string; + oneTenth: string; + circleQuestionMark: string; + questionMarkPrefix: string; + square: string; + squareDarkShade: string; + squareMediumShade: string; + squareLightShade: string; + squareTop: string; + squareBottom: string; + squareLeft: string; + squareRight: string; + squareCenter: string; + bullet: string; + dot: string; + ellipsis: string; + pointerSmall: string; + triangleUp: string; + triangleUpSmall: string; + triangleDown: string; + triangleDownSmall: string; + triangleLeftSmall: string; + triangleRightSmall: string; + home: string; + heart: string; + musicNote: string; + musicNoteBeamed: string; + arrowUp: string; + arrowDown: string; + arrowLeft: string; + arrowRight: string; + arrowLeftRight: string; + arrowUpDown: string; + almostEqual: string; + notEqual: string; + lessOrEqual: string; + greaterOrEqual: string; + identical: string; + infinity: string; + subscriptZero: string; + subscriptOne: string; + subscriptTwo: string; + subscriptThree: string; + subscriptFour: string; + subscriptFive: string; + subscriptSix: string; + subscriptSeven: string; + subscriptEight: string; + subscriptNine: string; + oneHalf: string; + oneThird: string; + oneQuarter: string; + oneFifth: string; + oneSixth: string; + oneEighth: string; + twoThirds: string; + twoFifths: string; + threeQuarters: string; + threeFifths: string; + threeEighths: string; + fourFifths: string; + fiveSixths: string; + fiveEighths: string; + sevenEighths: string; + line: string; + lineBold: string; + lineDouble: string; + lineDashed0: string; + lineDashed1: string; + lineDashed2: string; + lineDashed3: string; + lineDashed4: string; + lineDashed5: string; + lineDashed6: string; + lineDashed7: string; + lineDashed8: string; + lineDashed9: string; + lineDashed10: string; + lineDashed11: string; + lineDashed12: string; + lineDashed13: string; + lineDashed14: string; + lineDashed15: string; + lineVertical: string; + lineVerticalBold: string; + lineVerticalDouble: string; + lineVerticalDashed0: string; + lineVerticalDashed1: string; + lineVerticalDashed2: string; + lineVerticalDashed3: string; + lineVerticalDashed4: string; + lineVerticalDashed5: string; + lineVerticalDashed6: string; + lineVerticalDashed7: string; + lineVerticalDashed8: string; + lineVerticalDashed9: string; + lineVerticalDashed10: string; + lineVerticalDashed11: string; + lineDownLeft: string; + lineDownLeftArc: string; + lineDownBoldLeftBold: string; + lineDownBoldLeft: string; + lineDownLeftBold: string; + lineDownDoubleLeftDouble: string; + lineDownDoubleLeft: string; + lineDownLeftDouble: string; + lineDownRight: string; + lineDownRightArc: string; + lineDownBoldRightBold: string; + lineDownBoldRight: string; + lineDownRightBold: string; + lineDownDoubleRightDouble: string; + lineDownDoubleRight: string; + lineDownRightDouble: string; + lineUpLeft: string; + lineUpLeftArc: string; + lineUpBoldLeftBold: string; + lineUpBoldLeft: string; + lineUpLeftBold: string; + lineUpDoubleLeftDouble: string; + lineUpDoubleLeft: string; + lineUpLeftDouble: string; + lineUpRight: string; + lineUpRightArc: string; + lineUpBoldRightBold: string; + lineUpBoldRight: string; + lineUpRightBold: string; + lineUpDoubleRightDouble: string; + lineUpDoubleRight: string; + lineUpRightDouble: string; + lineUpDownLeft: string; + lineUpBoldDownBoldLeftBold: string; + lineUpBoldDownBoldLeft: string; + lineUpDownLeftBold: string; + lineUpBoldDownLeftBold: string; + lineUpDownBoldLeftBold: string; + lineUpDownBoldLeft: string; + lineUpBoldDownLeft: string; + lineUpDoubleDownDoubleLeftDouble: string; + lineUpDoubleDownDoubleLeft: string; + lineUpDownLeftDouble: string; + lineUpDownRight: string; + lineUpBoldDownBoldRightBold: string; + lineUpBoldDownBoldRight: string; + lineUpDownRightBold: string; + lineUpBoldDownRightBold: string; + lineUpDownBoldRightBold: string; + lineUpDownBoldRight: string; + lineUpBoldDownRight: string; + lineUpDoubleDownDoubleRightDouble: string; + lineUpDoubleDownDoubleRight: string; + lineUpDownRightDouble: string; + lineDownLeftRight: string; + lineDownBoldLeftBoldRightBold: string; + lineDownLeftBoldRightBold: string; + lineDownBoldLeftRight: string; + lineDownBoldLeftBoldRight: string; + lineDownBoldLeftRightBold: string; + lineDownLeftRightBold: string; + lineDownLeftBoldRight: string; + lineDownDoubleLeftDoubleRightDouble: string; + lineDownDoubleLeftRight: string; + lineDownLeftDoubleRightDouble: string; + lineUpLeftRight: string; + lineUpBoldLeftBoldRightBold: string; + lineUpLeftBoldRightBold: string; + lineUpBoldLeftRight: string; + lineUpBoldLeftBoldRight: string; + lineUpBoldLeftRightBold: string; + lineUpLeftRightBold: string; + lineUpLeftBoldRight: string; + lineUpDoubleLeftDoubleRightDouble: string; + lineUpDoubleLeftRight: string; + lineUpLeftDoubleRightDouble: string; + lineUpDownLeftRight: string; + lineUpBoldDownBoldLeftBoldRightBold: string; + lineUpDownBoldLeftBoldRightBold: string; + lineUpBoldDownLeftBoldRightBold: string; + lineUpBoldDownBoldLeftRightBold: string; + lineUpBoldDownBoldLeftBoldRight: string; + lineUpBoldDownLeftRight: string; + lineUpDownBoldLeftRight: string; + lineUpDownLeftBoldRight: string; + lineUpDownLeftRightBold: string; + lineUpBoldDownBoldLeftRight: string; + lineUpDownLeftBoldRightBold: string; + lineUpBoldDownLeftBoldRight: string; + lineUpBoldDownLeftRightBold: string; + lineUpDownBoldLeftBoldRight: string; + lineUpDownBoldLeftRightBold: string; + lineUpDoubleDownDoubleLeftDoubleRightDouble: string; + lineUpDoubleDownDoubleLeftRight: string; + lineUpDownLeftDoubleRightDouble: string; + lineCross: string; + lineBackslash: string; + lineSlash: string; +} | Record; +export default figures; +export declare const replaceSymbols: (string: string, { useFallback }?: { + useFallback?: boolean | undefined; +}) => string; diff --git a/node_modules/@inquirer/figures/package.json b/node_modules/@inquirer/figures/package.json new file mode 100644 index 0000000000000000000000000000000000000000..fea7df0364384040ebcabfa418eec01aa8b52791 --- /dev/null +++ b/node_modules/@inquirer/figures/package.json @@ -0,0 +1,123 @@ +{ + "_from": "@inquirer/figures@^1.0.3", + "_id": "@inquirer/figures@1.0.3", + "_inBundle": false, + "_integrity": "sha512-ErXXzENMH5pJt5/ssXV0DfWUZqly8nGzf0UcBV9xTnP+KyffE2mqyxIMBrZ8ijQck2nU0TQm40EQB53YreyWHw==", + "_location": "/@inquirer/figures", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@inquirer/figures@^1.0.3", + "name": "@inquirer/figures", + "escapedName": "@inquirer%2ffigures", + "scope": "@inquirer", + "rawSpec": "^1.0.3", + "saveSpec": null, + "fetchSpec": "^1.0.3" + }, + "_requiredBy": [ + "/@inquirer/core" + ], + "_resolved": "https://registry.npmjs.org/@inquirer/figures/-/figures-1.0.3.tgz", + "_shasum": "1227cc980f88e6d6ab85abadbf164f5038041edd", + "_spec": "@inquirer/figures@^1.0.3", + "_where": "/Users/sylvainfiloni/Documents/HuggingFace_Projects/live-vision/node_modules/@inquirer/core", + "author": { + "name": "Simon Boudrias", + "email": "admin@simonboudrias.com" + }, + "bugs": { + "url": "https://github.com/SBoudrias/Inquirer.js/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Vendored version of figures, for CJS compatibility", + "engines": { + "node": ">=18" + }, + "exports": { + ".": { + "import": { + "types": "./dist/esm/types/index.d.mts", + "default": "./dist/esm/index.mjs" + }, + "require": { + "types": "./dist/cjs/types/index.d.ts", + "default": "./dist/cjs/index.js" + } + } + }, + "files": [ + "dist/**/*" + ], + "gitHead": "209b4ce30fe71f8e2f0e066a1a98e385eecb15f4", + "homepage": "https://github.com/SBoudrias/Inquirer.js#readme", + "keywords": [ + "answer", + "answers", + "ask", + "base", + "cli", + "command", + "command-line", + "confirm", + "enquirer", + "generate", + "generator", + "hyper", + "input", + "inquire", + "inquirer", + "interface", + "iterm", + "javascript", + "menu", + "node", + "nodejs", + "prompt", + "promptly", + "prompts", + "question", + "readline", + "scaffold", + "scaffolder", + "scaffolding", + "stdin", + "stdout", + "terminal", + "tty", + "ui", + "yeoman", + "yo", + "zsh", + "types", + "typescript" + ], + "license": "MIT", + "main": "./dist/cjs/index.js", + "name": "@inquirer/figures", + "repository": { + "type": "git", + "url": "git+https://github.com/SBoudrias/Inquirer.js.git" + }, + "scripts": { + "attw": "attw --pack", + "dev": "tsc -p ./tsconfig.json --watch", + "tsc": "yarn run tsc:esm && yarn run tsc:cjs", + "tsc:cjs": "rm -rf dist/cjs && tsc -p ./tsconfig.cjs.json && node ../../tools/fix-ext.mjs", + "tsc:esm": "rm -rf dist/esm && tsc -p ./tsconfig.json" + }, + "sideEffects": false, + "typings": "./dist/cjs/types/index.d.ts", + "version": "1.0.3", + "warnings": [ + { + "code": "ENOTSUP", + "required": { + "node": ">=18" + }, + "pkgid": "@inquirer/figures@1.0.3" + } + ] +} diff --git a/node_modules/@inquirer/type/LICENSE b/node_modules/@inquirer/type/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..6a10a8efe516e142e0f1cd556830460b2cc89d02 --- /dev/null +++ b/node_modules/@inquirer/type/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2023 Simon Boudrias + +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/node_modules/@inquirer/type/dist/cjs/index.js b/node_modules/@inquirer/type/dist/cjs/index.js new file mode 100644 index 0000000000000000000000000000000000000000..7fd193d7f33cea24b06162229d4410929bc04973 --- /dev/null +++ b/node_modules/@inquirer/type/dist/cjs/index.js @@ -0,0 +1,15 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CancelablePromise = void 0; +class CancelablePromise extends Promise { + constructor() { + super(...arguments); + Object.defineProperty(this, "cancel", { + enumerable: true, + configurable: true, + writable: true, + value: () => { } + }); + } +} +exports.CancelablePromise = CancelablePromise; diff --git a/node_modules/@inquirer/type/dist/cjs/types/index.d.ts b/node_modules/@inquirer/type/dist/cjs/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..90399cbd2a8761708f9465d80d7f8ca7d437f8ef --- /dev/null +++ b/node_modules/@inquirer/type/dist/cjs/types/index.d.ts @@ -0,0 +1,34 @@ +/// +export declare class CancelablePromise extends Promise { + cancel: () => void; +} +export type Prettify = { + [K in keyof T]: T[K]; +} & {}; +export type PartialDeep = T extends object ? { + [P in keyof T]?: PartialDeep; +} : T; +export type Context = { + input?: NodeJS.ReadableStream; + output?: NodeJS.WritableStream; + clearPromptOnDone?: boolean; +}; +export type Prompt = (config: Config, context?: Context) => CancelablePromise; +/** + * Utility types used for writing tests + * + * Equal checks that A and B are the same type, and returns + * either `true` or `false`. + * + * You can use it in combination with `Expect` to write type + * inference unit tests: + * + * ```ts + * type t = Expect< + * Equal, { a?: string }> + * > + * ``` + */ +export type Equal = (() => T extends X ? 1 : 2) extends () => T extends Y ? 1 : 2 ? true : false; +export type Expect = T; +export type Not = T extends true ? false : true; diff --git a/node_modules/@inquirer/type/dist/esm/index.mjs b/node_modules/@inquirer/type/dist/esm/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7f995d8ac65bb6d04124e50fc39b1b66c90c0fe1 --- /dev/null +++ b/node_modules/@inquirer/type/dist/esm/index.mjs @@ -0,0 +1,3 @@ +export class CancelablePromise extends Promise { + cancel = () => { }; +} diff --git a/node_modules/@inquirer/type/dist/esm/types/index.d.mts b/node_modules/@inquirer/type/dist/esm/types/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..5c3df6871c0bc2b2c4de59357fe13422d4da9499 --- /dev/null +++ b/node_modules/@inquirer/type/dist/esm/types/index.d.mts @@ -0,0 +1,34 @@ +/// +export declare class CancelablePromise extends Promise { + cancel: () => void; +} +export type Prettify = { + [K in keyof T]: T[K]; +} & {}; +export type PartialDeep = T extends object ? { + [P in keyof T]?: PartialDeep; +} : T; +export type Context = { + input?: NodeJS.ReadableStream; + output?: NodeJS.WritableStream; + clearPromptOnDone?: boolean; +}; +export type Prompt = (config: Config, context?: Context) => CancelablePromise; +/** + * Utility types used for writing tests + * + * Equal checks that A and B are the same type, and returns + * either `true` or `false`. + * + * You can use it in combination with `Expect` to write type + * inference unit tests: + * + * ```ts + * type t = Expect< + * Equal, { a?: string }> + * > + * ``` + */ +export type Equal = (() => T extends X ? 1 : 2) extends () => T extends Y ? 1 : 2 ? true : false; +export type Expect = T; +export type Not = T extends true ? false : true; diff --git a/node_modules/@inquirer/type/package.json b/node_modules/@inquirer/type/package.json new file mode 100644 index 0000000000000000000000000000000000000000..752979b34f88ce60f7ec8b9c2809d6a2d74f53e4 --- /dev/null +++ b/node_modules/@inquirer/type/package.json @@ -0,0 +1,124 @@ +{ + "_from": "@inquirer/type@^1.3.3", + "_id": "@inquirer/type@1.3.3", + "_inBundle": false, + "_integrity": "sha512-xTUt0NulylX27/zMx04ZYar/kr1raaiFTVvQ5feljQsiAgdm0WPj4S73/ye0fbslh+15QrIuDvfCXTek7pMY5A==", + "_location": "/@inquirer/type", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@inquirer/type@^1.3.3", + "name": "@inquirer/type", + "escapedName": "@inquirer%2ftype", + "scope": "@inquirer", + "rawSpec": "^1.3.3", + "saveSpec": null, + "fetchSpec": "^1.3.3" + }, + "_requiredBy": [ + "/@inquirer/confirm", + "/@inquirer/core" + ], + "_resolved": "https://registry.npmjs.org/@inquirer/type/-/type-1.3.3.tgz", + "_shasum": "26b2628630fd2381c7fa1e3ab396feb9bbc575da", + "_spec": "@inquirer/type@^1.3.3", + "_where": "/Users/sylvainfiloni/Documents/HuggingFace_Projects/live-vision/node_modules/@inquirer/confirm", + "author": { + "name": "Simon Boudrias", + "email": "admin@simonboudrias.com" + }, + "bugs": { + "url": "https://github.com/SBoudrias/Inquirer.js/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Inquirer core TS types", + "engines": { + "node": ">=18" + }, + "exports": { + ".": { + "import": { + "types": "./dist/esm/types/index.d.mts", + "default": "./dist/esm/index.mjs" + }, + "require": { + "types": "./dist/cjs/types/index.d.ts", + "default": "./dist/cjs/index.js" + } + } + }, + "files": [ + "dist/**/*" + ], + "gitHead": "209b4ce30fe71f8e2f0e066a1a98e385eecb15f4", + "homepage": "https://github.com/SBoudrias/Inquirer.js#readme", + "keywords": [ + "answer", + "answers", + "ask", + "base", + "cli", + "command", + "command-line", + "confirm", + "enquirer", + "generate", + "generator", + "hyper", + "input", + "inquire", + "inquirer", + "interface", + "iterm", + "javascript", + "menu", + "node", + "nodejs", + "prompt", + "promptly", + "prompts", + "question", + "readline", + "scaffold", + "scaffolder", + "scaffolding", + "stdin", + "stdout", + "terminal", + "tty", + "ui", + "yeoman", + "yo", + "zsh", + "types", + "typescript" + ], + "license": "MIT", + "main": "./dist/cjs/index.js", + "name": "@inquirer/type", + "repository": { + "type": "git", + "url": "git+https://github.com/SBoudrias/Inquirer.js.git" + }, + "scripts": { + "attw": "attw --pack", + "dev": "tsc -p ./tsconfig.json --watch", + "tsc": "yarn run tsc:esm && yarn run tsc:cjs", + "tsc:cjs": "rm -rf dist/cjs && tsc -p ./tsconfig.cjs.json && node ../../tools/fix-ext.mjs", + "tsc:esm": "rm -rf dist/esm && tsc -p ./tsconfig.json" + }, + "sideEffects": false, + "typings": "./dist/cjs/types/index.d.ts", + "version": "1.3.3", + "warnings": [ + { + "code": "ENOTSUP", + "required": { + "node": ">=18" + }, + "pkgid": "@inquirer/type@1.3.3" + } + ] +} diff --git a/node_modules/@mswjs/cookies/LICENSE.md b/node_modules/@mswjs/cookies/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..74a03adddf4b428d9b79c16e787ea16e924f9baa --- /dev/null +++ b/node_modules/@mswjs/cookies/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020-present Artem Zakharchenko + +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/node_modules/@mswjs/cookies/README.md b/node_modules/@mswjs/cookies/README.md new file mode 100644 index 0000000000000000000000000000000000000000..36b2feabe7c697efc45538c8f7040be65f6d0348 --- /dev/null +++ b/node_modules/@mswjs/cookies/README.md @@ -0,0 +1,80 @@ +[![Latest version](https://img.shields.io/npm/v/@mswjs/cookies.svg)](https://www.npmjs.com/package/@mswjs/cookies) + +# Cookies + +Manage request/response cookies in the environments where those are not supported. + +## Install + +```bash +npm install @mswjs/cookies +``` + +## API + +### `set(request: Request, response: Response)` + +Sets the response cookies in the store associated with the given request origin. + +```js +store.set( + new Request('https://mswjs.io'), + new Response(null, { + headers: new Headers({ + 'set-cookie': 'id=abc-123', + }), + }), +) +``` + +### `get(request: Request)` + +Retrieves the cookies relevant to the given request's origin. + +```js +store.get(new Request('https://mswjs.io')) +``` + +> `.get()` respects the `req.credentials` policy. + +Executing this command returns a `Map` instance with the request cookies: + +```js +Map { + "id" => { name: "id", value: "abc-123" } +} +``` + +### `getAll()` + +Returns all the cookies in the store. + +Executing `.getAll()` method returns a `Map` instance with request cookies grouped by request origin. + +```js +Map { + "https://mswjs.io" => Map { + "id" => { name: "id", value: "abc-123" } + } +} +``` + +### `deleteAll(request: Request)` + +Removes all the cookies associated with the given request's origin. + +### `persist()` + +Persists the current store state in the `localStorage`. + +### `hydrate()` + +Hydrates the store values from the previously persisted state in `localStorage`. + +### `clear()` + +Removes all the cookies from the store, producing a nice and shiny empty store. + +## Credits + +Original idea by [Christoph Guttandin](https://github.com/chrisguttandin). diff --git a/node_modules/@mswjs/cookies/lib/index.d.ts b/node_modules/@mswjs/cookies/lib/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..19a5f0301609acae8b380356a7e54ae6e49c7d18 --- /dev/null +++ b/node_modules/@mswjs/cookies/lib/index.d.ts @@ -0,0 +1,57 @@ +import { Cookie } from 'set-cookie-parser'; + +interface RequestLike { + credentials: Request['credentials']; + url: string; +} +interface HeadersLike { + get(name: string): string | null; +} +interface ResponseLike { + headers: HeadersLike; +} +type Store = Map; +type StoreEntry = Map; +type CookieString = Omit & { + expires?: string; +}; +declare const PERSISTENCY_KEY = "MSW_COOKIE_STORE"; +declare class CookieStore { + private store; + constructor(); + /** + * Sets the given request cookies into the store. + * Respects the `request.credentials` policy. + */ + add(request: RequestLike, response: ResponseLike): void; + /** + * Returns cookies relevant to the given request + * and its `request.credentials` policy. + */ + get(request: RequestLike): StoreEntry; + /** + * Returns a collection of all stored cookies. + */ + getAll(): Store; + /** + * Deletes all cookies associated with the given request. + */ + deleteAll(request: RequestLike): void; + /** + * Clears the entire cookie store. + */ + clear(): void; + /** + * Hydrates the virtual cookie store from the `localStorage` if defined. + */ + hydrate(): void; + /** + * Persists the current virtual cookies into the `localStorage` if defined, + * so they are available on the next page load. + */ + persist(): void; + private deleteExpiredCookies; +} +declare const store: CookieStore; + +export { CookieString, PERSISTENCY_KEY, Store, StoreEntry, store }; diff --git a/node_modules/@mswjs/cookies/lib/index.js b/node_modules/@mswjs/cookies/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..7d5e3547bf65a98a21eade01f7fa06d3c0ee03fc --- /dev/null +++ b/node_modules/@mswjs/cookies/lib/index.js @@ -0,0 +1,344 @@ +"use strict";Object.defineProperty(exports, "__esModule", {value: true});var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); + +// node_modules/set-cookie-parser/lib/set-cookie.js +var require_set_cookie = __commonJS({ + "node_modules/set-cookie-parser/lib/set-cookie.js"(exports, module) { + "use strict"; + var defaultParseOptions = { + decodeValues: true, + map: false, + silent: false + }; + function isNonEmptyString(str) { + return typeof str === "string" && !!str.trim(); + } + function parseString(setCookieValue, options) { + var parts = setCookieValue.split(";").filter(isNonEmptyString); + var nameValuePairStr = parts.shift(); + var parsed = parseNameValuePair(nameValuePairStr); + var name = parsed.name; + var value = parsed.value; + options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions; + try { + value = options.decodeValues ? decodeURIComponent(value) : value; + } catch (e) { + console.error( + "set-cookie-parser encountered an error while decoding a cookie with value '" + value + "'. Set options.decodeValues to false to disable this feature.", + e + ); + } + var cookie = { + name, + value + }; + parts.forEach(function(part) { + var sides = part.split("="); + var key = sides.shift().trimLeft().toLowerCase(); + var value2 = sides.join("="); + if (key === "expires") { + cookie.expires = new Date(value2); + } else if (key === "max-age") { + cookie.maxAge = parseInt(value2, 10); + } else if (key === "secure") { + cookie.secure = true; + } else if (key === "httponly") { + cookie.httpOnly = true; + } else if (key === "samesite") { + cookie.sameSite = value2; + } else { + cookie[key] = value2; + } + }); + return cookie; + } + function parseNameValuePair(nameValuePairStr) { + var name = ""; + var value = ""; + var nameValueArr = nameValuePairStr.split("="); + if (nameValueArr.length > 1) { + name = nameValueArr.shift(); + value = nameValueArr.join("="); + } else { + value = nameValuePairStr; + } + return { name, value }; + } + function parse(input, options) { + options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions; + if (!input) { + if (!options.map) { + return []; + } else { + return {}; + } + } + if (input.headers) { + if (typeof input.headers.getSetCookie === "function") { + input = input.headers.getSetCookie(); + } else if (input.headers["set-cookie"]) { + input = input.headers["set-cookie"]; + } else { + var sch = input.headers[Object.keys(input.headers).find(function(key) { + return key.toLowerCase() === "set-cookie"; + })]; + if (!sch && input.headers.cookie && !options.silent) { + console.warn( + "Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning." + ); + } + input = sch; + } + } + if (!Array.isArray(input)) { + input = [input]; + } + options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions; + if (!options.map) { + return input.filter(isNonEmptyString).map(function(str) { + return parseString(str, options); + }); + } else { + var cookies = {}; + return input.filter(isNonEmptyString).reduce(function(cookies2, str) { + var cookie = parseString(str, options); + cookies2[cookie.name] = cookie; + return cookies2; + }, cookies); + } + } + function splitCookiesString(cookiesString) { + if (Array.isArray(cookiesString)) { + return cookiesString; + } + if (typeof cookiesString !== "string") { + return []; + } + var cookiesStrings = []; + var pos = 0; + var start; + var ch; + var lastComma; + var nextStart; + var cookiesSeparatorFound; + function skipWhitespace() { + while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) { + pos += 1; + } + return pos < cookiesString.length; + } + function notSpecialChar() { + ch = cookiesString.charAt(pos); + return ch !== "=" && ch !== ";" && ch !== ","; + } + while (pos < cookiesString.length) { + start = pos; + cookiesSeparatorFound = false; + while (skipWhitespace()) { + ch = cookiesString.charAt(pos); + if (ch === ",") { + lastComma = pos; + pos += 1; + skipWhitespace(); + nextStart = pos; + while (pos < cookiesString.length && notSpecialChar()) { + pos += 1; + } + if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") { + cookiesSeparatorFound = true; + pos = nextStart; + cookiesStrings.push(cookiesString.substring(start, lastComma)); + start = pos; + } else { + pos = lastComma + 1; + } + } else { + pos += 1; + } + } + if (!cookiesSeparatorFound || pos >= cookiesString.length) { + cookiesStrings.push(cookiesString.substring(start, cookiesString.length)); + } + } + return cookiesStrings; + } + module.exports = parse; + module.exports.parse = parse; + module.exports.parseString = parseString; + module.exports.splitCookiesString = splitCookiesString; + } +}); + +// src/store.ts +var import_set_cookie_parser = __toESM(require_set_cookie()); +var PERSISTENCY_KEY = "MSW_COOKIE_STORE"; +function supportsLocalStorage() { + try { + if (localStorage == null) { + return false; + } + const testKey = PERSISTENCY_KEY + "_test"; + localStorage.setItem(testKey, "test"); + localStorage.getItem(testKey); + localStorage.removeItem(testKey); + return true; + } catch (error) { + return false; + } +} +var hasLocalStorageSupport = supportsLocalStorage(); +function isPropertyAccessible(object, method) { + try { + object[method]; + return true; + } catch (e2) { + return false; + } +} +var CookieStore = class { + constructor() { + this.store = /* @__PURE__ */ new Map(); + } + add(request, response) { + if (isPropertyAccessible(request, "credentials") && request.credentials === "omit") { + return; + } + const requestUrl = new URL(request.url); + const responseCookies = response.headers.get("set-cookie"); + if (!responseCookies) { + return; + } + const now = Date.now(); + const parsedResponseCookies = (0, import_set_cookie_parser.parse)(responseCookies).map( + ({ maxAge, ...cookie }) => ({ + ...cookie, + expires: maxAge === void 0 ? cookie.expires : new Date(now + maxAge * 1e3), + maxAge + }) + ); + const prevCookies = this.store.get(requestUrl.origin) || /* @__PURE__ */ new Map(); + parsedResponseCookies.forEach((cookie) => { + this.store.set(requestUrl.origin, prevCookies.set(cookie.name, cookie)); + }); + } + get(request) { + this.deleteExpiredCookies(); + const requestUrl = new URL(request.url); + const originCookies = this.store.get(requestUrl.origin) || /* @__PURE__ */ new Map(); + if (!isPropertyAccessible(request, "credentials")) { + return originCookies; + } + switch (request.credentials) { + case "include": { + if (typeof document === "undefined") { + return originCookies; + } + const documentCookies = (0, import_set_cookie_parser.parse)(document.cookie); + documentCookies.forEach((cookie) => { + originCookies.set(cookie.name, cookie); + }); + return originCookies; + } + case "same-origin": { + return originCookies; + } + default: + return /* @__PURE__ */ new Map(); + } + } + getAll() { + this.deleteExpiredCookies(); + return this.store; + } + deleteAll(request) { + const requestUrl = new URL(request.url); + this.store.delete(requestUrl.origin); + } + clear() { + this.store.clear(); + } + hydrate() { + if (!hasLocalStorageSupport) { + return; + } + const persistedCookies = localStorage.getItem(PERSISTENCY_KEY); + if (!persistedCookies) { + return; + } + try { + const parsedCookies = JSON.parse(persistedCookies); + parsedCookies.forEach(([origin, cookies]) => { + this.store.set( + origin, + new Map( + cookies.map(([token, { expires, ...cookie }]) => [ + token, + expires === void 0 ? cookie : { ...cookie, expires: new Date(expires) } + ]) + ) + ); + }); + } catch (error) { + console.warn(` +[virtual-cookie] Failed to parse a stored cookie from the localStorage (key "${PERSISTENCY_KEY}"). + +Stored value: +${localStorage.getItem(PERSISTENCY_KEY)} + +Thrown exception: +${error} + +Invalid value has been removed from localStorage to prevent subsequent failed parsing attempts.`); + localStorage.removeItem(PERSISTENCY_KEY); + } + } + persist() { + if (!hasLocalStorageSupport) { + return; + } + const serializedCookies = Array.from(this.store.entries()).map( + ([origin, cookies]) => { + return [origin, Array.from(cookies.entries())]; + } + ); + localStorage.setItem(PERSISTENCY_KEY, JSON.stringify(serializedCookies)); + } + deleteExpiredCookies() { + const now = Date.now(); + this.store.forEach((originCookies, origin) => { + originCookies.forEach(({ expires, name }) => { + if (expires !== void 0 && expires.getTime() <= now) { + originCookies.delete(name); + } + }); + if (originCookies.size === 0) { + this.store.delete(origin); + } + }); + } +}; +var store = new CookieStore(); + + + +exports.PERSISTENCY_KEY = PERSISTENCY_KEY; exports.store = store; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@mswjs/cookies/lib/index.js.map b/node_modules/@mswjs/cookies/lib/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..53b5adc580f24a76873395db51a81440bcc307ae --- /dev/null +++ b/node_modules/@mswjs/cookies/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../node_modules/set-cookie-parser/lib/set-cookie.js","../src/store.ts"],"names":["value","cookies","parseCookie"],"mappings":"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","sourcesContent":["\"use strict\";\n\nvar defaultParseOptions = {\n decodeValues: true,\n map: false,\n silent: false,\n};\n\nfunction isNonEmptyString(str) {\n return typeof str === \"string\" && !!str.trim();\n}\n\nfunction parseString(setCookieValue, options) {\n var parts = setCookieValue.split(\";\").filter(isNonEmptyString);\n\n var nameValuePairStr = parts.shift();\n var parsed = parseNameValuePair(nameValuePairStr);\n var name = parsed.name;\n var value = parsed.value;\n\n options = options\n ? Object.assign({}, defaultParseOptions, options)\n : defaultParseOptions;\n\n try {\n value = options.decodeValues ? decodeURIComponent(value) : value; // decode cookie value\n } catch (e) {\n console.error(\n \"set-cookie-parser encountered an error while decoding a cookie with value '\" +\n value +\n \"'. Set options.decodeValues to false to disable this feature.\",\n e\n );\n }\n\n var cookie = {\n name: name,\n value: value,\n };\n\n parts.forEach(function (part) {\n var sides = part.split(\"=\");\n var key = sides.shift().trimLeft().toLowerCase();\n var value = sides.join(\"=\");\n if (key === \"expires\") {\n cookie.expires = new Date(value);\n } else if (key === \"max-age\") {\n cookie.maxAge = parseInt(value, 10);\n } else if (key === \"secure\") {\n cookie.secure = true;\n } else if (key === \"httponly\") {\n cookie.httpOnly = true;\n } else if (key === \"samesite\") {\n cookie.sameSite = value;\n } else {\n cookie[key] = value;\n }\n });\n\n return cookie;\n}\n\nfunction parseNameValuePair(nameValuePairStr) {\n // Parses name-value-pair according to rfc6265bis draft\n\n var name = \"\";\n var value = \"\";\n var nameValueArr = nameValuePairStr.split(\"=\");\n if (nameValueArr.length > 1) {\n name = nameValueArr.shift();\n value = nameValueArr.join(\"=\"); // everything after the first =, joined by a \"=\" if there was more than one part\n } else {\n value = nameValuePairStr;\n }\n\n return { name: name, value: value };\n}\n\nfunction parse(input, options) {\n options = options\n ? Object.assign({}, defaultParseOptions, options)\n : defaultParseOptions;\n\n if (!input) {\n if (!options.map) {\n return [];\n } else {\n return {};\n }\n }\n\n if (input.headers) {\n if (typeof input.headers.getSetCookie === \"function\") {\n // for fetch responses - they combine headers of the same type in the headers array,\n // but getSetCookie returns an uncombined array\n input = input.headers.getSetCookie();\n } else if (input.headers[\"set-cookie\"]) {\n // fast-path for node.js (which automatically normalizes header names to lower-case\n input = input.headers[\"set-cookie\"];\n } else {\n // slow-path for other environments - see #25\n var sch =\n input.headers[\n Object.keys(input.headers).find(function (key) {\n return key.toLowerCase() === \"set-cookie\";\n })\n ];\n // warn if called on a request-like object with a cookie header rather than a set-cookie header - see #34, 36\n if (!sch && input.headers.cookie && !options.silent) {\n console.warn(\n \"Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning.\"\n );\n }\n input = sch;\n }\n }\n if (!Array.isArray(input)) {\n input = [input];\n }\n\n options = options\n ? Object.assign({}, defaultParseOptions, options)\n : defaultParseOptions;\n\n if (!options.map) {\n return input.filter(isNonEmptyString).map(function (str) {\n return parseString(str, options);\n });\n } else {\n var cookies = {};\n return input.filter(isNonEmptyString).reduce(function (cookies, str) {\n var cookie = parseString(str, options);\n cookies[cookie.name] = cookie;\n return cookies;\n }, cookies);\n }\n}\n\n/*\n Set-Cookie header field-values are sometimes comma joined in one string. This splits them without choking on commas\n that are within a single set-cookie field-value, such as in the Expires portion.\n\n This is uncommon, but explicitly allowed - see https://tools.ietf.org/html/rfc2616#section-4.2\n Node.js does this for every header *except* set-cookie - see https://github.com/nodejs/node/blob/d5e363b77ebaf1caf67cd7528224b651c86815c1/lib/_http_incoming.js#L128\n React Native's fetch does this for *every* header, including set-cookie.\n\n Based on: https://github.com/google/j2objc/commit/16820fdbc8f76ca0c33472810ce0cb03d20efe25\n Credits to: https://github.com/tomball for original and https://github.com/chrusart for JavaScript implementation\n*/\nfunction splitCookiesString(cookiesString) {\n if (Array.isArray(cookiesString)) {\n return cookiesString;\n }\n if (typeof cookiesString !== \"string\") {\n return [];\n }\n\n var cookiesStrings = [];\n var pos = 0;\n var start;\n var ch;\n var lastComma;\n var nextStart;\n var cookiesSeparatorFound;\n\n function skipWhitespace() {\n while (pos < cookiesString.length && /\\s/.test(cookiesString.charAt(pos))) {\n pos += 1;\n }\n return pos < cookiesString.length;\n }\n\n function notSpecialChar() {\n ch = cookiesString.charAt(pos);\n\n return ch !== \"=\" && ch !== \";\" && ch !== \",\";\n }\n\n while (pos < cookiesString.length) {\n start = pos;\n cookiesSeparatorFound = false;\n\n while (skipWhitespace()) {\n ch = cookiesString.charAt(pos);\n if (ch === \",\") {\n // ',' is a cookie separator if we have later first '=', not ';' or ','\n lastComma = pos;\n pos += 1;\n\n skipWhitespace();\n nextStart = pos;\n\n while (pos < cookiesString.length && notSpecialChar()) {\n pos += 1;\n }\n\n // currently special character\n if (pos < cookiesString.length && cookiesString.charAt(pos) === \"=\") {\n // we found cookies separator\n cookiesSeparatorFound = true;\n // pos is inside the next cookie, so back up and return it.\n pos = nextStart;\n cookiesStrings.push(cookiesString.substring(start, lastComma));\n start = pos;\n } else {\n // in param ',' or param separator ';',\n // we continue from that comma\n pos = lastComma + 1;\n }\n } else {\n pos += 1;\n }\n }\n\n if (!cookiesSeparatorFound || pos >= cookiesString.length) {\n cookiesStrings.push(cookiesString.substring(start, cookiesString.length));\n }\n }\n\n return cookiesStrings;\n}\n\nmodule.exports = parse;\nmodule.exports.parse = parse;\nmodule.exports.parseString = parseString;\nmodule.exports.splitCookiesString = splitCookiesString;\n","import { Cookie, parse as parseCookie } from 'set-cookie-parser'\n\ninterface RequestLike {\n credentials: Request['credentials']\n url: string\n}\n\ninterface HeadersLike {\n get(name: string): string | null\n}\n\ninterface ResponseLike {\n headers: HeadersLike\n}\n\nexport type Store = Map\nexport type StoreEntry = Map\nexport type CookieString = Omit & { expires?: string }\n\nexport const PERSISTENCY_KEY = 'MSW_COOKIE_STORE'\n\nfunction supportsLocalStorage() {\n try {\n if (localStorage == null) {\n return false\n }\n\n const testKey = PERSISTENCY_KEY + '_test'\n\n localStorage.setItem(testKey, 'test')\n localStorage.getItem(testKey)\n localStorage.removeItem(testKey)\n\n return true\n } catch (error) {\n return false\n }\n}\n\nconst hasLocalStorageSupport = supportsLocalStorage()\n\n/**\n * Checks that accessing a given property on an object\n * by name does not throw an error.\n *\n * This is generally used to avoid issues in environments\n * like `miniflare` where some properties are defined as getters\n * where accessing that property throws directly.\n */\nfunction isPropertyAccessible>(\n object: Obj,\n method: keyof Obj,\n) {\n try {\n object[method]\n return true\n } catch {\n return false\n }\n}\n\nclass CookieStore {\n private store: Store\n\n constructor() {\n this.store = new Map()\n }\n\n /**\n * Sets the given request cookies into the store.\n * Respects the `request.credentials` policy.\n */\n add(request: RequestLike, response: ResponseLike): void {\n if (\n isPropertyAccessible(request, 'credentials') &&\n request.credentials === 'omit'\n ) {\n return\n }\n\n const requestUrl = new URL(request.url)\n const responseCookies = response.headers.get('set-cookie')\n\n if (!responseCookies) {\n return\n }\n\n const now = Date.now()\n const parsedResponseCookies = parseCookie(responseCookies).map(\n ({ maxAge, ...cookie }) => ({\n ...cookie,\n expires:\n maxAge === undefined ? cookie.expires : new Date(now + maxAge * 1000),\n maxAge,\n }),\n )\n\n const prevCookies =\n this.store.get(requestUrl.origin) || new Map()\n\n parsedResponseCookies.forEach((cookie) => {\n this.store.set(requestUrl.origin, prevCookies.set(cookie.name, cookie))\n })\n }\n\n /**\n * Returns cookies relevant to the given request\n * and its `request.credentials` policy.\n */\n get(request: RequestLike): StoreEntry {\n this.deleteExpiredCookies()\n\n const requestUrl = new URL(request.url)\n const originCookies =\n this.store.get(requestUrl.origin) || new Map()\n\n if (!isPropertyAccessible(request, 'credentials')) {\n return originCookies\n }\n\n switch (request.credentials) {\n case 'include': {\n // Support running this method in Node.js.\n if (typeof document === 'undefined') {\n return originCookies\n }\n\n const documentCookies = parseCookie(document.cookie)\n\n documentCookies.forEach((cookie) => {\n originCookies.set(cookie.name, cookie)\n })\n\n return originCookies\n }\n\n case 'same-origin': {\n return originCookies\n }\n\n default:\n return new Map()\n }\n }\n\n /**\n * Returns a collection of all stored cookies.\n */\n getAll(): Store {\n this.deleteExpiredCookies()\n return this.store\n }\n\n /**\n * Deletes all cookies associated with the given request.\n */\n deleteAll(request: RequestLike): void {\n const requestUrl = new URL(request.url)\n this.store.delete(requestUrl.origin)\n }\n\n /**\n * Clears the entire cookie store.\n */\n clear(): void {\n this.store.clear()\n }\n\n /**\n * Hydrates the virtual cookie store from the `localStorage` if defined.\n */\n hydrate(): void {\n if (!hasLocalStorageSupport) {\n return\n }\n\n const persistedCookies = localStorage.getItem(PERSISTENCY_KEY)\n\n if (!persistedCookies) {\n return\n }\n\n try {\n const parsedCookies: [string, [string, CookieString][]][] =\n JSON.parse(persistedCookies)\n\n parsedCookies.forEach(([origin, cookies]) => {\n this.store.set(\n origin,\n new Map(\n cookies.map(([token, { expires, ...cookie }]) => [\n token,\n expires === undefined\n ? cookie\n : { ...cookie, expires: new Date(expires) },\n ]),\n ),\n )\n })\n } catch (error) {\n console.warn(`\n[virtual-cookie] Failed to parse a stored cookie from the localStorage (key \"${PERSISTENCY_KEY}\").\n\nStored value:\n${localStorage.getItem(PERSISTENCY_KEY)}\n\nThrown exception:\n${error}\n\nInvalid value has been removed from localStorage to prevent subsequent failed parsing attempts.`)\n localStorage.removeItem(PERSISTENCY_KEY)\n }\n }\n\n /**\n * Persists the current virtual cookies into the `localStorage` if defined,\n * so they are available on the next page load.\n */\n persist(): void {\n if (!hasLocalStorageSupport) {\n return\n }\n\n const serializedCookies = Array.from(this.store.entries()).map(\n ([origin, cookies]) => {\n return [origin, Array.from(cookies.entries())]\n },\n )\n\n localStorage.setItem(PERSISTENCY_KEY, JSON.stringify(serializedCookies))\n }\n\n private deleteExpiredCookies() {\n const now = Date.now()\n\n this.store.forEach((originCookies, origin) => {\n originCookies.forEach(({ expires, name }) => {\n if (expires !== undefined && expires.getTime() <= now) {\n originCookies.delete(name)\n }\n })\n\n if (originCookies.size === 0) {\n this.store.delete(origin)\n }\n })\n }\n}\n\nexport const store = new CookieStore()\n"]} \ No newline at end of file diff --git a/node_modules/@mswjs/cookies/lib/index.mjs b/node_modules/@mswjs/cookies/lib/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0ff101bc653f11a39605be6bbc5282998c1929d5 --- /dev/null +++ b/node_modules/@mswjs/cookies/lib/index.mjs @@ -0,0 +1,344 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); + +// node_modules/set-cookie-parser/lib/set-cookie.js +var require_set_cookie = __commonJS({ + "node_modules/set-cookie-parser/lib/set-cookie.js"(exports, module) { + "use strict"; + var defaultParseOptions = { + decodeValues: true, + map: false, + silent: false + }; + function isNonEmptyString(str) { + return typeof str === "string" && !!str.trim(); + } + function parseString(setCookieValue, options) { + var parts = setCookieValue.split(";").filter(isNonEmptyString); + var nameValuePairStr = parts.shift(); + var parsed = parseNameValuePair(nameValuePairStr); + var name = parsed.name; + var value = parsed.value; + options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions; + try { + value = options.decodeValues ? decodeURIComponent(value) : value; + } catch (e) { + console.error( + "set-cookie-parser encountered an error while decoding a cookie with value '" + value + "'. Set options.decodeValues to false to disable this feature.", + e + ); + } + var cookie = { + name, + value + }; + parts.forEach(function(part) { + var sides = part.split("="); + var key = sides.shift().trimLeft().toLowerCase(); + var value2 = sides.join("="); + if (key === "expires") { + cookie.expires = new Date(value2); + } else if (key === "max-age") { + cookie.maxAge = parseInt(value2, 10); + } else if (key === "secure") { + cookie.secure = true; + } else if (key === "httponly") { + cookie.httpOnly = true; + } else if (key === "samesite") { + cookie.sameSite = value2; + } else { + cookie[key] = value2; + } + }); + return cookie; + } + function parseNameValuePair(nameValuePairStr) { + var name = ""; + var value = ""; + var nameValueArr = nameValuePairStr.split("="); + if (nameValueArr.length > 1) { + name = nameValueArr.shift(); + value = nameValueArr.join("="); + } else { + value = nameValuePairStr; + } + return { name, value }; + } + function parse(input, options) { + options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions; + if (!input) { + if (!options.map) { + return []; + } else { + return {}; + } + } + if (input.headers) { + if (typeof input.headers.getSetCookie === "function") { + input = input.headers.getSetCookie(); + } else if (input.headers["set-cookie"]) { + input = input.headers["set-cookie"]; + } else { + var sch = input.headers[Object.keys(input.headers).find(function(key) { + return key.toLowerCase() === "set-cookie"; + })]; + if (!sch && input.headers.cookie && !options.silent) { + console.warn( + "Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning." + ); + } + input = sch; + } + } + if (!Array.isArray(input)) { + input = [input]; + } + options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions; + if (!options.map) { + return input.filter(isNonEmptyString).map(function(str) { + return parseString(str, options); + }); + } else { + var cookies = {}; + return input.filter(isNonEmptyString).reduce(function(cookies2, str) { + var cookie = parseString(str, options); + cookies2[cookie.name] = cookie; + return cookies2; + }, cookies); + } + } + function splitCookiesString(cookiesString) { + if (Array.isArray(cookiesString)) { + return cookiesString; + } + if (typeof cookiesString !== "string") { + return []; + } + var cookiesStrings = []; + var pos = 0; + var start; + var ch; + var lastComma; + var nextStart; + var cookiesSeparatorFound; + function skipWhitespace() { + while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) { + pos += 1; + } + return pos < cookiesString.length; + } + function notSpecialChar() { + ch = cookiesString.charAt(pos); + return ch !== "=" && ch !== ";" && ch !== ","; + } + while (pos < cookiesString.length) { + start = pos; + cookiesSeparatorFound = false; + while (skipWhitespace()) { + ch = cookiesString.charAt(pos); + if (ch === ",") { + lastComma = pos; + pos += 1; + skipWhitespace(); + nextStart = pos; + while (pos < cookiesString.length && notSpecialChar()) { + pos += 1; + } + if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") { + cookiesSeparatorFound = true; + pos = nextStart; + cookiesStrings.push(cookiesString.substring(start, lastComma)); + start = pos; + } else { + pos = lastComma + 1; + } + } else { + pos += 1; + } + } + if (!cookiesSeparatorFound || pos >= cookiesString.length) { + cookiesStrings.push(cookiesString.substring(start, cookiesString.length)); + } + } + return cookiesStrings; + } + module.exports = parse; + module.exports.parse = parse; + module.exports.parseString = parseString; + module.exports.splitCookiesString = splitCookiesString; + } +}); + +// src/store.ts +var import_set_cookie_parser = __toESM(require_set_cookie()); +var PERSISTENCY_KEY = "MSW_COOKIE_STORE"; +function supportsLocalStorage() { + try { + if (localStorage == null) { + return false; + } + const testKey = PERSISTENCY_KEY + "_test"; + localStorage.setItem(testKey, "test"); + localStorage.getItem(testKey); + localStorage.removeItem(testKey); + return true; + } catch (error) { + return false; + } +} +var hasLocalStorageSupport = supportsLocalStorage(); +function isPropertyAccessible(object, method) { + try { + object[method]; + return true; + } catch { + return false; + } +} +var CookieStore = class { + constructor() { + this.store = /* @__PURE__ */ new Map(); + } + add(request, response) { + if (isPropertyAccessible(request, "credentials") && request.credentials === "omit") { + return; + } + const requestUrl = new URL(request.url); + const responseCookies = response.headers.get("set-cookie"); + if (!responseCookies) { + return; + } + const now = Date.now(); + const parsedResponseCookies = (0, import_set_cookie_parser.parse)(responseCookies).map( + ({ maxAge, ...cookie }) => ({ + ...cookie, + expires: maxAge === void 0 ? cookie.expires : new Date(now + maxAge * 1e3), + maxAge + }) + ); + const prevCookies = this.store.get(requestUrl.origin) || /* @__PURE__ */ new Map(); + parsedResponseCookies.forEach((cookie) => { + this.store.set(requestUrl.origin, prevCookies.set(cookie.name, cookie)); + }); + } + get(request) { + this.deleteExpiredCookies(); + const requestUrl = new URL(request.url); + const originCookies = this.store.get(requestUrl.origin) || /* @__PURE__ */ new Map(); + if (!isPropertyAccessible(request, "credentials")) { + return originCookies; + } + switch (request.credentials) { + case "include": { + if (typeof document === "undefined") { + return originCookies; + } + const documentCookies = (0, import_set_cookie_parser.parse)(document.cookie); + documentCookies.forEach((cookie) => { + originCookies.set(cookie.name, cookie); + }); + return originCookies; + } + case "same-origin": { + return originCookies; + } + default: + return /* @__PURE__ */ new Map(); + } + } + getAll() { + this.deleteExpiredCookies(); + return this.store; + } + deleteAll(request) { + const requestUrl = new URL(request.url); + this.store.delete(requestUrl.origin); + } + clear() { + this.store.clear(); + } + hydrate() { + if (!hasLocalStorageSupport) { + return; + } + const persistedCookies = localStorage.getItem(PERSISTENCY_KEY); + if (!persistedCookies) { + return; + } + try { + const parsedCookies = JSON.parse(persistedCookies); + parsedCookies.forEach(([origin, cookies]) => { + this.store.set( + origin, + new Map( + cookies.map(([token, { expires, ...cookie }]) => [ + token, + expires === void 0 ? cookie : { ...cookie, expires: new Date(expires) } + ]) + ) + ); + }); + } catch (error) { + console.warn(` +[virtual-cookie] Failed to parse a stored cookie from the localStorage (key "${PERSISTENCY_KEY}"). + +Stored value: +${localStorage.getItem(PERSISTENCY_KEY)} + +Thrown exception: +${error} + +Invalid value has been removed from localStorage to prevent subsequent failed parsing attempts.`); + localStorage.removeItem(PERSISTENCY_KEY); + } + } + persist() { + if (!hasLocalStorageSupport) { + return; + } + const serializedCookies = Array.from(this.store.entries()).map( + ([origin, cookies]) => { + return [origin, Array.from(cookies.entries())]; + } + ); + localStorage.setItem(PERSISTENCY_KEY, JSON.stringify(serializedCookies)); + } + deleteExpiredCookies() { + const now = Date.now(); + this.store.forEach((originCookies, origin) => { + originCookies.forEach(({ expires, name }) => { + if (expires !== void 0 && expires.getTime() <= now) { + originCookies.delete(name); + } + }); + if (originCookies.size === 0) { + this.store.delete(origin); + } + }); + } +}; +var store = new CookieStore(); +export { + PERSISTENCY_KEY, + store +}; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/cookies/lib/index.mjs.map b/node_modules/@mswjs/cookies/lib/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..672b1eb95987f8f905bee18f221f8bdd65043e1b --- /dev/null +++ b/node_modules/@mswjs/cookies/lib/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../node_modules/set-cookie-parser/lib/set-cookie.js","../src/store.ts"],"sourcesContent":["\"use strict\";\n\nvar defaultParseOptions = {\n decodeValues: true,\n map: false,\n silent: false,\n};\n\nfunction isNonEmptyString(str) {\n return typeof str === \"string\" && !!str.trim();\n}\n\nfunction parseString(setCookieValue, options) {\n var parts = setCookieValue.split(\";\").filter(isNonEmptyString);\n\n var nameValuePairStr = parts.shift();\n var parsed = parseNameValuePair(nameValuePairStr);\n var name = parsed.name;\n var value = parsed.value;\n\n options = options\n ? Object.assign({}, defaultParseOptions, options)\n : defaultParseOptions;\n\n try {\n value = options.decodeValues ? decodeURIComponent(value) : value; // decode cookie value\n } catch (e) {\n console.error(\n \"set-cookie-parser encountered an error while decoding a cookie with value '\" +\n value +\n \"'. Set options.decodeValues to false to disable this feature.\",\n e\n );\n }\n\n var cookie = {\n name: name,\n value: value,\n };\n\n parts.forEach(function (part) {\n var sides = part.split(\"=\");\n var key = sides.shift().trimLeft().toLowerCase();\n var value = sides.join(\"=\");\n if (key === \"expires\") {\n cookie.expires = new Date(value);\n } else if (key === \"max-age\") {\n cookie.maxAge = parseInt(value, 10);\n } else if (key === \"secure\") {\n cookie.secure = true;\n } else if (key === \"httponly\") {\n cookie.httpOnly = true;\n } else if (key === \"samesite\") {\n cookie.sameSite = value;\n } else {\n cookie[key] = value;\n }\n });\n\n return cookie;\n}\n\nfunction parseNameValuePair(nameValuePairStr) {\n // Parses name-value-pair according to rfc6265bis draft\n\n var name = \"\";\n var value = \"\";\n var nameValueArr = nameValuePairStr.split(\"=\");\n if (nameValueArr.length > 1) {\n name = nameValueArr.shift();\n value = nameValueArr.join(\"=\"); // everything after the first =, joined by a \"=\" if there was more than one part\n } else {\n value = nameValuePairStr;\n }\n\n return { name: name, value: value };\n}\n\nfunction parse(input, options) {\n options = options\n ? Object.assign({}, defaultParseOptions, options)\n : defaultParseOptions;\n\n if (!input) {\n if (!options.map) {\n return [];\n } else {\n return {};\n }\n }\n\n if (input.headers) {\n if (typeof input.headers.getSetCookie === \"function\") {\n // for fetch responses - they combine headers of the same type in the headers array,\n // but getSetCookie returns an uncombined array\n input = input.headers.getSetCookie();\n } else if (input.headers[\"set-cookie\"]) {\n // fast-path for node.js (which automatically normalizes header names to lower-case\n input = input.headers[\"set-cookie\"];\n } else {\n // slow-path for other environments - see #25\n var sch =\n input.headers[\n Object.keys(input.headers).find(function (key) {\n return key.toLowerCase() === \"set-cookie\";\n })\n ];\n // warn if called on a request-like object with a cookie header rather than a set-cookie header - see #34, 36\n if (!sch && input.headers.cookie && !options.silent) {\n console.warn(\n \"Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning.\"\n );\n }\n input = sch;\n }\n }\n if (!Array.isArray(input)) {\n input = [input];\n }\n\n options = options\n ? Object.assign({}, defaultParseOptions, options)\n : defaultParseOptions;\n\n if (!options.map) {\n return input.filter(isNonEmptyString).map(function (str) {\n return parseString(str, options);\n });\n } else {\n var cookies = {};\n return input.filter(isNonEmptyString).reduce(function (cookies, str) {\n var cookie = parseString(str, options);\n cookies[cookie.name] = cookie;\n return cookies;\n }, cookies);\n }\n}\n\n/*\n Set-Cookie header field-values are sometimes comma joined in one string. This splits them without choking on commas\n that are within a single set-cookie field-value, such as in the Expires portion.\n\n This is uncommon, but explicitly allowed - see https://tools.ietf.org/html/rfc2616#section-4.2\n Node.js does this for every header *except* set-cookie - see https://github.com/nodejs/node/blob/d5e363b77ebaf1caf67cd7528224b651c86815c1/lib/_http_incoming.js#L128\n React Native's fetch does this for *every* header, including set-cookie.\n\n Based on: https://github.com/google/j2objc/commit/16820fdbc8f76ca0c33472810ce0cb03d20efe25\n Credits to: https://github.com/tomball for original and https://github.com/chrusart for JavaScript implementation\n*/\nfunction splitCookiesString(cookiesString) {\n if (Array.isArray(cookiesString)) {\n return cookiesString;\n }\n if (typeof cookiesString !== \"string\") {\n return [];\n }\n\n var cookiesStrings = [];\n var pos = 0;\n var start;\n var ch;\n var lastComma;\n var nextStart;\n var cookiesSeparatorFound;\n\n function skipWhitespace() {\n while (pos < cookiesString.length && /\\s/.test(cookiesString.charAt(pos))) {\n pos += 1;\n }\n return pos < cookiesString.length;\n }\n\n function notSpecialChar() {\n ch = cookiesString.charAt(pos);\n\n return ch !== \"=\" && ch !== \";\" && ch !== \",\";\n }\n\n while (pos < cookiesString.length) {\n start = pos;\n cookiesSeparatorFound = false;\n\n while (skipWhitespace()) {\n ch = cookiesString.charAt(pos);\n if (ch === \",\") {\n // ',' is a cookie separator if we have later first '=', not ';' or ','\n lastComma = pos;\n pos += 1;\n\n skipWhitespace();\n nextStart = pos;\n\n while (pos < cookiesString.length && notSpecialChar()) {\n pos += 1;\n }\n\n // currently special character\n if (pos < cookiesString.length && cookiesString.charAt(pos) === \"=\") {\n // we found cookies separator\n cookiesSeparatorFound = true;\n // pos is inside the next cookie, so back up and return it.\n pos = nextStart;\n cookiesStrings.push(cookiesString.substring(start, lastComma));\n start = pos;\n } else {\n // in param ',' or param separator ';',\n // we continue from that comma\n pos = lastComma + 1;\n }\n } else {\n pos += 1;\n }\n }\n\n if (!cookiesSeparatorFound || pos >= cookiesString.length) {\n cookiesStrings.push(cookiesString.substring(start, cookiesString.length));\n }\n }\n\n return cookiesStrings;\n}\n\nmodule.exports = parse;\nmodule.exports.parse = parse;\nmodule.exports.parseString = parseString;\nmodule.exports.splitCookiesString = splitCookiesString;\n","import { Cookie, parse as parseCookie } from 'set-cookie-parser'\n\ninterface RequestLike {\n credentials: Request['credentials']\n url: string\n}\n\ninterface HeadersLike {\n get(name: string): string | null\n}\n\ninterface ResponseLike {\n headers: HeadersLike\n}\n\nexport type Store = Map\nexport type StoreEntry = Map\nexport type CookieString = Omit & { expires?: string }\n\nexport const PERSISTENCY_KEY = 'MSW_COOKIE_STORE'\n\nfunction supportsLocalStorage() {\n try {\n if (localStorage == null) {\n return false\n }\n\n const testKey = PERSISTENCY_KEY + '_test'\n\n localStorage.setItem(testKey, 'test')\n localStorage.getItem(testKey)\n localStorage.removeItem(testKey)\n\n return true\n } catch (error) {\n return false\n }\n}\n\nconst hasLocalStorageSupport = supportsLocalStorage()\n\n/**\n * Checks that accessing a given property on an object\n * by name does not throw an error.\n *\n * This is generally used to avoid issues in environments\n * like `miniflare` where some properties are defined as getters\n * where accessing that property throws directly.\n */\nfunction isPropertyAccessible>(\n object: Obj,\n method: keyof Obj,\n) {\n try {\n object[method]\n return true\n } catch {\n return false\n }\n}\n\nclass CookieStore {\n private store: Store\n\n constructor() {\n this.store = new Map()\n }\n\n /**\n * Sets the given request cookies into the store.\n * Respects the `request.credentials` policy.\n */\n add(request: RequestLike, response: ResponseLike): void {\n if (\n isPropertyAccessible(request, 'credentials') &&\n request.credentials === 'omit'\n ) {\n return\n }\n\n const requestUrl = new URL(request.url)\n const responseCookies = response.headers.get('set-cookie')\n\n if (!responseCookies) {\n return\n }\n\n const now = Date.now()\n const parsedResponseCookies = parseCookie(responseCookies).map(\n ({ maxAge, ...cookie }) => ({\n ...cookie,\n expires:\n maxAge === undefined ? cookie.expires : new Date(now + maxAge * 1000),\n maxAge,\n }),\n )\n\n const prevCookies =\n this.store.get(requestUrl.origin) || new Map()\n\n parsedResponseCookies.forEach((cookie) => {\n this.store.set(requestUrl.origin, prevCookies.set(cookie.name, cookie))\n })\n }\n\n /**\n * Returns cookies relevant to the given request\n * and its `request.credentials` policy.\n */\n get(request: RequestLike): StoreEntry {\n this.deleteExpiredCookies()\n\n const requestUrl = new URL(request.url)\n const originCookies =\n this.store.get(requestUrl.origin) || new Map()\n\n if (!isPropertyAccessible(request, 'credentials')) {\n return originCookies\n }\n\n switch (request.credentials) {\n case 'include': {\n // Support running this method in Node.js.\n if (typeof document === 'undefined') {\n return originCookies\n }\n\n const documentCookies = parseCookie(document.cookie)\n\n documentCookies.forEach((cookie) => {\n originCookies.set(cookie.name, cookie)\n })\n\n return originCookies\n }\n\n case 'same-origin': {\n return originCookies\n }\n\n default:\n return new Map()\n }\n }\n\n /**\n * Returns a collection of all stored cookies.\n */\n getAll(): Store {\n this.deleteExpiredCookies()\n return this.store\n }\n\n /**\n * Deletes all cookies associated with the given request.\n */\n deleteAll(request: RequestLike): void {\n const requestUrl = new URL(request.url)\n this.store.delete(requestUrl.origin)\n }\n\n /**\n * Clears the entire cookie store.\n */\n clear(): void {\n this.store.clear()\n }\n\n /**\n * Hydrates the virtual cookie store from the `localStorage` if defined.\n */\n hydrate(): void {\n if (!hasLocalStorageSupport) {\n return\n }\n\n const persistedCookies = localStorage.getItem(PERSISTENCY_KEY)\n\n if (!persistedCookies) {\n return\n }\n\n try {\n const parsedCookies: [string, [string, CookieString][]][] =\n JSON.parse(persistedCookies)\n\n parsedCookies.forEach(([origin, cookies]) => {\n this.store.set(\n origin,\n new Map(\n cookies.map(([token, { expires, ...cookie }]) => [\n token,\n expires === undefined\n ? cookie\n : { ...cookie, expires: new Date(expires) },\n ]),\n ),\n )\n })\n } catch (error) {\n console.warn(`\n[virtual-cookie] Failed to parse a stored cookie from the localStorage (key \"${PERSISTENCY_KEY}\").\n\nStored value:\n${localStorage.getItem(PERSISTENCY_KEY)}\n\nThrown exception:\n${error}\n\nInvalid value has been removed from localStorage to prevent subsequent failed parsing attempts.`)\n localStorage.removeItem(PERSISTENCY_KEY)\n }\n }\n\n /**\n * Persists the current virtual cookies into the `localStorage` if defined,\n * so they are available on the next page load.\n */\n persist(): void {\n if (!hasLocalStorageSupport) {\n return\n }\n\n const serializedCookies = Array.from(this.store.entries()).map(\n ([origin, cookies]) => {\n return [origin, Array.from(cookies.entries())]\n },\n )\n\n localStorage.setItem(PERSISTENCY_KEY, JSON.stringify(serializedCookies))\n }\n\n private deleteExpiredCookies() {\n const now = Date.now()\n\n this.store.forEach((originCookies, origin) => {\n originCookies.forEach(({ expires, name }) => {\n if (expires !== undefined && expires.getTime() <= now) {\n originCookies.delete(name)\n }\n })\n\n if (originCookies.size === 0) {\n this.store.delete(origin)\n }\n })\n }\n}\n\nexport const store = new CookieStore()\n"],"mappings":"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","names":["value","cookies","parseCookie"]} \ No newline at end of file diff --git a/node_modules/@mswjs/cookies/package.json b/node_modules/@mswjs/cookies/package.json new file mode 100644 index 0000000000000000000000000000000000000000..315ff269c24b9545c998c35ea39a5a0e7c3c0fb4 --- /dev/null +++ b/node_modules/@mswjs/cookies/package.json @@ -0,0 +1,99 @@ +{ + "_from": "@mswjs/cookies@^1.1.0", + "_id": "@mswjs/cookies@1.1.1", + "_inBundle": false, + "_integrity": "sha512-W68qOHEjx1iD+4VjQudlx26CPIoxmIAtK4ZCexU0/UJBG6jYhcuyzKJx+Iw8uhBIGd9eba64XgWVgo20it1qwA==", + "_location": "/@mswjs/cookies", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@mswjs/cookies@^1.1.0", + "name": "@mswjs/cookies", + "escapedName": "@mswjs%2fcookies", + "scope": "@mswjs", + "rawSpec": "^1.1.0", + "saveSpec": null, + "fetchSpec": "^1.1.0" + }, + "_requiredBy": [ + "/msw" + ], + "_resolved": "https://registry.npmjs.org/@mswjs/cookies/-/cookies-1.1.1.tgz", + "_shasum": "8b519e2bd8f1577c530beed44a25578eb9a6e72c", + "_spec": "@mswjs/cookies@^1.1.0", + "_where": "/Users/sylvainfiloni/Documents/HuggingFace_Projects/live-vision/node_modules/msw", + "author": { + "name": "Artem Zakharchenko" + }, + "bugs": { + "url": "https://github.com/mswjs/cookies/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Manage request/response cookies in the environments where those are not supported.", + "devDependencies": { + "@commitlint/cli": "^16.0.3", + "@commitlint/config-conventional": "^16.0.0", + "@ossjs/release": "^0.8.0", + "@types/jest": "^29.5.7", + "@types/set-cookie-parser": "^2.4.5", + "commitizen": "^4.2.4", + "cz-conventional-changelog": "^3.3.0", + "jest": "^29.7.0", + "jest-environment-jsdom": "^29.7.0", + "jest-environment-miniflare": "^2.14.1", + "rimraf": "^5.0.5", + "set-cookie-parser": "^2.6.0", + "simple-git-hooks": "^2.7.0", + "ts-jest": "^29.1.1", + "ts-node": "^10.9.1", + "tsup": "^6.2.3", + "typescript": "^5.2.2", + "whatwg-fetch": "^3.6.19" + }, + "engines": { + "node": ">=18" + }, + "exports": { + ".": { + "types": "./lib/index.d.ts", + "require": "./lib/index.js", + "default": "./lib/index.mjs" + } + }, + "files": [ + "README.md", + "lib" + ], + "homepage": "https://github.com/mswjs/cookies#readme", + "license": "MIT", + "main": "lib/index.js", + "module": "lib/index.mjs", + "name": "@mswjs/cookies", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/mswjs/cookies.git" + }, + "scripts": { + "build": "yarn clean && tsup", + "clean": "rimraf lib", + "prepack": "yarn build", + "prepare": "yarn simple-git-hooks init", + "prepublishOnly": "yarn test", + "release": "release publish", + "start": "tsup --watch", + "test": "jest" + }, + "types": "lib/index.d.ts", + "version": "1.1.1", + "warnings": [ + { + "code": "ENOTSUP", + "required": { + "node": ">=18" + }, + "pkgid": "@mswjs/cookies@1.1.1" + } + ] +} diff --git a/node_modules/@mswjs/interceptors/ClientRequest/package.json b/node_modules/@mswjs/interceptors/ClientRequest/package.json new file mode 100644 index 0000000000000000000000000000000000000000..4ee863900b8d67f320b4675f3d9666ee10d61262 --- /dev/null +++ b/node_modules/@mswjs/interceptors/ClientRequest/package.json @@ -0,0 +1,6 @@ +{ + "main": "../lib/node/interceptors/ClientRequest/index.js", + "module": "../lib/node/interceptors/ClientRequest/index.mjs", + "browser": null, + "types": "../lib/node/interceptors/ClientRequest/index.d.ts" +} diff --git a/node_modules/@mswjs/interceptors/LICENSE.md b/node_modules/@mswjs/interceptors/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..e5c461e5fd63682eba93307cade8b073c7782489 --- /dev/null +++ b/node_modules/@mswjs/interceptors/LICENSE.md @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) 2018–present Artem Zakharchenko + +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/node_modules/@mswjs/interceptors/README.md b/node_modules/@mswjs/interceptors/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8bc5adb5aec43fa9e41f5a25179cffdc79ccf77f --- /dev/null +++ b/node_modules/@mswjs/interceptors/README.md @@ -0,0 +1,547 @@ +[![Latest version](https://img.shields.io/npm/v/@mswjs/interceptors.svg)](https://www.npmjs.com/package/@mswjs/interceptors) + +# `@mswjs/interceptors` + +Low-level network interception library. + +This library supports intercepting the following protocols: + +- HTTP (via the `http` module, `XMLHttpRequest`, or `globalThis.fetch`); +- [WebSocket](#websocket-interception) (the `WebSocket` class in Undici and in the browser). + +## Motivation + +While there are a lot of network communication mocking libraries, they tend to use request interception as an implementation detail, giving you a high-level API that includes request matching, timeouts, retries, and so forth. + +This library is a strip-to-bone implementation that provides as little abstraction as possible to execute arbitrary logic upon any request. It's primarily designed as an underlying component for high-level API mocking solutions such as [Mock Service Worker](https://github.com/mswjs/msw). + +### How is this library different? + +A traditional API mocking implementation in Node.js looks roughly like this: + +```js +import http from 'http' + +function applyMock() { + // Store the original request module. + const originalHttpRequest = http.request + + // Rewrite the request module entirely. + http.request = function (...args) { + // Decide whether to handle this request before + // the actual request happens. + if (shouldMock(args)) { + // If so, never create a request, respond to it + // using the mocked response from this blackbox. + return coerceToResponse.bind(this, mock) + } + + // Otherwise, construct the original request + // and perform it as-is (receives the original response). + return originalHttpRequest(...args) + } +} +``` + +This library deviates from such implementation and uses _class extensions_ instead of module rewrites. Such deviation is necessary because, unlike other solutions that include request matching and can determine whether to mock requests _before_ they actually happen, this library is not opinionated about the mocked/bypassed nature of the requests. Instead, it _intercepts all requests_ and delegates the decision of mocking to the end consumer. + +```js +class NodeClientRequest extends ClientRequest { + async end(...args) { + // Check if there's a mocked response for this request. + // You control this in the "resolver" function. + const mockedResponse = await resolver(request) + + // If there is a mocked response, use it to respond to this + // request, finalizing it afterward as if it received that + // response from the actual server it connected to. + if (mockedResponse) { + this.respondWith(mockedResponse) + this.finish() + return + } + + // Otherwise, perform the original "ClientRequest.prototype.end" call. + return super.end(...args) + } +} +``` + +By extending the native modules, this library actually constructs requests as soon as they are constructed by the consumer. This enables all the request input validation and transformations done natively by Node.js—something that traditional solutions simply cannot do (they replace `http.ClientRequest` entirely). The class extension allows to fully utilize Node.js internals instead of polyfilling them, which results in more resilient mocks. + +## What this library does + +This library extends (or patches, where applicable) the following native modules: + +- `http.get`/`http.request` +- `https.get`/`https.request` +- `XMLHttpRequest` +- `fetch` + +Once extended, it intercepts and normalizes all requests to the Fetch API `Request` instances. This way, no matter the request source (`http.ClientRequest`, `XMLHttpRequest`, `window.Request`, etc), you always get a specification-compliant request instance to work with. + +You can respond to the intercepted request by constructing a Fetch API Response instance. Instead of designing custom abstractions, this library respects the Fetch API specification and takes the responsibility to coerce a single response declaration to the appropriate response formats based on the request-issuing modules (like `http.OutgoingMessage` to respond to `http.ClientRequest`, or updating `XMLHttpRequest` response-related properties). + +## What this library doesn't do + +- Does **not** provide any request matching logic; +- Does **not** decide how to handle requests. + +## Getting started + +```bash +npm install @mswjs/interceptors +``` + +## Interceptors + +To use this library you need to choose one or multiple interceptors to apply. There are different interceptors exported by this library to spy on respective request-issuing modules: + +- `ClientRequestInterceptor` to spy on `http.ClientRequest` (`http.get`/`http.request`); +- `XMLHttpRequestInterceptor` to spy on `XMLHttpRequest`; +- `FetchInterceptor` to spy on `fetch`. + +Use an interceptor by constructing it and attaching request/response listeners: + +```js +import { ClientRequestInterceptor } from '@mswjs/interceptors/ClientRequest' + +const interceptor = new ClientRequestInterceptor() + +// Enable the interception of requests. +interceptor.apply() + +// Listen to any "http.ClientRequest" being dispatched, +// and log its method and full URL. +interceptor.on('request', ({ request, requestId }) => { + console.log(request.method, request.url) +}) + +// Listen to any responses sent to "http.ClientRequest". +// Note that this listener is read-only and cannot affect responses. +interceptor.on( + 'response', + ({ response, isMockedResponse, request, requestId }) => { + console.log('response to %s %s was:', request.method, request.url, response) + } +) +``` + +All HTTP request interceptors implement the same events: + +- `request`, emitted whenever a request has been dispatched; +- `response`, emitted whenever any request receives a response. + +### Using multiple interceptors + +You can combine multiple interceptors to capture requests from different request-issuing modules at once. + +```js +import { BatchInterceptor } from '@mswjs/interceptors' +import { ClientRequestInterceptor } from '@mswjs/interceptors/ClientRequest' +import { XMLHttpRequestInterceptor } from '@mswjs/interceptors/XMLHttpRequest' + +const interceptor = new BatchInterceptor({ + name: 'my-interceptor', + interceptors: [ + new ClientRequestInterceptor(), + new XMLHttpRequestInterceptor(), + ], +}) + +interceptor.apply() + +// This "request" listener will be called on both +// "http.ClientRequest" and "XMLHttpRequest" being dispatched. +interceptor.on('request', listener) +``` + +> Note that you can use [pre-defined presets](#presets) that cover all the request sources for a given environment type. + +## Presets + +When using [`BatchInterceptor`](#batchinterceptor), you can provide a pre-defined preset to its "interceptors" option to capture all request for that environment. + +### Node.js preset + +This preset combines `ClientRequestInterceptor`, `XMLHttpRequestInterceptor` and is meant to be used in Node.js. + +```js +import { BatchInterceptor } from '@mswjs/interceptors' +import nodeInterceptors from '@mswjs/interceptors/presets/node' + +const interceptor = new BatchInterceptor({ + name: 'my-interceptor', + interceptors: nodeInterceptors, +}) + +interceptor.apply() + +interceptor.on('request', listener) +``` + +### Browser preset + +This preset combines `XMLHttpRequestInterceptor` and `FetchInterceptor` and is meant to be used in a browser. + +```js +import { BatchInterceptor } from '@mswjs/interceptors' +import browserInterceptors from '@mswjs/interceptors/presets/browser' + +const interceptor = new BatchInterceptor({ + name: 'my-interceptor', + interceptors: browserInterceptors, +}) + +interceptor.on('request', listener) +``` + +## Introspecting requests + +All HTTP request interceptors emit a "request" event. In the listener to this event, they expose a `request` reference, which is a [Fetch API Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) instance. + +> There are many ways to describe a request in Node.js but this library coerces different request definitions to a single specification-compliant `Request` instance to make the handling consistent. + +```js +interceptor.on('request', ({ request, requestId }) => { + console.log(request.method, request.url) +}) +``` + +Since the exposed `request` instance implements the Fetch API specification, you can operate with it just as you do with the regular browser request. For example, this is how you would read the request body as JSON: + +```js +interceptor.on('request', async ({ request, requestId }) => { + const json = await request.clone().json() +}) +``` + +> **Do not forget to clone the request before reading its body!** + +## Modifying requests + +Request representations are readonly. You can, however, mutate the intercepted request's headers in the "request" listener: + +```js +interceptor.on('request', ({ request }) => { + request.headers.set('X-My-Header', 'true') +}) +``` + +> This restriction is done so that the library wouldn't have to unnecessarily synchronize the actual request instance and its Fetch API request representation. As of now, this library is not meant to be used as a full-scale proxy. + +## Mocking responses + +Although this library can be used purely for request introspection purposes, you can also affect request resolution by responding to any intercepted request within the "request" event. + +Use the `request.respondWith()` method to respond to a request with a mocked response: + +```js +interceptor.on('request', ({ request, requestId }) => { + request.respondWith( + new Response( + JSON.stringify({ + firstName: 'John', + lastName: 'Maverick', + }), + { + status: 201, + statusText: 'Created', + headers: { + 'Content-Type': 'application/json', + }, + } + ) + ) +}) +``` + +> We use Fetch API `Response` class as the middle-ground for mocked response definition. This library then coerces the response instance to the appropriate response format (e.g. to `http.OutgoingMessage` in the case of `http.ClientRequest`). + +**The `Response` class is built-in in since Node.js 18. Use a Fetch API-compatible polyfill, like `node-fetch`, for older versions of Node.js.`** + +Note that a single request _can only be handled once_. You may want to introduce conditional logic, like routing, in your request listener but it's generally advised to use a higher-level library like [Mock Service Worker](https://github.com/mswjs/msw) that does request matching for you. + +Requests must be responded to within the same tick as the request listener. This means you cannot respond to a request using `setTimeout`, as this will delegate the callback to the next tick. If you wish to introduce asynchronous side-effects in the listener, consider making it an `async` function, awaiting any side-effects you need. + +```js +// Respond to all requests with a 500 response +// delayed by 500ms. +interceptor.on('request', async ({ request, requestId }) => { + await sleep(500) + request.respondWith(new Response(null, { status: 500 })) +}) +``` + +## Observing responses + +You can use the "response" event to transparently observe any incoming responses in your Node.js process. + +```js +interceptor.on( + 'response', + ({ response, isMockedResponse, request, requestId }) => { + // react to the incoming response... + } +) +``` + +> Note that the `isMockedResponse` property will only be set to `true` if you resolved this request in the "request" event listener using the `request.respondWith()` method and providing a mocked `Response` instance. + +## WebSocket interception + +You can intercept a WebSocket communication using the `WebSocketInterceptor` class. + +> [!IMPORTANT] +> This library only supports intercepting WebSocket connections created using the global WHATWG `WebSocket` class. Third-party transports, such as HTTP/XHR polling, are not supported by design due to their contrived nature. + +```js +import { WebSocketInterceptor } from '@mswjs/interceptors/WebSocket' + +const interceptor = new WebSocketInterceptor() +``` + +Unlike the HTTP-based interceptors that share the same `request`/`response` events, the WebSocket interceptor only emits the `connection` event and let's you handle the incoming/outgoing events in its listener. + +### Important defaults + +1. Intercepted WebSocket connections are _not opened_. To open the actual WebSocket connection, call [`server.connect()`](#connect) in the interceptor. +1. Once connected to the actual server, the outgoing client events are _forwarded to that server by default_. If you wish to prevent a client message from reaching the server, call `event.preventDefault()` for that client message event. +1. Once connected to the actual server, the incoming server events are _forwarded to the client by default_. If you wish to prevent a server message from reaching the client, call `event.preventDefault()` for the server message event. +1. Once connected to the actual server, the `close` event received from that server is _forwarded to the client by default_. If you wish to prevent that, call `event.preventDefault()` for that close event of the server. + +### WebSocket connection + +Whenever a WebSocket instance is constructed, the `connection` event is emitted on the WebSocket interceptor. + +```js +intereceptor.on('connection', ({ client }) => { + console.log(client.url) +}) +``` + +The `connection` event exposes the following arguments: + +| Name | Type | Description | +| -------- | --------------------------------------------------------- | ---------------------------------------------------------------- | +| `client` | [`WebSocketClientConnection`](#websocketclientconnection) | An object representing a connected WebSocket client instance. | +| `server` | [`WebSocketServerConnection`](#websocketserverconnection) | An object representing the original WebSocket server connection. | + +### `WebSocketClientConnection` + +#### `.addEventListener(type, listener)` + +- `type`, `string` +- `listener`, `EventListener` + +Adds an event listener to the given event type of the WebSocket client. + +```ts +interface WebSocketServerConnectionEventMap { + // Dispatched when the WebSocket client sends data. + message: (this: WebSocket, event: MessageEvent) => void + + // Dispatched when the WebSocket client is closed. + close: (this: WebSocket, event: CloseEvent) => void +} +``` + +```js +client.addEventListener('message', (event) => { + console.log('outgoing:', event.data) +}) +``` + +#### `.removeEventListener(type, listener)` + +- `type`, `string` +- `listener`, `EventListener` + +Removes the listener for the given event type. + +#### `.send(data)` + +- `data`, `string | Blob | ArrayBuffer` + +Sends the data to the intercepted WebSocket client. + +```js +client.send('text') +client.send(new Blob(['blob'])) +client.send(new TextEncoder().encode('array buffer')) +``` + +#### `.close(code, reason)` + +- `code`, close [status code](https://www.rfc-editor.org/rfc/rfc6455#section-7.4.1). +- `reason`, [close reason](https://www.rfc-editor.org/rfc/rfc6455#section-7.1.6). + +Closes the client connection. Unlike the regular `WebSocket.prototype.close()`, the `client.close()` method can accept a non-configurable status codes, such as 1001, 1003, etc. + +```js +// Gracefully close the connection with the +// intercepted WebSocket client. +client.close() +``` + +```js +// Terminate the connection by emulating +// the server unable to process the received data. +client.close(1003) +``` + +### `WebSocketServerConnection` + +#### `.connect()` + +Establishes the connection to the original WebSocket server. Connection cannot be awaited. Any data sent via `server.send()` while connecting is buffered and flushed once the connection is open. + +#### `.addEventListener(type, listener)` + +- `type`, `string` +- `listener`, `EventListener` + +Adds an event listener to the given event type of the WebSocket server. + +```ts +interface WebSocketServerConnectionEventMap { + // Dispatched when the server connection is open. + open: (this: WebSocket, event: Event) => void + + // Dispatched when the server sends data to the client. + message: (this: WebSocket, event: MessageEvent) => void + + // Dispatched when the server connection closes. + close: (this: WebSocket, event: CloseEvent) => void +} +``` + +```js +server.addEventListener('message', (event) => { + console.log('incoming:', event.data) +}) +``` + +#### `.removeEventListener(type, listener)` + +- `type`, `string` +- `listener`, `EventListener` + +Removes the listener for the given event type. + +#### `.send(data)` + +- `data`, `string | Blob | ArrayBuffer` + +Sends the data to the original WebSocket server. Useful in a combination with the client-sent events forwarding: + +```js +client.addEventListener('message', (event) => { + server.send(event.data) +}) +``` + +#### `.close()` + +Closes the connection with the original WebSocket server. Unlike `client.close()`, closing the server connection does not accept any arguments and always asumes a graceful closure. Sending data via `server.send()` after the connection has been closed will have no effect. + +## API + +### `Interceptor` + +A generic class implemented by all interceptors. You do not interact with this class directly. + +```ts +class Interceptor { + // Applies the interceptor, enabling the interception of requests + // in the current process. + apply(): void + + // Listens to the public interceptor events. + // For HTTP requests, these are "request' and "response" events. + on(event, listener): void + + // Cleans up any side-effects introduced by the interceptor + // and disables the interception of requests. + dispose(): void +} +``` + +**For public consumption, use [interceptors](#interceptors) instead**. + +### `BatchInterceptor` + +Applies multiple request interceptors at the same time. + +```js +import { BatchInterceptor } from '@mswjs/interceptors' +import nodeInterceptors from '@mswjs/interceptors/presets/node' + +const interceptor = new BatchInterceptor({ + name: 'my-interceptor', + interceptors: nodeInterceptors, +}) + +interceptor.apply() + +interceptor.on('request', ({ request, requestId }) => { + // Inspect the intercepted "request". + // Optionally, return a mocked response. +}) +``` + +> Using the `/presets/node` interceptors preset is the recommended way to ensure all requests get intercepted, regardless of their origin. + +### `RemoteHttpInterceptor` + +Enables request interception in the current process while delegating the response resolution logic to the _parent process_. **Requires the current process to be a child process**. Requires the parent process to establish a resolver by calling the `createRemoteResolver` function. + +```js +// child.js +import { RemoteHttpInterceptor } from '@mswjs/interceptors/RemoteHttpInterceptor' +import { ClientRequestInterceptor } from '@mswjs/interceptors/ClientRequest' + +const interceptor = new RemoteHttpInterceptor({ + // Alternatively, you can use presets. + interceptors: [new ClientRequestInterceptor()], +}) + +interceptor.apply() + +process.on('disconnect', () => { + interceptor.dispose() +}) +``` + +You can still listen to and handle any requests in the child process via the `request` event listener. Keep in mind that a single request can only be responded to once. + +### `RemoteHttpResolver` + +Resolves an intercepted request in the given child `process`. Requires for that child process to enable request interception by calling the `createRemoteInterceptor` function. + +```js +// parent.js +import { spawn } from 'child_process' +import { RemoteHttpResolver } from '@mswjs/interceptors/RemoteHttpInterceptor' + +const appProcess = spawn('node', ['app.js'], { + stdio: ['inherit', 'inherit', 'inherit', 'ipc'], +}) + +const resolver = new RemoteHttpResolver({ + process: appProcess, +}) + +resolver.on('request', ({ request, requestId }) => { + // Optionally, return a mocked response + // for a request that occurred in the "appProcess". +}) +``` + +## Special mention + +The following libraries were used as an inspiration to write this low-level API: + +- [`node`](https://github.com/nodejs/node) +- [`nock`](https://github.com/nock/nock) +- [`mock-xmlhttprequest`](https://github.com/berniegp/mock-xmlhttprequest) diff --git a/node_modules/@mswjs/interceptors/RemoteHttpInterceptor/package.json b/node_modules/@mswjs/interceptors/RemoteHttpInterceptor/package.json new file mode 100644 index 0000000000000000000000000000000000000000..bc5d53aaffbbd17864028ec47062a66a0191a3c3 --- /dev/null +++ b/node_modules/@mswjs/interceptors/RemoteHttpInterceptor/package.json @@ -0,0 +1,6 @@ +{ + "main": "../lib/node/RemoteHttpInterceptor.js", + "module": "../lib/node/RemoteHttpInterceptor.mjs", + "browser": null, + "types": "../lib/node/RemoteHttpInterceptor.d.ts" +} diff --git a/node_modules/@mswjs/interceptors/WebSocket/package.json b/node_modules/@mswjs/interceptors/WebSocket/package.json new file mode 100644 index 0000000000000000000000000000000000000000..52dfef27bdab307504d8c85d5e789dfa00207656 --- /dev/null +++ b/node_modules/@mswjs/interceptors/WebSocket/package.json @@ -0,0 +1,5 @@ +{ + "main": "../lib/browser/interceptors/WebSocket/index.js", + "module": "../lib/browser/interceptors/WebSocket/index.mjs", + "types": "../lib/browser/interceptors/WebSocket/index.d.ts" +} diff --git a/node_modules/@mswjs/interceptors/XMLHttpRequest/package.json b/node_modules/@mswjs/interceptors/XMLHttpRequest/package.json new file mode 100644 index 0000000000000000000000000000000000000000..8830bae0e2f893df8e80629f10503719451f23e2 --- /dev/null +++ b/node_modules/@mswjs/interceptors/XMLHttpRequest/package.json @@ -0,0 +1,6 @@ +{ + "main": "../lib/node/interceptors/XMLHttpRequest/index.js", + "module": "../lib/node/interceptors/XMLHttpRequest/index.mjs", + "browser": "../lib/browser/interceptors/XMLHttpRequest/index.js", + "types": "../lib/node/interceptors/XMLHttpRequest/index.d.ts" +} diff --git a/node_modules/@mswjs/interceptors/fetch/package.json b/node_modules/@mswjs/interceptors/fetch/package.json new file mode 100644 index 0000000000000000000000000000000000000000..5e5dac857354660542b403210ae36e059a5478df --- /dev/null +++ b/node_modules/@mswjs/interceptors/fetch/package.json @@ -0,0 +1,6 @@ +{ + "main": "../lib/node/interceptors/fetch/index.js", + "module": "../lib/node/interceptors/fetch/index.mjs", + "browser": "../lib/browser/interceptors/fetch/index.js", + "types": "../lib/node/interceptors/fetch/index.d.ts" +} diff --git a/node_modules/@mswjs/interceptors/lib/browser/Interceptor-af98b768.d.ts b/node_modules/@mswjs/interceptors/lib/browser/Interceptor-af98b768.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..257c42dde00d3a3d9e1cc073f6f7481c62186c2c --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/Interceptor-af98b768.d.ts @@ -0,0 +1,63 @@ +import { Logger } from '@open-draft/logger'; +import { Emitter, Listener } from 'strict-event-emitter'; + +type InterceptorEventMap = Record; +type InterceptorSubscription = () => void; +/** + * Request header name to detect when a single request + * is being handled by nested interceptors (XHR -> ClientRequest). + * Obscure by design to prevent collisions with user-defined headers. + * Ideally, come up with the Interceptor-level mechanism for this. + * @see https://github.com/mswjs/interceptors/issues/378 + */ +declare const INTERNAL_REQUEST_ID_HEADER_NAME = "x-interceptors-internal-request-id"; +declare function getGlobalSymbol(symbol: Symbol): V | undefined; +declare function deleteGlobalSymbol(symbol: Symbol): void; +declare enum InterceptorReadyState { + INACTIVE = "INACTIVE", + APPLYING = "APPLYING", + APPLIED = "APPLIED", + DISPOSING = "DISPOSING", + DISPOSED = "DISPOSED" +} +type ExtractEventNames> = Events extends Record ? EventName : never; +declare class Interceptor { + private readonly symbol; + protected emitter: Emitter; + protected subscriptions: Array; + protected logger: Logger; + readyState: InterceptorReadyState; + constructor(symbol: symbol); + /** + * Determine if this interceptor can be applied + * in the current environment. + */ + protected checkEnvironment(): boolean; + /** + * Apply this interceptor to the current process. + * Returns an already running interceptor instance if it's present. + */ + apply(): void; + /** + * Setup the module augments and stubs necessary for this interceptor. + * This method is not run if there's a running interceptor instance + * to prevent instantiating an interceptor multiple times. + */ + protected setup(): void; + /** + * Listen to the interceptor's public events. + */ + on>(event: EventName, listener: Listener): this; + once>(event: EventName, listener: Listener): this; + off>(event: EventName, listener: Listener): this; + removeAllListeners>(event?: EventName): this; + /** + * Disposes of any side-effects this interceptor has introduced. + */ + dispose(): void; + private getInstance; + private setInstance; + private clearInstance; +} + +export { ExtractEventNames as E, Interceptor as I, InterceptorEventMap as a, InterceptorSubscription as b, INTERNAL_REQUEST_ID_HEADER_NAME as c, deleteGlobalSymbol as d, InterceptorReadyState as e, getGlobalSymbol as g }; diff --git a/node_modules/@mswjs/interceptors/lib/browser/chunk-2CRB3JAQ.js b/node_modules/@mswjs/interceptors/lib/browser/chunk-2CRB3JAQ.js new file mode 100644 index 0000000000000000000000000000000000000000..dc6d882b7eafc1576d2a9fb2f277a7d7afb77529 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/chunk-2CRB3JAQ.js @@ -0,0 +1,53 @@ +"use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/glossary.ts +var IS_PATCHED_MODULE = Symbol("isPatchedModule"); + +// src/utils/isPropertyAccessible.ts +function isPropertyAccessible(obj, key) { + try { + obj[key]; + return true; + } catch (e) { + return false; + } +} + +// src/utils/responseUtils.ts +var RESPONSE_STATUS_CODES_WITHOUT_BODY = /* @__PURE__ */ new Set([ + 101, + 103, + 204, + 205, + 304 +]); +function isResponseWithoutBody(status) { + return RESPONSE_STATUS_CODES_WITHOUT_BODY.has(status); +} +function createServerErrorResponse(body) { + return new Response( + JSON.stringify( + body instanceof Error ? { + name: body.name, + message: body.message, + stack: body.stack + } : body + ), + { + status: 500, + statusText: "Unhandled Exception", + headers: { + "Content-Type": "application/json" + } + } + ); +} +function isResponseError(response) { + return isPropertyAccessible(response, "type") && response.type === "error"; +} + + + + + + +exports.IS_PATCHED_MODULE = IS_PATCHED_MODULE; exports.isResponseWithoutBody = isResponseWithoutBody; exports.createServerErrorResponse = createServerErrorResponse; exports.isResponseError = isResponseError; +//# sourceMappingURL=chunk-2CRB3JAQ.js.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/chunk-2CRB3JAQ.js.map b/node_modules/@mswjs/interceptors/lib/browser/chunk-2CRB3JAQ.js.map new file mode 100644 index 0000000000000000000000000000000000000000..520652f02b33437c1147abfe3d74d62c09717744 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/chunk-2CRB3JAQ.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/glossary.ts","../../src/utils/isPropertyAccessible.ts","../../src/utils/responseUtils.ts"],"names":[],"mappings":";AAEO,IAAM,oBAAmC,OAAO,iBAAiB;;;ACMjE,SAAS,qBACd,KACA,KACA;AACA,MAAI;AACF,QAAI,GAAG;AACP,WAAO;AAAA,EACT,SAAQ,GAAN;AACA,WAAO;AAAA,EACT;AACF;;;ACZO,IAAM,qCAAqC,oBAAI,IAAI;AAAA,EACxD;AAAA,EAAK;AAAA,EAAK;AAAA,EAAK;AAAA,EAAK;AACtB,CAAC;AAMM,SAAS,sBAAsB,QAAyB;AAC7D,SAAO,mCAAmC,IAAI,MAAM;AACtD;AAKO,SAAS,0BAA0B,MAAyB;AACjE,SAAO,IAAI;AAAA,IACT,KAAK;AAAA,MACH,gBAAgB,QACZ;AAAA,QACE,MAAM,KAAK;AAAA,QACX,SAAS,KAAK;AAAA,QACd,OAAO,KAAK;AAAA,MACd,IACA;AAAA,IACN;AAAA,IACA;AAAA,MACE,QAAQ;AAAA,MACR,YAAY;AAAA,MACZ,SAAS;AAAA,QACP,gBAAgB;AAAA,MAClB;AAAA,IACF;AAAA,EACF;AACF;AAUO,SAAS,gBACd,UAC0C;AAC1C,SAAO,qBAAqB,UAAU,MAAM,KAAK,SAAS,SAAS;AACrE","sourcesContent":["import type { InteractiveRequest } from './utils/toInteractiveRequest'\n\nexport const IS_PATCHED_MODULE: unique symbol = Symbol('isPatchedModule')\n\nexport type RequestCredentials = 'omit' | 'include' | 'same-origin'\n\nexport type HttpRequestEventMap = {\n request: [\n args: {\n request: InteractiveRequest\n requestId: string\n }\n ]\n response: [\n args: {\n response: Response\n isMockedResponse: boolean\n request: Request\n requestId: string\n }\n ]\n unhandledException: [\n args: {\n error: unknown\n request: Request\n requestId: string\n controller: {\n respondWith(response: Response): void\n errorWith(error?: Error): void\n }\n }\n ]\n}\n","/**\n * A function that validates if property access is possible on an object\n * without throwing. It returns `true` if the property access is possible\n * and `false` otherwise.\n *\n * Environments like miniflare will throw on property access on certain objects\n * like Request and Response, for unimplemented properties.\n */\nexport function isPropertyAccessible>(\n obj: Obj,\n key: keyof Obj\n) {\n try {\n obj[key]\n return true\n } catch {\n return false\n }\n}\n","import { isPropertyAccessible } from './isPropertyAccessible'\n\n/**\n * Response status codes for responses that cannot have body.\n * @see https://fetch.spec.whatwg.org/#statuses\n */\nexport const RESPONSE_STATUS_CODES_WITHOUT_BODY = new Set([\n 101, 103, 204, 205, 304,\n])\n\n/**\n * Returns a boolean indicating whether the given response status\n * code represents a response that cannot have a body.\n */\nexport function isResponseWithoutBody(status: number): boolean {\n return RESPONSE_STATUS_CODES_WITHOUT_BODY.has(status)\n}\n\n/**\n * Creates a generic 500 Unhandled Exception response.\n */\nexport function createServerErrorResponse(body: unknown): Response {\n return new Response(\n JSON.stringify(\n body instanceof Error\n ? {\n name: body.name,\n message: body.message,\n stack: body.stack,\n }\n : body\n ),\n {\n status: 500,\n statusText: 'Unhandled Exception',\n headers: {\n 'Content-Type': 'application/json',\n },\n }\n )\n}\n\n/**\n * Checks if the given response is a `Response.error()`.\n *\n * @note Some environments, like Miniflare (Cloudflare) do not\n * implement the \"Response.type\" property and throw on its access.\n * Safely check if we can access \"type\" on \"Response\" before continuing.\n * @see https://github.com/mswjs/msw/issues/1834\n */\nexport function isResponseError(\n response: Response\n): response is Response & { type: 'error' } {\n return isPropertyAccessible(response, 'type') && response.type === 'error'\n}\n"]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/chunk-6HYIRFX2.mjs b/node_modules/@mswjs/interceptors/lib/browser/chunk-6HYIRFX2.mjs new file mode 100644 index 0000000000000000000000000000000000000000..05b6c33cb2dec03c23115c9c1de440c0a0a10277 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/chunk-6HYIRFX2.mjs @@ -0,0 +1,22 @@ +// src/utils/bufferUtils.ts +var encoder = new TextEncoder(); +function encodeBuffer(text) { + return encoder.encode(text); +} +function decodeBuffer(buffer, encoding) { + const decoder = new TextDecoder(encoding); + return decoder.decode(buffer); +} +function toArrayBuffer(array) { + return array.buffer.slice( + array.byteOffset, + array.byteOffset + array.byteLength + ); +} + +export { + encodeBuffer, + decodeBuffer, + toArrayBuffer +}; +//# sourceMappingURL=chunk-6HYIRFX2.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/chunk-6HYIRFX2.mjs.map b/node_modules/@mswjs/interceptors/lib/browser/chunk-6HYIRFX2.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..6f27915c41e396fe4b28381b580d8fc7fdffbb3b --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/chunk-6HYIRFX2.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/utils/bufferUtils.ts"],"sourcesContent":["const encoder = new TextEncoder()\n\nexport function encodeBuffer(text: string): Uint8Array {\n return encoder.encode(text)\n}\n\nexport function decodeBuffer(buffer: ArrayBuffer, encoding?: string): string {\n const decoder = new TextDecoder(encoding)\n return decoder.decode(buffer)\n}\n\n/**\n * Create an `ArrayBuffer` from the given `Uint8Array`.\n * Takes the byte offset into account to produce the right buffer\n * in the case when the buffer is bigger than the data view.\n */\nexport function toArrayBuffer(array: Uint8Array): ArrayBuffer {\n return array.buffer.slice(\n array.byteOffset,\n array.byteOffset + array.byteLength\n )\n}\n"],"mappings":";AAAA,IAAM,UAAU,IAAI,YAAY;AAEzB,SAAS,aAAa,MAA0B;AACrD,SAAO,QAAQ,OAAO,IAAI;AAC5B;AAEO,SAAS,aAAa,QAAqB,UAA2B;AAC3E,QAAM,UAAU,IAAI,YAAY,QAAQ;AACxC,SAAO,QAAQ,OAAO,MAAM;AAC9B;AAOO,SAAS,cAAc,OAAgC;AAC5D,SAAO,MAAM,OAAO;AAAA,IAClB,MAAM;AAAA,IACN,MAAM,aAAa,MAAM;AAAA,EAC3B;AACF;","names":[]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/chunk-732REFPX.mjs b/node_modules/@mswjs/interceptors/lib/browser/chunk-732REFPX.mjs new file mode 100644 index 0000000000000000000000000000000000000000..54356ec65b61546033eeb7ee9efd2268c6cc2116 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/chunk-732REFPX.mjs @@ -0,0 +1,820 @@ +import { + decodeBuffer, + encodeBuffer, + toArrayBuffer +} from "./chunk-6HYIRFX2.mjs"; +import { + emitAsync, + toInteractiveRequest +} from "./chunk-OUWBQF3Z.mjs"; +import { + IS_PATCHED_MODULE, + createServerErrorResponse, + isResponseError, + isResponseWithoutBody +} from "./chunk-OMISYKWR.mjs"; +import { + INTERNAL_REQUEST_ID_HEADER_NAME, + Interceptor, + createRequestId +} from "./chunk-QED3Q6Z2.mjs"; + +// src/interceptors/XMLHttpRequest/index.ts +import { invariant as invariant2 } from "outvariant"; + +// src/interceptors/XMLHttpRequest/XMLHttpRequestProxy.ts +import { until } from "@open-draft/until"; + +// src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts +import { invariant } from "outvariant"; +import { isNodeProcess } from "is-node-process"; + +// src/interceptors/XMLHttpRequest/utils/concatArrayBuffer.ts +function concatArrayBuffer(left, right) { + const result = new Uint8Array(left.byteLength + right.byteLength); + result.set(left, 0); + result.set(right, left.byteLength); + return result; +} + +// src/interceptors/XMLHttpRequest/polyfills/EventPolyfill.ts +var EventPolyfill = class { + constructor(type, options) { + this.AT_TARGET = 0; + this.BUBBLING_PHASE = 0; + this.CAPTURING_PHASE = 0; + this.NONE = 0; + this.type = ""; + this.srcElement = null; + this.currentTarget = null; + this.eventPhase = 0; + this.isTrusted = true; + this.composed = false; + this.cancelable = true; + this.defaultPrevented = false; + this.bubbles = true; + this.lengthComputable = true; + this.loaded = 0; + this.total = 0; + this.cancelBubble = false; + this.returnValue = true; + this.type = type; + this.target = (options == null ? void 0 : options.target) || null; + this.currentTarget = (options == null ? void 0 : options.currentTarget) || null; + this.timeStamp = Date.now(); + } + composedPath() { + return []; + } + initEvent(type, bubbles, cancelable) { + this.type = type; + this.bubbles = !!bubbles; + this.cancelable = !!cancelable; + } + preventDefault() { + this.defaultPrevented = true; + } + stopPropagation() { + } + stopImmediatePropagation() { + } +}; + +// src/interceptors/XMLHttpRequest/polyfills/ProgressEventPolyfill.ts +var ProgressEventPolyfill = class extends EventPolyfill { + constructor(type, init) { + super(type); + this.lengthComputable = (init == null ? void 0 : init.lengthComputable) || false; + this.composed = (init == null ? void 0 : init.composed) || false; + this.loaded = (init == null ? void 0 : init.loaded) || 0; + this.total = (init == null ? void 0 : init.total) || 0; + } +}; + +// src/interceptors/XMLHttpRequest/utils/createEvent.ts +var SUPPORTS_PROGRESS_EVENT = typeof ProgressEvent !== "undefined"; +function createEvent(target, type, init) { + const progressEvents = [ + "error", + "progress", + "loadstart", + "loadend", + "load", + "timeout", + "abort" + ]; + const ProgressEventClass = SUPPORTS_PROGRESS_EVENT ? ProgressEvent : ProgressEventPolyfill; + const event = progressEvents.includes(type) ? new ProgressEventClass(type, { + lengthComputable: true, + loaded: (init == null ? void 0 : init.loaded) || 0, + total: (init == null ? void 0 : init.total) || 0 + }) : new EventPolyfill(type, { + target, + currentTarget: target + }); + return event; +} + +// src/utils/findPropertySource.ts +function findPropertySource(target, propertyName) { + if (!(propertyName in target)) { + return null; + } + const hasProperty = Object.prototype.hasOwnProperty.call(target, propertyName); + if (hasProperty) { + return target; + } + const prototype = Reflect.getPrototypeOf(target); + return prototype ? findPropertySource(prototype, propertyName) : null; +} + +// src/utils/createProxy.ts +function createProxy(target, options) { + const proxy = new Proxy(target, optionsToProxyHandler(options)); + return proxy; +} +function optionsToProxyHandler(options) { + const { constructorCall, methodCall, getProperty, setProperty } = options; + const handler = {}; + if (typeof constructorCall !== "undefined") { + handler.construct = function(target, args, newTarget) { + const next = Reflect.construct.bind(null, target, args, newTarget); + return constructorCall.call(newTarget, args, next); + }; + } + handler.set = function(target, propertyName, nextValue) { + const next = () => { + const propertySource = findPropertySource(target, propertyName) || target; + const ownDescriptors = Reflect.getOwnPropertyDescriptor( + propertySource, + propertyName + ); + if (typeof (ownDescriptors == null ? void 0 : ownDescriptors.set) !== "undefined") { + ownDescriptors.set.apply(target, [nextValue]); + return true; + } + return Reflect.defineProperty(propertySource, propertyName, { + writable: true, + enumerable: true, + configurable: true, + value: nextValue + }); + }; + if (typeof setProperty !== "undefined") { + return setProperty.call(target, [propertyName, nextValue], next); + } + return next(); + }; + handler.get = function(target, propertyName, receiver) { + const next = () => target[propertyName]; + const value = typeof getProperty !== "undefined" ? getProperty.call(target, [propertyName, receiver], next) : next(); + if (typeof value === "function") { + return (...args) => { + const next2 = value.bind(target, ...args); + if (typeof methodCall !== "undefined") { + return methodCall.call(target, [propertyName, args], next2); + } + return next2(); + }; + } + return value; + }; + return handler; +} + +// src/interceptors/XMLHttpRequest/utils/isDomParserSupportedType.ts +function isDomParserSupportedType(type) { + const supportedTypes = [ + "application/xhtml+xml", + "application/xml", + "image/svg+xml", + "text/html", + "text/xml" + ]; + return supportedTypes.some((supportedType) => { + return type.startsWith(supportedType); + }); +} + +// src/utils/parseJson.ts +function parseJson(data) { + try { + const json = JSON.parse(data); + return json; + } catch (_) { + return null; + } +} + +// src/interceptors/XMLHttpRequest/utils/createResponse.ts +function createResponse(request, body) { + const responseBodyOrNull = isResponseWithoutBody(request.status) ? null : body; + return new Response(responseBodyOrNull, { + status: request.status, + statusText: request.statusText, + headers: createHeadersFromXMLHttpReqestHeaders( + request.getAllResponseHeaders() + ) + }); +} +function createHeadersFromXMLHttpReqestHeaders(headersString) { + const headers = new Headers(); + const lines = headersString.split(/[\r\n]+/); + for (const line of lines) { + if (line.trim() === "") { + continue; + } + const [name, ...parts] = line.split(": "); + const value = parts.join(": "); + headers.append(name, value); + } + return headers; +} + +// src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts +var IS_MOCKED_RESPONSE = Symbol("isMockedResponse"); +var IS_NODE = isNodeProcess(); +var XMLHttpRequestController = class { + constructor(initialRequest, logger) { + this.initialRequest = initialRequest; + this.logger = logger; + this.method = "GET"; + this.url = null; + this.events = /* @__PURE__ */ new Map(); + this.requestId = createRequestId(); + this.requestHeaders = new Headers(); + this.responseBuffer = new Uint8Array(); + this.request = createProxy(initialRequest, { + setProperty: ([propertyName, nextValue], invoke) => { + switch (propertyName) { + case "ontimeout": { + const eventName = propertyName.slice( + 2 + ); + this.request.addEventListener(eventName, nextValue); + return invoke(); + } + default: { + return invoke(); + } + } + }, + methodCall: ([methodName, args], invoke) => { + var _a; + switch (methodName) { + case "open": { + const [method, url] = args; + if (typeof url === "undefined") { + this.method = "GET"; + this.url = toAbsoluteUrl(method); + } else { + this.method = method; + this.url = toAbsoluteUrl(url); + } + this.logger = this.logger.extend(`${this.method} ${this.url.href}`); + this.logger.info("open", this.method, this.url.href); + return invoke(); + } + case "addEventListener": { + const [eventName, listener] = args; + this.registerEvent(eventName, listener); + this.logger.info("addEventListener", eventName, listener); + return invoke(); + } + case "setRequestHeader": { + const [name, value] = args; + this.requestHeaders.set(name, value); + this.logger.info("setRequestHeader", name, value); + return invoke(); + } + case "send": { + const [body] = args; + if (body != null) { + this.requestBody = typeof body === "string" ? encodeBuffer(body) : body; + } + this.request.addEventListener("load", () => { + if (typeof this.onResponse !== "undefined") { + const fetchResponse = createResponse( + this.request, + /** + * The `response` property is the right way to read + * the ambiguous response body, as the request's "responseType" may differ. + * @see https://xhr.spec.whatwg.org/#the-response-attribute + */ + this.request.response + ); + this.onResponse.call(this, { + response: fetchResponse, + isMockedResponse: IS_MOCKED_RESPONSE in this.request, + request: fetchRequest, + requestId: this.requestId + }); + } + }); + const fetchRequest = this.toFetchApiRequest(); + const onceRequestSettled = ((_a = this.onRequest) == null ? void 0 : _a.call(this, { + request: fetchRequest, + requestId: this.requestId + })) || Promise.resolve(); + onceRequestSettled.finally(() => { + if (this.request.readyState < this.request.LOADING) { + this.logger.info( + "request callback settled but request has not been handled (readystate %d), performing as-is...", + this.request.readyState + ); + if (IS_NODE) { + this.request.setRequestHeader( + INTERNAL_REQUEST_ID_HEADER_NAME, + this.requestId + ); + } + return invoke(); + } + }); + break; + } + default: { + return invoke(); + } + } + } + }); + } + registerEvent(eventName, listener) { + const prevEvents = this.events.get(eventName) || []; + const nextEvents = prevEvents.concat(listener); + this.events.set(eventName, nextEvents); + this.logger.info('registered event "%s"', eventName, listener); + } + /** + * Responds to the current request with the given + * Fetch API `Response` instance. + */ + respondWith(response) { + this.logger.info( + "responding with a mocked response: %d %s", + response.status, + response.statusText + ); + define(this.request, IS_MOCKED_RESPONSE, true); + define(this.request, "status", response.status); + define(this.request, "statusText", response.statusText); + define(this.request, "responseURL", this.url.href); + this.request.getResponseHeader = new Proxy(this.request.getResponseHeader, { + apply: (_, __, args) => { + this.logger.info("getResponseHeader", args[0]); + if (this.request.readyState < this.request.HEADERS_RECEIVED) { + this.logger.info("headers not received yet, returning null"); + return null; + } + const headerValue = response.headers.get(args[0]); + this.logger.info( + 'resolved response header "%s" to', + args[0], + headerValue + ); + return headerValue; + } + }); + this.request.getAllResponseHeaders = new Proxy( + this.request.getAllResponseHeaders, + { + apply: () => { + this.logger.info("getAllResponseHeaders"); + if (this.request.readyState < this.request.HEADERS_RECEIVED) { + this.logger.info("headers not received yet, returning empty string"); + return ""; + } + const headersList = Array.from(response.headers.entries()); + const allHeaders = headersList.map(([headerName, headerValue]) => { + return `${headerName}: ${headerValue}`; + }).join("\r\n"); + this.logger.info("resolved all response headers to", allHeaders); + return allHeaders; + } + } + ); + Object.defineProperties(this.request, { + response: { + enumerable: true, + configurable: false, + get: () => this.response + }, + responseText: { + enumerable: true, + configurable: false, + get: () => this.responseText + }, + responseXML: { + enumerable: true, + configurable: false, + get: () => this.responseXML + } + }); + const totalResponseBodyLength = response.headers.has("Content-Length") ? Number(response.headers.get("Content-Length")) : ( + /** + * @todo Infer the response body length from the response body. + */ + void 0 + ); + this.logger.info("calculated response body length", totalResponseBodyLength); + this.trigger("loadstart", { + loaded: 0, + total: totalResponseBodyLength + }); + this.setReadyState(this.request.HEADERS_RECEIVED); + this.setReadyState(this.request.LOADING); + const finalizeResponse = () => { + this.logger.info("finalizing the mocked response..."); + this.setReadyState(this.request.DONE); + this.trigger("load", { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength + }); + this.trigger("loadend", { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength + }); + }; + if (response.body) { + this.logger.info("mocked response has body, streaming..."); + const reader = response.body.getReader(); + const readNextResponseBodyChunk = async () => { + const { value, done } = await reader.read(); + if (done) { + this.logger.info("response body stream done!"); + finalizeResponse(); + return; + } + if (value) { + this.logger.info("read response body chunk:", value); + this.responseBuffer = concatArrayBuffer(this.responseBuffer, value); + this.trigger("progress", { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength + }); + } + readNextResponseBodyChunk(); + }; + readNextResponseBodyChunk(); + } else { + finalizeResponse(); + } + } + responseBufferToText() { + return decodeBuffer(this.responseBuffer); + } + get response() { + this.logger.info( + "getResponse (responseType: %s)", + this.request.responseType + ); + if (this.request.readyState !== this.request.DONE) { + return null; + } + switch (this.request.responseType) { + case "json": { + const responseJson = parseJson(this.responseBufferToText()); + this.logger.info("resolved response JSON", responseJson); + return responseJson; + } + case "arraybuffer": { + const arrayBuffer = toArrayBuffer(this.responseBuffer); + this.logger.info("resolved response ArrayBuffer", arrayBuffer); + return arrayBuffer; + } + case "blob": { + const mimeType = this.request.getResponseHeader("Content-Type") || "text/plain"; + const responseBlob = new Blob([this.responseBufferToText()], { + type: mimeType + }); + this.logger.info( + "resolved response Blob (mime type: %s)", + responseBlob, + mimeType + ); + return responseBlob; + } + default: { + const responseText = this.responseBufferToText(); + this.logger.info( + 'resolving "%s" response type as text', + this.request.responseType, + responseText + ); + return responseText; + } + } + } + get responseText() { + invariant( + this.request.responseType === "" || this.request.responseType === "text", + "InvalidStateError: The object is in invalid state." + ); + if (this.request.readyState !== this.request.LOADING && this.request.readyState !== this.request.DONE) { + return ""; + } + const responseText = this.responseBufferToText(); + this.logger.info('getResponseText: "%s"', responseText); + return responseText; + } + get responseXML() { + invariant( + this.request.responseType === "" || this.request.responseType === "document", + "InvalidStateError: The object is in invalid state." + ); + if (this.request.readyState !== this.request.DONE) { + return null; + } + const contentType = this.request.getResponseHeader("Content-Type") || ""; + if (typeof DOMParser === "undefined") { + console.warn( + "Cannot retrieve XMLHttpRequest response body as XML: DOMParser is not defined. You are likely using an environment that is not browser or does not polyfill browser globals correctly." + ); + return null; + } + if (isDomParserSupportedType(contentType)) { + return new DOMParser().parseFromString( + this.responseBufferToText(), + contentType + ); + } + return null; + } + errorWith(error) { + this.logger.info("responding with an error"); + this.setReadyState(this.request.DONE); + this.trigger("error"); + this.trigger("loadend"); + } + /** + * Transitions this request's `readyState` to the given one. + */ + setReadyState(nextReadyState) { + this.logger.info( + "setReadyState: %d -> %d", + this.request.readyState, + nextReadyState + ); + if (this.request.readyState === nextReadyState) { + this.logger.info("ready state identical, skipping transition..."); + return; + } + define(this.request, "readyState", nextReadyState); + this.logger.info("set readyState to: %d", nextReadyState); + if (nextReadyState !== this.request.UNSENT) { + this.logger.info('triggerring "readystatechange" event...'); + this.trigger("readystatechange"); + } + } + /** + * Triggers given event on the `XMLHttpRequest` instance. + */ + trigger(eventName, options) { + const callback = this.request[`on${eventName}`]; + const event = createEvent(this.request, eventName, options); + this.logger.info('trigger "%s"', eventName, options || ""); + if (typeof callback === "function") { + this.logger.info('found a direct "%s" callback, calling...', eventName); + callback.call(this.request, event); + } + for (const [registeredEventName, listeners] of this.events) { + if (registeredEventName === eventName) { + this.logger.info( + 'found %d listener(s) for "%s" event, calling...', + listeners.length, + eventName + ); + listeners.forEach((listener) => listener.call(this.request, event)); + } + } + } + /** + * Converts this `XMLHttpRequest` instance into a Fetch API `Request` instance. + */ + toFetchApiRequest() { + this.logger.info("converting request to a Fetch API Request..."); + const fetchRequest = new Request(this.url.href, { + method: this.method, + headers: this.requestHeaders, + /** + * @see https://xhr.spec.whatwg.org/#cross-origin-credentials + */ + credentials: this.request.withCredentials ? "include" : "same-origin", + body: ["GET", "HEAD"].includes(this.method) ? null : this.requestBody + }); + const proxyHeaders = createProxy(fetchRequest.headers, { + methodCall: ([methodName, args], invoke) => { + switch (methodName) { + case "append": + case "set": { + const [headerName, headerValue] = args; + this.request.setRequestHeader(headerName, headerValue); + break; + } + case "delete": { + const [headerName] = args; + console.warn( + `XMLHttpRequest: Cannot remove a "${headerName}" header from the Fetch API representation of the "${fetchRequest.method} ${fetchRequest.url}" request. XMLHttpRequest headers cannot be removed.` + ); + break; + } + } + return invoke(); + } + }); + define(fetchRequest, "headers", proxyHeaders); + this.logger.info("converted request to a Fetch API Request!", fetchRequest); + return fetchRequest; + } +}; +function toAbsoluteUrl(url) { + if (typeof location === "undefined") { + return new URL(url); + } + return new URL(url.toString(), location.href); +} +function define(target, property, value) { + Reflect.defineProperty(target, property, { + // Ensure writable properties to allow redefining readonly properties. + writable: true, + enumerable: true, + value + }); +} + +// src/interceptors/XMLHttpRequest/XMLHttpRequestProxy.ts +function createXMLHttpRequestProxy({ + emitter, + logger +}) { + const XMLHttpRequestProxy = new Proxy(globalThis.XMLHttpRequest, { + construct(target, args, newTarget) { + logger.info("constructed new XMLHttpRequest"); + const originalRequest = Reflect.construct( + target, + args, + newTarget + ); + const prototypeDescriptors = Object.getOwnPropertyDescriptors( + target.prototype + ); + for (const propertyName in prototypeDescriptors) { + Reflect.defineProperty( + originalRequest, + propertyName, + prototypeDescriptors[propertyName] + ); + } + const xhrRequestController = new XMLHttpRequestController( + originalRequest, + logger + ); + xhrRequestController.onRequest = async function({ request, requestId }) { + const { interactiveRequest, requestController } = toInteractiveRequest(request); + this.logger.info("awaiting mocked response..."); + emitter.once("request", ({ requestId: pendingRequestId }) => { + if (pendingRequestId !== requestId) { + return; + } + if (requestController.responsePromise.state === "pending") { + requestController.respondWith(void 0); + } + }); + const resolverResult = await until(async () => { + this.logger.info( + 'emitting the "request" event for %s listener(s)...', + emitter.listenerCount("request") + ); + await emitAsync(emitter, "request", { + request: interactiveRequest, + requestId + }); + this.logger.info('all "request" listeners settled!'); + const mockedResponse2 = await requestController.responsePromise; + this.logger.info("event.respondWith called with:", mockedResponse2); + return mockedResponse2; + }); + if (resolverResult.error) { + this.logger.info( + "request listener threw an exception, aborting request...", + resolverResult.error + ); + if (resolverResult.error instanceof Response) { + if (isResponseError(resolverResult.error)) { + xhrRequestController.errorWith(new TypeError("Network error")); + } else { + this.respondWith(resolverResult.error); + } + return; + } + if (emitter.listenerCount("unhandledException") > 0) { + await emitAsync(emitter, "unhandledException", { + error: resolverResult.error, + request, + requestId, + controller: { + respondWith: xhrRequestController.respondWith.bind(xhrRequestController), + errorWith: xhrRequestController.errorWith.bind(xhrRequestController) + } + }); + if (originalRequest.readyState > XMLHttpRequest.OPENED) { + return; + } + } + xhrRequestController.respondWith( + createServerErrorResponse(resolverResult.error) + ); + return; + } + const mockedResponse = resolverResult.data; + if (typeof mockedResponse !== "undefined") { + this.logger.info( + "received mocked response: %d %s", + mockedResponse.status, + mockedResponse.statusText + ); + if (isResponseError(mockedResponse)) { + this.logger.info( + "received a network error response, rejecting the request promise..." + ); + xhrRequestController.errorWith(new TypeError("Network error")); + return; + } + return xhrRequestController.respondWith(mockedResponse); + } + this.logger.info( + "no mocked response received, performing request as-is..." + ); + }; + xhrRequestController.onResponse = async function({ + response, + isMockedResponse, + request, + requestId + }) { + this.logger.info( + 'emitting the "response" event for %s listener(s)...', + emitter.listenerCount("response") + ); + emitter.emit("response", { + response, + isMockedResponse, + request, + requestId + }); + }; + return xhrRequestController.request; + } + }); + return XMLHttpRequestProxy; +} + +// src/interceptors/XMLHttpRequest/index.ts +var _XMLHttpRequestInterceptor = class extends Interceptor { + constructor() { + super(_XMLHttpRequestInterceptor.interceptorSymbol); + } + checkEnvironment() { + return typeof globalThis.XMLHttpRequest !== "undefined"; + } + setup() { + const logger = this.logger.extend("setup"); + logger.info('patching "XMLHttpRequest" module...'); + const PureXMLHttpRequest = globalThis.XMLHttpRequest; + invariant2( + !PureXMLHttpRequest[IS_PATCHED_MODULE], + 'Failed to patch the "XMLHttpRequest" module: already patched.' + ); + globalThis.XMLHttpRequest = createXMLHttpRequestProxy({ + emitter: this.emitter, + logger: this.logger + }); + logger.info( + 'native "XMLHttpRequest" module patched!', + globalThis.XMLHttpRequest.name + ); + Object.defineProperty(globalThis.XMLHttpRequest, IS_PATCHED_MODULE, { + enumerable: true, + configurable: true, + value: true + }); + this.subscriptions.push(() => { + Object.defineProperty(globalThis.XMLHttpRequest, IS_PATCHED_MODULE, { + value: void 0 + }); + globalThis.XMLHttpRequest = PureXMLHttpRequest; + logger.info( + 'native "XMLHttpRequest" module restored!', + globalThis.XMLHttpRequest.name + ); + }); + } +}; +var XMLHttpRequestInterceptor = _XMLHttpRequestInterceptor; +XMLHttpRequestInterceptor.interceptorSymbol = Symbol("xhr"); + +export { + XMLHttpRequestInterceptor +}; +//# sourceMappingURL=chunk-732REFPX.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/chunk-732REFPX.mjs.map b/node_modules/@mswjs/interceptors/lib/browser/chunk-732REFPX.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..be0412b37715efb667c94e9820fc418354fc8fb9 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/chunk-732REFPX.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/interceptors/XMLHttpRequest/index.ts","../../src/interceptors/XMLHttpRequest/XMLHttpRequestProxy.ts","../../src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts","../../src/interceptors/XMLHttpRequest/utils/concatArrayBuffer.ts","../../src/interceptors/XMLHttpRequest/polyfills/EventPolyfill.ts","../../src/interceptors/XMLHttpRequest/polyfills/ProgressEventPolyfill.ts","../../src/interceptors/XMLHttpRequest/utils/createEvent.ts","../../src/utils/findPropertySource.ts","../../src/utils/createProxy.ts","../../src/interceptors/XMLHttpRequest/utils/isDomParserSupportedType.ts","../../src/utils/parseJson.ts","../../src/interceptors/XMLHttpRequest/utils/createResponse.ts"],"sourcesContent":["import { invariant } from 'outvariant'\nimport { Emitter } from 'strict-event-emitter'\nimport { HttpRequestEventMap, IS_PATCHED_MODULE } from '../../glossary'\nimport { InteractiveRequest } from '../../utils/toInteractiveRequest'\nimport { Interceptor } from '../../Interceptor'\nimport { createXMLHttpRequestProxy } from './XMLHttpRequestProxy'\n\nexport type XMLHttpRequestEventListener = (args: {\n request: InteractiveRequest\n requestId: string\n}) => Promise | void\n\nexport type XMLHttpRequestEmitter = Emitter\n\nexport class XMLHttpRequestInterceptor extends Interceptor {\n static interceptorSymbol = Symbol('xhr')\n\n constructor() {\n super(XMLHttpRequestInterceptor.interceptorSymbol)\n }\n\n protected checkEnvironment() {\n return typeof globalThis.XMLHttpRequest !== 'undefined'\n }\n\n protected setup() {\n const logger = this.logger.extend('setup')\n\n logger.info('patching \"XMLHttpRequest\" module...')\n\n const PureXMLHttpRequest = globalThis.XMLHttpRequest\n\n invariant(\n !(PureXMLHttpRequest as any)[IS_PATCHED_MODULE],\n 'Failed to patch the \"XMLHttpRequest\" module: already patched.'\n )\n\n globalThis.XMLHttpRequest = createXMLHttpRequestProxy({\n emitter: this.emitter,\n logger: this.logger,\n })\n\n logger.info(\n 'native \"XMLHttpRequest\" module patched!',\n globalThis.XMLHttpRequest.name\n )\n\n Object.defineProperty(globalThis.XMLHttpRequest, IS_PATCHED_MODULE, {\n enumerable: true,\n configurable: true,\n value: true,\n })\n\n this.subscriptions.push(() => {\n Object.defineProperty(globalThis.XMLHttpRequest, IS_PATCHED_MODULE, {\n value: undefined,\n })\n\n globalThis.XMLHttpRequest = PureXMLHttpRequest\n logger.info(\n 'native \"XMLHttpRequest\" module restored!',\n globalThis.XMLHttpRequest.name\n )\n })\n }\n}\n","import { until } from '@open-draft/until'\nimport type { Logger } from '@open-draft/logger'\nimport { XMLHttpRequestEmitter } from '.'\nimport { toInteractiveRequest } from '../../utils/toInteractiveRequest'\nimport { emitAsync } from '../../utils/emitAsync'\nimport { XMLHttpRequestController } from './XMLHttpRequestController'\nimport {\n createServerErrorResponse,\n isResponseError,\n} from '../../utils/responseUtils'\n\nexport interface XMLHttpRequestProxyOptions {\n emitter: XMLHttpRequestEmitter\n logger: Logger\n}\n\n/**\n * Create a proxied `XMLHttpRequest` class.\n * The proxied class establishes spies on certain methods,\n * allowing us to intercept requests and respond to them.\n */\nexport function createXMLHttpRequestProxy({\n emitter,\n logger,\n}: XMLHttpRequestProxyOptions) {\n const XMLHttpRequestProxy = new Proxy(globalThis.XMLHttpRequest, {\n construct(target, args, newTarget) {\n logger.info('constructed new XMLHttpRequest')\n\n const originalRequest = Reflect.construct(\n target,\n args,\n newTarget\n ) as XMLHttpRequest\n\n /**\n * @note Forward prototype descriptors onto the proxied object.\n * XMLHttpRequest is implemented in JSDOM in a way that assigns\n * a bunch of descriptors, like \"set responseType()\" on the prototype.\n * With this propagation, we make sure that those descriptors trigger\n * when the user operates with the proxied request instance.\n */\n const prototypeDescriptors = Object.getOwnPropertyDescriptors(\n target.prototype\n )\n for (const propertyName in prototypeDescriptors) {\n Reflect.defineProperty(\n originalRequest,\n propertyName,\n prototypeDescriptors[propertyName]\n )\n }\n\n const xhrRequestController = new XMLHttpRequestController(\n originalRequest,\n logger\n )\n\n xhrRequestController.onRequest = async function ({ request, requestId }) {\n const { interactiveRequest, requestController } =\n toInteractiveRequest(request)\n\n this.logger.info('awaiting mocked response...')\n\n emitter.once('request', ({ requestId: pendingRequestId }) => {\n if (pendingRequestId !== requestId) {\n return\n }\n\n if (requestController.responsePromise.state === 'pending') {\n requestController.respondWith(undefined)\n }\n })\n\n const resolverResult = await until(async () => {\n this.logger.info(\n 'emitting the \"request\" event for %s listener(s)...',\n emitter.listenerCount('request')\n )\n\n await emitAsync(emitter, 'request', {\n request: interactiveRequest,\n requestId,\n })\n\n this.logger.info('all \"request\" listeners settled!')\n\n const mockedResponse = await requestController.responsePromise\n\n this.logger.info('event.respondWith called with:', mockedResponse)\n\n return mockedResponse\n })\n\n if (resolverResult.error) {\n this.logger.info(\n 'request listener threw an exception, aborting request...',\n resolverResult.error\n )\n\n // Treat thrown Responses as mocked responses.\n if (resolverResult.error instanceof Response) {\n if (isResponseError(resolverResult.error)) {\n xhrRequestController.errorWith(new TypeError('Network error'))\n } else {\n this.respondWith(resolverResult.error)\n }\n\n return\n }\n\n if (emitter.listenerCount('unhandledException') > 0) {\n // Emit the \"unhandledException\" event so the client can opt-out\n // from the default exception handling (producing 500 error responses).\n await emitAsync(emitter, 'unhandledException', {\n error: resolverResult.error,\n request,\n requestId,\n controller: {\n respondWith:\n xhrRequestController.respondWith.bind(xhrRequestController),\n errorWith:\n xhrRequestController.errorWith.bind(xhrRequestController),\n },\n })\n\n // If any of the \"unhandledException\" listeners handled the request,\n // do nothing. Note that mocked responses will dispatch\n // HEADERS_RECEIVED (2), then LOADING (3), and DONE (4) can take\n // time as the mocked response body finishes streaming.\n if (originalRequest.readyState > XMLHttpRequest.OPENED) {\n return\n }\n }\n\n // Unhandled exceptions in the request listeners are\n // synonymous to unhandled exceptions on the server.\n // Those are represented as 500 error responses.\n xhrRequestController.respondWith(\n createServerErrorResponse(resolverResult.error)\n )\n\n return\n }\n\n const mockedResponse = resolverResult.data\n\n if (typeof mockedResponse !== 'undefined') {\n this.logger.info(\n 'received mocked response: %d %s',\n mockedResponse.status,\n mockedResponse.statusText\n )\n\n if (isResponseError(mockedResponse)) {\n this.logger.info(\n 'received a network error response, rejecting the request promise...'\n )\n\n xhrRequestController.errorWith(new TypeError('Network error'))\n return\n }\n\n return xhrRequestController.respondWith(mockedResponse)\n }\n\n this.logger.info(\n 'no mocked response received, performing request as-is...'\n )\n }\n\n xhrRequestController.onResponse = async function ({\n response,\n isMockedResponse,\n request,\n requestId,\n }) {\n this.logger.info(\n 'emitting the \"response\" event for %s listener(s)...',\n emitter.listenerCount('response')\n )\n\n emitter.emit('response', {\n response,\n isMockedResponse,\n request,\n requestId,\n })\n }\n\n // Return the proxied request from the controller\n // so that the controller can react to the consumer's interactions\n // with this request (opening/sending/etc).\n return xhrRequestController.request\n },\n })\n\n return XMLHttpRequestProxy\n}\n","import { invariant } from 'outvariant'\nimport { isNodeProcess } from 'is-node-process'\nimport type { Logger } from '@open-draft/logger'\nimport { concatArrayBuffer } from './utils/concatArrayBuffer'\nimport { createEvent } from './utils/createEvent'\nimport {\n decodeBuffer,\n encodeBuffer,\n toArrayBuffer,\n} from '../../utils/bufferUtils'\nimport { createProxy } from '../../utils/createProxy'\nimport { isDomParserSupportedType } from './utils/isDomParserSupportedType'\nimport { parseJson } from '../../utils/parseJson'\nimport { createResponse } from './utils/createResponse'\nimport { INTERNAL_REQUEST_ID_HEADER_NAME } from '../../Interceptor'\nimport { createRequestId } from '../../createRequestId'\n\nconst IS_MOCKED_RESPONSE = Symbol('isMockedResponse')\nconst IS_NODE = isNodeProcess()\n\n/**\n * An `XMLHttpRequest` instance controller that allows us\n * to handle any given request instance (e.g. responding to it).\n */\nexport class XMLHttpRequestController {\n public request: XMLHttpRequest\n public requestId: string\n public onRequest?: (\n this: XMLHttpRequestController,\n args: {\n request: Request\n requestId: string\n }\n ) => Promise\n public onResponse?: (\n this: XMLHttpRequestController,\n args: {\n response: Response\n isMockedResponse: boolean\n request: Request\n requestId: string\n }\n ) => void\n\n private method: string = 'GET'\n private url: URL = null as any\n private requestHeaders: Headers\n private requestBody?: XMLHttpRequestBodyInit | Document | null\n private responseBuffer: Uint8Array\n private events: Map>\n\n constructor(readonly initialRequest: XMLHttpRequest, public logger: Logger) {\n this.events = new Map()\n this.requestId = createRequestId()\n this.requestHeaders = new Headers()\n this.responseBuffer = new Uint8Array()\n\n this.request = createProxy(initialRequest, {\n setProperty: ([propertyName, nextValue], invoke) => {\n switch (propertyName) {\n case 'ontimeout': {\n const eventName = propertyName.slice(\n 2\n ) as keyof XMLHttpRequestEventTargetEventMap\n\n /**\n * @note Proxy callbacks to event listeners because JSDOM has trouble\n * translating these properties to callbacks. It seemed to be operating\n * on events exclusively.\n */\n this.request.addEventListener(eventName, nextValue as any)\n\n return invoke()\n }\n\n default: {\n return invoke()\n }\n }\n },\n methodCall: ([methodName, args], invoke) => {\n switch (methodName) {\n case 'open': {\n const [method, url] = args as [string, string | undefined]\n\n if (typeof url === 'undefined') {\n this.method = 'GET'\n this.url = toAbsoluteUrl(method)\n } else {\n this.method = method\n this.url = toAbsoluteUrl(url)\n }\n\n this.logger = this.logger.extend(`${this.method} ${this.url.href}`)\n this.logger.info('open', this.method, this.url.href)\n\n return invoke()\n }\n\n case 'addEventListener': {\n const [eventName, listener] = args as [\n keyof XMLHttpRequestEventTargetEventMap,\n Function\n ]\n\n this.registerEvent(eventName, listener)\n this.logger.info('addEventListener', eventName, listener)\n\n return invoke()\n }\n\n case 'setRequestHeader': {\n const [name, value] = args as [string, string]\n this.requestHeaders.set(name, value)\n\n this.logger.info('setRequestHeader', name, value)\n\n return invoke()\n }\n\n case 'send': {\n const [body] = args as [\n body?: XMLHttpRequestBodyInit | Document | null\n ]\n\n if (body != null) {\n this.requestBody =\n typeof body === 'string' ? encodeBuffer(body) : body\n }\n\n this.request.addEventListener('load', () => {\n if (typeof this.onResponse !== 'undefined') {\n // Create a Fetch API Response representation of whichever\n // response this XMLHttpRequest received. Note those may\n // be either a mocked and the original response.\n const fetchResponse = createResponse(\n this.request,\n /**\n * The `response` property is the right way to read\n * the ambiguous response body, as the request's \"responseType\" may differ.\n * @see https://xhr.spec.whatwg.org/#the-response-attribute\n */\n this.request.response\n )\n\n // Notify the consumer about the response.\n this.onResponse.call(this, {\n response: fetchResponse,\n isMockedResponse: IS_MOCKED_RESPONSE in this.request,\n request: fetchRequest,\n requestId: this.requestId!,\n })\n }\n })\n\n // Delegate request handling to the consumer.\n const fetchRequest = this.toFetchApiRequest()\n const onceRequestSettled =\n this.onRequest?.call(this, {\n request: fetchRequest,\n requestId: this.requestId!,\n }) || Promise.resolve()\n\n onceRequestSettled.finally(() => {\n // If the consumer didn't handle the request perform it as-is.\n // Note that the request may not yet be DONE and may, in fact,\n // be LOADING while the \"respondWith\" method does its magic.\n if (this.request.readyState < this.request.LOADING) {\n this.logger.info(\n 'request callback settled but request has not been handled (readystate %d), performing as-is...',\n this.request.readyState\n )\n\n /**\n * @note Set the intercepted request ID on the original request in Node.js\n * so that if it triggers any other interceptors, they don't attempt\n * to process it once again.\n *\n * For instance, XMLHttpRequest is often implemented via \"http.ClientRequest\"\n * and we don't want for both XHR and ClientRequest interceptors to\n * handle the same request at the same time (e.g. emit the \"response\" event twice).\n */\n if (IS_NODE) {\n this.request.setRequestHeader(\n INTERNAL_REQUEST_ID_HEADER_NAME,\n this.requestId!\n )\n }\n\n return invoke()\n }\n })\n\n break\n }\n\n default: {\n return invoke()\n }\n }\n },\n })\n }\n\n private registerEvent(\n eventName: keyof XMLHttpRequestEventTargetEventMap,\n listener: Function\n ): void {\n const prevEvents = this.events.get(eventName) || []\n const nextEvents = prevEvents.concat(listener)\n this.events.set(eventName, nextEvents)\n\n this.logger.info('registered event \"%s\"', eventName, listener)\n }\n\n /**\n * Responds to the current request with the given\n * Fetch API `Response` instance.\n */\n public respondWith(response: Response): void {\n this.logger.info(\n 'responding with a mocked response: %d %s',\n response.status,\n response.statusText\n )\n\n /**\n * @note Since `XMLHttpRequestController` delegates the handling of the responses\n * to the \"load\" event listener that doesn't distinguish between the mocked and original\n * responses, mark the request that had a mocked response with a corresponding symbol.\n */\n define(this.request, IS_MOCKED_RESPONSE, true)\n\n define(this.request, 'status', response.status)\n define(this.request, 'statusText', response.statusText)\n define(this.request, 'responseURL', this.url.href)\n\n this.request.getResponseHeader = new Proxy(this.request.getResponseHeader, {\n apply: (_, __, args: [name: string]) => {\n this.logger.info('getResponseHeader', args[0])\n\n if (this.request.readyState < this.request.HEADERS_RECEIVED) {\n this.logger.info('headers not received yet, returning null')\n\n // Headers not received yet, nothing to return.\n return null\n }\n\n const headerValue = response.headers.get(args[0])\n this.logger.info(\n 'resolved response header \"%s\" to',\n args[0],\n headerValue\n )\n\n return headerValue\n },\n })\n\n this.request.getAllResponseHeaders = new Proxy(\n this.request.getAllResponseHeaders,\n {\n apply: () => {\n this.logger.info('getAllResponseHeaders')\n\n if (this.request.readyState < this.request.HEADERS_RECEIVED) {\n this.logger.info('headers not received yet, returning empty string')\n\n // Headers not received yet, nothing to return.\n return ''\n }\n\n const headersList = Array.from(response.headers.entries())\n const allHeaders = headersList\n .map(([headerName, headerValue]) => {\n return `${headerName}: ${headerValue}`\n })\n .join('\\r\\n')\n\n this.logger.info('resolved all response headers to', allHeaders)\n\n return allHeaders\n },\n }\n )\n\n // Update the response getters to resolve against the mocked response.\n Object.defineProperties(this.request, {\n response: {\n enumerable: true,\n configurable: false,\n get: () => this.response,\n },\n responseText: {\n enumerable: true,\n configurable: false,\n get: () => this.responseText,\n },\n responseXML: {\n enumerable: true,\n configurable: false,\n get: () => this.responseXML,\n },\n })\n\n const totalResponseBodyLength = response.headers.has('Content-Length')\n ? Number(response.headers.get('Content-Length'))\n : /**\n * @todo Infer the response body length from the response body.\n */\n undefined\n\n this.logger.info('calculated response body length', totalResponseBodyLength)\n\n this.trigger('loadstart', {\n loaded: 0,\n total: totalResponseBodyLength,\n })\n\n this.setReadyState(this.request.HEADERS_RECEIVED)\n this.setReadyState(this.request.LOADING)\n\n const finalizeResponse = () => {\n this.logger.info('finalizing the mocked response...')\n\n this.setReadyState(this.request.DONE)\n\n this.trigger('load', {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n\n this.trigger('loadend', {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n }\n\n if (response.body) {\n this.logger.info('mocked response has body, streaming...')\n\n const reader = response.body.getReader()\n\n const readNextResponseBodyChunk = async () => {\n const { value, done } = await reader.read()\n\n if (done) {\n this.logger.info('response body stream done!')\n finalizeResponse()\n return\n }\n\n if (value) {\n this.logger.info('read response body chunk:', value)\n this.responseBuffer = concatArrayBuffer(this.responseBuffer, value)\n\n this.trigger('progress', {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n }\n\n readNextResponseBodyChunk()\n }\n\n readNextResponseBodyChunk()\n } else {\n finalizeResponse()\n }\n }\n\n private responseBufferToText(): string {\n return decodeBuffer(this.responseBuffer)\n }\n\n get response(): unknown {\n this.logger.info(\n 'getResponse (responseType: %s)',\n this.request.responseType\n )\n\n if (this.request.readyState !== this.request.DONE) {\n return null\n }\n\n switch (this.request.responseType) {\n case 'json': {\n const responseJson = parseJson(this.responseBufferToText())\n this.logger.info('resolved response JSON', responseJson)\n\n return responseJson\n }\n\n case 'arraybuffer': {\n const arrayBuffer = toArrayBuffer(this.responseBuffer)\n this.logger.info('resolved response ArrayBuffer', arrayBuffer)\n\n return arrayBuffer\n }\n\n case 'blob': {\n const mimeType =\n this.request.getResponseHeader('Content-Type') || 'text/plain'\n const responseBlob = new Blob([this.responseBufferToText()], {\n type: mimeType,\n })\n\n this.logger.info(\n 'resolved response Blob (mime type: %s)',\n responseBlob,\n mimeType\n )\n\n return responseBlob\n }\n\n default: {\n const responseText = this.responseBufferToText()\n this.logger.info(\n 'resolving \"%s\" response type as text',\n this.request.responseType,\n responseText\n )\n\n return responseText\n }\n }\n }\n\n get responseText(): string {\n /**\n * Throw when trying to read the response body as text when the\n * \"responseType\" doesn't expect text. This just respects the spec better.\n * @see https://xhr.spec.whatwg.org/#the-responsetext-attribute\n */\n invariant(\n this.request.responseType === '' || this.request.responseType === 'text',\n 'InvalidStateError: The object is in invalid state.'\n )\n\n if (\n this.request.readyState !== this.request.LOADING &&\n this.request.readyState !== this.request.DONE\n ) {\n return ''\n }\n\n const responseText = this.responseBufferToText()\n this.logger.info('getResponseText: \"%s\"', responseText)\n\n return responseText\n }\n\n get responseXML(): Document | null {\n invariant(\n this.request.responseType === '' ||\n this.request.responseType === 'document',\n 'InvalidStateError: The object is in invalid state.'\n )\n\n if (this.request.readyState !== this.request.DONE) {\n return null\n }\n\n const contentType = this.request.getResponseHeader('Content-Type') || ''\n\n if (typeof DOMParser === 'undefined') {\n console.warn(\n 'Cannot retrieve XMLHttpRequest response body as XML: DOMParser is not defined. You are likely using an environment that is not browser or does not polyfill browser globals correctly.'\n )\n return null\n }\n\n if (isDomParserSupportedType(contentType)) {\n return new DOMParser().parseFromString(\n this.responseBufferToText(),\n contentType\n )\n }\n\n return null\n }\n\n public errorWith(error: Error): void {\n this.logger.info('responding with an error')\n\n this.setReadyState(this.request.DONE)\n this.trigger('error')\n this.trigger('loadend')\n }\n\n /**\n * Transitions this request's `readyState` to the given one.\n */\n private setReadyState(nextReadyState: number): void {\n this.logger.info(\n 'setReadyState: %d -> %d',\n this.request.readyState,\n nextReadyState\n )\n\n if (this.request.readyState === nextReadyState) {\n this.logger.info('ready state identical, skipping transition...')\n return\n }\n\n define(this.request, 'readyState', nextReadyState)\n\n this.logger.info('set readyState to: %d', nextReadyState)\n\n if (nextReadyState !== this.request.UNSENT) {\n this.logger.info('triggerring \"readystatechange\" event...')\n\n this.trigger('readystatechange')\n }\n }\n\n /**\n * Triggers given event on the `XMLHttpRequest` instance.\n */\n private trigger<\n EventName extends keyof (XMLHttpRequestEventTargetEventMap & {\n readystatechange: ProgressEvent\n })\n >(eventName: EventName, options?: ProgressEventInit): void {\n const callback = this.request[`on${eventName}`]\n const event = createEvent(this.request, eventName, options)\n\n this.logger.info('trigger \"%s\"', eventName, options || '')\n\n // Invoke direct callbacks.\n if (typeof callback === 'function') {\n this.logger.info('found a direct \"%s\" callback, calling...', eventName)\n callback.call(this.request, event)\n }\n\n // Invoke event listeners.\n for (const [registeredEventName, listeners] of this.events) {\n if (registeredEventName === eventName) {\n this.logger.info(\n 'found %d listener(s) for \"%s\" event, calling...',\n listeners.length,\n eventName\n )\n\n listeners.forEach((listener) => listener.call(this.request, event))\n }\n }\n }\n\n /**\n * Converts this `XMLHttpRequest` instance into a Fetch API `Request` instance.\n */\n public toFetchApiRequest(): Request {\n this.logger.info('converting request to a Fetch API Request...')\n\n const fetchRequest = new Request(this.url.href, {\n method: this.method,\n headers: this.requestHeaders,\n /**\n * @see https://xhr.spec.whatwg.org/#cross-origin-credentials\n */\n credentials: this.request.withCredentials ? 'include' : 'same-origin',\n body: ['GET', 'HEAD'].includes(this.method)\n ? null\n : (this.requestBody as BodyInit),\n })\n\n const proxyHeaders = createProxy(fetchRequest.headers, {\n methodCall: ([methodName, args], invoke) => {\n // Forward the latest state of the internal request headers\n // because the interceptor might have modified them\n // without responding to the request.\n switch (methodName) {\n case 'append':\n case 'set': {\n const [headerName, headerValue] = args as [string, string]\n this.request.setRequestHeader(headerName, headerValue)\n break\n }\n\n case 'delete': {\n const [headerName] = args as [string]\n console.warn(\n `XMLHttpRequest: Cannot remove a \"${headerName}\" header from the Fetch API representation of the \"${fetchRequest.method} ${fetchRequest.url}\" request. XMLHttpRequest headers cannot be removed.`\n )\n break\n }\n }\n\n return invoke()\n },\n })\n define(fetchRequest, 'headers', proxyHeaders)\n\n this.logger.info('converted request to a Fetch API Request!', fetchRequest)\n\n return fetchRequest\n }\n}\n\nfunction toAbsoluteUrl(url: string | URL): URL {\n /**\n * @note XMLHttpRequest interceptor may run in environments\n * that implement XMLHttpRequest but don't implement \"location\"\n * (for example, React Native). If that's the case, return the\n * input URL as-is (nothing to be relative to).\n * @see https://github.com/mswjs/msw/issues/1777\n */\n if (typeof location === 'undefined') {\n return new URL(url)\n }\n\n return new URL(url.toString(), location.href)\n}\n\nfunction define(\n target: object,\n property: string | symbol,\n value: unknown\n): void {\n Reflect.defineProperty(target, property, {\n // Ensure writable properties to allow redefining readonly properties.\n writable: true,\n enumerable: true,\n value,\n })\n}\n","/**\n * Concatenate two `Uint8Array` buffers.\n */\nexport function concatArrayBuffer(\n left: Uint8Array,\n right: Uint8Array\n): Uint8Array {\n const result = new Uint8Array(left.byteLength + right.byteLength)\n result.set(left, 0)\n result.set(right, left.byteLength)\n return result\n}\n","export class EventPolyfill implements Event {\n readonly AT_TARGET: number = 0\n readonly BUBBLING_PHASE: number = 0\n readonly CAPTURING_PHASE: number = 0\n readonly NONE: number = 0\n\n public type: string = ''\n public srcElement: EventTarget | null = null\n public target: EventTarget | null\n public currentTarget: EventTarget | null = null\n public eventPhase: number = 0\n public timeStamp: number\n public isTrusted: boolean = true\n public composed: boolean = false\n public cancelable: boolean = true\n public defaultPrevented: boolean = false\n public bubbles: boolean = true\n public lengthComputable: boolean = true\n public loaded: number = 0\n public total: number = 0\n\n cancelBubble: boolean = false\n returnValue: boolean = true\n\n constructor(\n type: string,\n options?: { target: EventTarget; currentTarget: EventTarget }\n ) {\n this.type = type\n this.target = options?.target || null\n this.currentTarget = options?.currentTarget || null\n this.timeStamp = Date.now()\n }\n\n public composedPath(): EventTarget[] {\n return []\n }\n\n public initEvent(type: string, bubbles?: boolean, cancelable?: boolean) {\n this.type = type\n this.bubbles = !!bubbles\n this.cancelable = !!cancelable\n }\n\n public preventDefault() {\n this.defaultPrevented = true\n }\n\n public stopPropagation() {}\n public stopImmediatePropagation() {}\n}\n","import { EventPolyfill } from './EventPolyfill'\n\nexport class ProgressEventPolyfill extends EventPolyfill {\n readonly lengthComputable: boolean\n readonly composed: boolean\n readonly loaded: number\n readonly total: number\n\n constructor(type: string, init?: ProgressEventInit) {\n super(type)\n\n this.lengthComputable = init?.lengthComputable || false\n this.composed = init?.composed || false\n this.loaded = init?.loaded || 0\n this.total = init?.total || 0\n }\n}\n","import { EventPolyfill } from '../polyfills/EventPolyfill'\nimport { ProgressEventPolyfill } from '../polyfills/ProgressEventPolyfill'\n\nconst SUPPORTS_PROGRESS_EVENT = typeof ProgressEvent !== 'undefined'\n\nexport function createEvent(\n target: XMLHttpRequest,\n type: string,\n init?: ProgressEventInit\n): EventPolyfill {\n const progressEvents = [\n 'error',\n 'progress',\n 'loadstart',\n 'loadend',\n 'load',\n 'timeout',\n 'abort',\n ]\n\n /**\n * `ProgressEvent` is not supported in React Native.\n * @see https://github.com/mswjs/interceptors/issues/40\n */\n const ProgressEventClass = SUPPORTS_PROGRESS_EVENT\n ? ProgressEvent\n : ProgressEventPolyfill\n\n const event = progressEvents.includes(type)\n ? new ProgressEventClass(type, {\n lengthComputable: true,\n loaded: init?.loaded || 0,\n total: init?.total || 0,\n })\n : new EventPolyfill(type, {\n target,\n currentTarget: target,\n })\n\n return event\n}\n","/**\n * Returns the source object of the given property on the target object\n * (the target itself, any parent in its prototype, or null).\n */\nexport function findPropertySource(\n target: object,\n propertyName: string | symbol\n): object | null {\n if (!(propertyName in target)) {\n return null\n }\n\n const hasProperty = Object.prototype.hasOwnProperty.call(target, propertyName)\n if (hasProperty) {\n return target\n }\n\n const prototype = Reflect.getPrototypeOf(target)\n return prototype ? findPropertySource(prototype, propertyName) : null\n}\n","import { findPropertySource } from './findPropertySource'\n\nexport interface ProxyOptions> {\n constructorCall?(args: Array, next: NextFunction): Target\n\n methodCall?(\n this: Target,\n data: [methodName: F, args: Array],\n next: NextFunction\n ): void\n\n setProperty?(\n data: [propertyName: string | symbol, nextValue: unknown],\n next: NextFunction\n ): boolean\n\n getProperty?(\n data: [propertyName: string | symbol, receiver: Target],\n next: NextFunction\n ): void\n}\n\nexport type NextFunction = () => ReturnType\n\nexport function createProxy(\n target: Target,\n options: ProxyOptions\n): Target {\n const proxy = new Proxy(target, optionsToProxyHandler(options))\n\n return proxy\n}\n\nfunction optionsToProxyHandler>(\n options: ProxyOptions\n): ProxyHandler {\n const { constructorCall, methodCall, getProperty, setProperty } = options\n const handler: ProxyHandler = {}\n\n if (typeof constructorCall !== 'undefined') {\n handler.construct = function (target, args, newTarget) {\n const next = Reflect.construct.bind(null, target as any, args, newTarget)\n return constructorCall.call(newTarget, args, next)\n }\n }\n\n handler.set = function (target, propertyName, nextValue) {\n const next = () => {\n const propertySource = findPropertySource(target, propertyName) || target\n const ownDescriptors = Reflect.getOwnPropertyDescriptor(\n propertySource,\n propertyName\n )\n\n // Respect any custom setters present for this property.\n if (typeof ownDescriptors?.set !== 'undefined') {\n ownDescriptors.set.apply(target, [nextValue])\n return true\n }\n\n // Otherwise, set the property on the source.\n return Reflect.defineProperty(propertySource, propertyName, {\n writable: true,\n enumerable: true,\n configurable: true,\n value: nextValue,\n })\n }\n\n if (typeof setProperty !== 'undefined') {\n return setProperty.call(target, [propertyName, nextValue], next)\n }\n\n return next()\n }\n\n handler.get = function (target, propertyName, receiver) {\n /**\n * @note Using `Reflect.get()` here causes \"TypeError: Illegal invocation\".\n */\n const next = () => target[propertyName as any]\n\n const value =\n typeof getProperty !== 'undefined'\n ? getProperty.call(target, [propertyName, receiver], next)\n : next()\n\n if (typeof value === 'function') {\n return (...args: Array) => {\n const next = value.bind(target, ...args)\n\n if (typeof methodCall !== 'undefined') {\n return methodCall.call(target, [propertyName as any, args], next)\n }\n\n return next()\n }\n }\n\n return value\n }\n\n return handler\n}\n","export function isDomParserSupportedType(\n type: string\n): type is DOMParserSupportedType {\n const supportedTypes: Array = [\n 'application/xhtml+xml',\n 'application/xml',\n 'image/svg+xml',\n 'text/html',\n 'text/xml',\n ]\n return supportedTypes.some((supportedType) => {\n return type.startsWith(supportedType)\n })\n}\n","/**\n * Parses a given string into JSON.\n * Gracefully handles invalid JSON by returning `null`.\n */\nexport function parseJson(data: string): Record | null {\n try {\n const json = JSON.parse(data)\n return json\n } catch (_) {\n return null\n }\n}\n","import { isResponseWithoutBody } from '../../../utils/responseUtils'\n\n/**\n * Creates a Fetch API `Response` instance from the given\n * `XMLHttpRequest` instance and a response body.\n */\nexport function createResponse(\n request: XMLHttpRequest,\n body: BodyInit | null\n): Response {\n /**\n * Handle XMLHttpRequest responses that must have null as the\n * response body when represented using Fetch API Response.\n * XMLHttpRequest response will always have an empty string\n * as the \"request.response\" in those cases, resulting in an error\n * when constructing a Response instance.\n * @see https://github.com/mswjs/interceptors/issues/379\n */\n const responseBodyOrNull = isResponseWithoutBody(request.status) ? null : body\n\n return new Response(responseBodyOrNull, {\n status: request.status,\n statusText: request.statusText,\n headers: createHeadersFromXMLHttpReqestHeaders(\n request.getAllResponseHeaders()\n ),\n })\n}\n\nfunction createHeadersFromXMLHttpReqestHeaders(headersString: string): Headers {\n const headers = new Headers()\n\n const lines = headersString.split(/[\\r\\n]+/)\n for (const line of lines) {\n if (line.trim() === '') {\n continue\n }\n\n const [name, ...parts] = line.split(': ')\n const value = parts.join(': ')\n\n headers.append(name, value)\n }\n\n return headers\n}\n"],"mappings":"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","names":["invariant","next","mockedResponse","invariant"]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/chunk-LK6DILFK.js b/node_modules/@mswjs/interceptors/lib/browser/chunk-LK6DILFK.js new file mode 100644 index 0000000000000000000000000000000000000000..f41d9eae5715ee544bf3d8f597fd16e59a271f58 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/chunk-LK6DILFK.js @@ -0,0 +1,22 @@ +"use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/utils/bufferUtils.ts +var encoder = new TextEncoder(); +function encodeBuffer(text) { + return encoder.encode(text); +} +function decodeBuffer(buffer, encoding) { + const decoder = new TextDecoder(encoding); + return decoder.decode(buffer); +} +function toArrayBuffer(array) { + return array.buffer.slice( + array.byteOffset, + array.byteOffset + array.byteLength + ); +} + + + + + +exports.encodeBuffer = encodeBuffer; exports.decodeBuffer = decodeBuffer; exports.toArrayBuffer = toArrayBuffer; +//# sourceMappingURL=chunk-LK6DILFK.js.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/chunk-LK6DILFK.js.map b/node_modules/@mswjs/interceptors/lib/browser/chunk-LK6DILFK.js.map new file mode 100644 index 0000000000000000000000000000000000000000..691683680b4e26eecaa7dfe2d0466c8f348eb21f --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/chunk-LK6DILFK.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/utils/bufferUtils.ts"],"names":[],"mappings":";AAAA,IAAM,UAAU,IAAI,YAAY;AAEzB,SAAS,aAAa,MAA0B;AACrD,SAAO,QAAQ,OAAO,IAAI;AAC5B;AAEO,SAAS,aAAa,QAAqB,UAA2B;AAC3E,QAAM,UAAU,IAAI,YAAY,QAAQ;AACxC,SAAO,QAAQ,OAAO,MAAM;AAC9B;AAOO,SAAS,cAAc,OAAgC;AAC5D,SAAO,MAAM,OAAO;AAAA,IAClB,MAAM;AAAA,IACN,MAAM,aAAa,MAAM;AAAA,EAC3B;AACF","sourcesContent":["const encoder = new TextEncoder()\n\nexport function encodeBuffer(text: string): Uint8Array {\n return encoder.encode(text)\n}\n\nexport function decodeBuffer(buffer: ArrayBuffer, encoding?: string): string {\n const decoder = new TextDecoder(encoding)\n return decoder.decode(buffer)\n}\n\n/**\n * Create an `ArrayBuffer` from the given `Uint8Array`.\n * Takes the byte offset into account to produce the right buffer\n * in the case when the buffer is bigger than the data view.\n */\nexport function toArrayBuffer(array: Uint8Array): ArrayBuffer {\n return array.buffer.slice(\n array.byteOffset,\n array.byteOffset + array.byteLength\n )\n}\n"]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/chunk-MAEPOYB6.mjs b/node_modules/@mswjs/interceptors/lib/browser/chunk-MAEPOYB6.mjs new file mode 100644 index 0000000000000000000000000000000000000000..dec67193b3c891b3c6bfa0c447695a5865ada297 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/chunk-MAEPOYB6.mjs @@ -0,0 +1,213 @@ +import { + emitAsync, + toInteractiveRequest +} from "./chunk-OUWBQF3Z.mjs"; +import { + IS_PATCHED_MODULE, + createServerErrorResponse, + isResponseError +} from "./chunk-OMISYKWR.mjs"; +import { + Interceptor, + createRequestId +} from "./chunk-QED3Q6Z2.mjs"; + +// src/interceptors/fetch/index.ts +import { invariant } from "outvariant"; +import { DeferredPromise } from "@open-draft/deferred-promise"; +import { until } from "@open-draft/until"; + +// src/utils/canParseUrl.ts +function canParseUrl(url) { + try { + new URL(url); + return true; + } catch (_error) { + return false; + } +} + +// src/interceptors/fetch/index.ts +var _FetchInterceptor = class extends Interceptor { + constructor() { + super(_FetchInterceptor.symbol); + } + checkEnvironment() { + return typeof globalThis !== "undefined" && typeof globalThis.fetch !== "undefined"; + } + async setup() { + const pureFetch = globalThis.fetch; + invariant( + !pureFetch[IS_PATCHED_MODULE], + 'Failed to patch the "fetch" module: already patched.' + ); + globalThis.fetch = async (input, init) => { + var _a; + const requestId = createRequestId(); + const resolvedInput = typeof input === "string" && typeof location !== "undefined" && !canParseUrl(input) ? new URL(input, location.origin) : input; + const request = new Request(resolvedInput, init); + this.logger.info("[%s] %s", request.method, request.url); + const { interactiveRequest, requestController } = toInteractiveRequest(request); + this.logger.info( + 'emitting the "request" event for %d listener(s)...', + this.emitter.listenerCount("request") + ); + this.emitter.once("request", ({ requestId: pendingRequestId }) => { + if (pendingRequestId !== requestId) { + return; + } + if (requestController.responsePromise.state === "pending") { + requestController.responsePromise.resolve(void 0); + } + }); + this.logger.info("awaiting for the mocked response..."); + const signal = interactiveRequest.signal; + const requestAborted = new DeferredPromise(); + if (signal) { + signal.addEventListener( + "abort", + () => { + requestAborted.reject(signal.reason); + }, + { once: true } + ); + } + const responsePromise = new DeferredPromise(); + const respondWith = (response) => { + this.logger.info("responding with a mock response:", response); + if (this.emitter.listenerCount("response") > 0) { + this.logger.info('emitting the "response" event...'); + const responseClone = response.clone(); + this.emitter.emit("response", { + response: responseClone, + isMockedResponse: true, + request: interactiveRequest, + requestId + }); + } + Object.defineProperty(response, "url", { + writable: false, + enumerable: true, + configurable: false, + value: request.url + }); + responsePromise.resolve(response); + }; + const errorWith = (reason) => { + responsePromise.reject(reason); + }; + const resolverResult = await until( + async () => { + const listenersFinished = emitAsync(this.emitter, "request", { + request: interactiveRequest, + requestId + }); + await Promise.race([ + requestAborted, + // Put the listeners invocation Promise in the same race condition + // with the request abort Promise because otherwise awaiting the listeners + // would always yield some response (or undefined). + listenersFinished, + requestController.responsePromise + ]); + this.logger.info("all request listeners have been resolved!"); + const mockedResponse2 = await requestController.responsePromise; + this.logger.info("event.respondWith called with:", mockedResponse2); + return mockedResponse2; + } + ); + if (requestAborted.state === "rejected") { + this.logger.info( + "request has been aborted:", + requestAborted.rejectionReason + ); + responsePromise.reject(requestAborted.rejectionReason); + return responsePromise; + } + if (resolverResult.error) { + this.logger.info( + "request listerner threw an error:", + resolverResult.error + ); + if (resolverResult.error instanceof Response) { + if (isResponseError(resolverResult.error)) { + errorWith(createNetworkError(resolverResult.error)); + } else { + respondWith(resolverResult.error); + } + } + if (this.emitter.listenerCount("unhandledException") > 0) { + await emitAsync(this.emitter, "unhandledException", { + error: resolverResult.error, + request, + requestId, + controller: { + respondWith, + errorWith + } + }); + if (responsePromise.state !== "pending") { + return responsePromise; + } + } + respondWith(createServerErrorResponse(resolverResult.error)); + return responsePromise; + } + const mockedResponse = resolverResult.data; + if (mockedResponse && !((_a = request.signal) == null ? void 0 : _a.aborted)) { + this.logger.info("received mocked response:", mockedResponse); + if (isResponseError(mockedResponse)) { + this.logger.info( + "received a network error response, rejecting the request promise..." + ); + errorWith(createNetworkError(mockedResponse)); + } else { + respondWith(mockedResponse); + } + return responsePromise; + } + this.logger.info("no mocked response received!"); + return pureFetch(request).then((response) => { + this.logger.info("original fetch performed", response); + if (this.emitter.listenerCount("response") > 0) { + this.logger.info('emitting the "response" event...'); + const responseClone = response.clone(); + this.emitter.emit("response", { + response: responseClone, + isMockedResponse: false, + request: interactiveRequest, + requestId + }); + } + return response; + }); + }; + Object.defineProperty(globalThis.fetch, IS_PATCHED_MODULE, { + enumerable: true, + configurable: true, + value: true + }); + this.subscriptions.push(() => { + Object.defineProperty(globalThis.fetch, IS_PATCHED_MODULE, { + value: void 0 + }); + globalThis.fetch = pureFetch; + this.logger.info( + 'restored native "globalThis.fetch"!', + globalThis.fetch.name + ); + }); + } +}; +var FetchInterceptor = _FetchInterceptor; +FetchInterceptor.symbol = Symbol("fetch"); +function createNetworkError(cause) { + return Object.assign(new TypeError("Failed to fetch"), { + cause + }); +} + +export { + FetchInterceptor +}; +//# sourceMappingURL=chunk-MAEPOYB6.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/chunk-MAEPOYB6.mjs.map b/node_modules/@mswjs/interceptors/lib/browser/chunk-MAEPOYB6.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..fed7d7cfb64be82c23937a7c1f7bb0028657c8f6 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/chunk-MAEPOYB6.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/interceptors/fetch/index.ts","../../src/utils/canParseUrl.ts"],"sourcesContent":["import { invariant } from 'outvariant'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { until } from '@open-draft/until'\nimport { HttpRequestEventMap, IS_PATCHED_MODULE } from '../../glossary'\nimport { Interceptor } from '../../Interceptor'\nimport { toInteractiveRequest } from '../../utils/toInteractiveRequest'\nimport { emitAsync } from '../../utils/emitAsync'\nimport { canParseUrl } from '../../utils/canParseUrl'\nimport { createRequestId } from '../../createRequestId'\nimport {\n createServerErrorResponse,\n isResponseError,\n} from '../../utils/responseUtils'\n\nexport class FetchInterceptor extends Interceptor {\n static symbol = Symbol('fetch')\n\n constructor() {\n super(FetchInterceptor.symbol)\n }\n\n protected checkEnvironment() {\n return (\n typeof globalThis !== 'undefined' &&\n typeof globalThis.fetch !== 'undefined'\n )\n }\n\n protected async setup() {\n const pureFetch = globalThis.fetch\n\n invariant(\n !(pureFetch as any)[IS_PATCHED_MODULE],\n 'Failed to patch the \"fetch\" module: already patched.'\n )\n\n globalThis.fetch = async (input, init) => {\n const requestId = createRequestId()\n\n /**\n * @note Resolve potentially relative request URL\n * against the present `location`. This is mainly\n * for native `fetch` in JSDOM.\n * @see https://github.com/mswjs/msw/issues/1625\n */\n const resolvedInput =\n typeof input === 'string' &&\n typeof location !== 'undefined' &&\n !canParseUrl(input)\n ? new URL(input, location.origin)\n : input\n\n const request = new Request(resolvedInput, init)\n\n this.logger.info('[%s] %s', request.method, request.url)\n\n const { interactiveRequest, requestController } =\n toInteractiveRequest(request)\n\n this.logger.info(\n 'emitting the \"request\" event for %d listener(s)...',\n this.emitter.listenerCount('request')\n )\n\n this.emitter.once('request', ({ requestId: pendingRequestId }) => {\n if (pendingRequestId !== requestId) {\n return\n }\n\n if (requestController.responsePromise.state === 'pending') {\n requestController.responsePromise.resolve(undefined)\n }\n })\n\n this.logger.info('awaiting for the mocked response...')\n\n const signal = interactiveRequest.signal\n const requestAborted = new DeferredPromise()\n\n // Signal isn't always defined in react-native.\n if (signal) {\n signal.addEventListener(\n 'abort',\n () => {\n requestAborted.reject(signal.reason)\n },\n { once: true }\n )\n }\n\n const responsePromise = new DeferredPromise()\n\n const respondWith = (response: Response): void => {\n this.logger.info('responding with a mock response:', response)\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n // Clone the mocked response for the \"response\" event listener.\n // This way, the listener can read the response and not lock its body\n // for the actual fetch consumer.\n const responseClone = response.clone()\n\n this.emitter.emit('response', {\n response: responseClone,\n isMockedResponse: true,\n request: interactiveRequest,\n requestId,\n })\n }\n\n // Set the \"response.url\" property to equal the intercepted request URL.\n Object.defineProperty(response, 'url', {\n writable: false,\n enumerable: true,\n configurable: false,\n value: request.url,\n })\n\n responsePromise.resolve(response)\n }\n\n const errorWith = (reason: unknown): void => {\n responsePromise.reject(reason)\n }\n\n const resolverResult = await until(\n async () => {\n const listenersFinished = emitAsync(this.emitter, 'request', {\n request: interactiveRequest,\n requestId,\n })\n\n await Promise.race([\n requestAborted,\n // Put the listeners invocation Promise in the same race condition\n // with the request abort Promise because otherwise awaiting the listeners\n // would always yield some response (or undefined).\n listenersFinished,\n requestController.responsePromise,\n ])\n\n this.logger.info('all request listeners have been resolved!')\n\n const mockedResponse = await requestController.responsePromise\n this.logger.info('event.respondWith called with:', mockedResponse)\n\n return mockedResponse\n }\n )\n\n if (requestAborted.state === 'rejected') {\n this.logger.info(\n 'request has been aborted:',\n requestAborted.rejectionReason\n )\n\n responsePromise.reject(requestAborted.rejectionReason)\n return responsePromise\n }\n\n if (resolverResult.error) {\n this.logger.info(\n 'request listerner threw an error:',\n resolverResult.error\n )\n\n // Treat thrown Responses as mocked responses.\n if (resolverResult.error instanceof Response) {\n // Treat thrown Response.error() as a request error.\n if (isResponseError(resolverResult.error)) {\n errorWith(createNetworkError(resolverResult.error))\n } else {\n // Treat the rest of thrown Responses as mocked responses.\n respondWith(resolverResult.error)\n }\n }\n\n // Emit the \"unhandledException\" interceptor event so the client\n // can opt-out from exceptions translating to 500 error responses.\n\n if (this.emitter.listenerCount('unhandledException') > 0) {\n await emitAsync(this.emitter, 'unhandledException', {\n error: resolverResult.error,\n request,\n requestId,\n controller: {\n respondWith,\n errorWith,\n },\n })\n\n if (responsePromise.state !== 'pending') {\n return responsePromise\n }\n }\n\n // Unhandled exceptions in the request listeners are\n // synonymous to unhandled exceptions on the server.\n // Those are represented as 500 error responses.\n respondWith(createServerErrorResponse(resolverResult.error))\n return responsePromise\n }\n\n const mockedResponse = resolverResult.data\n\n if (mockedResponse && !request.signal?.aborted) {\n this.logger.info('received mocked response:', mockedResponse)\n\n // Reject the request Promise on mocked \"Response.error\" responses.\n if (isResponseError(mockedResponse)) {\n this.logger.info(\n 'received a network error response, rejecting the request promise...'\n )\n\n /**\n * Set the cause of the request promise rejection to the\n * network error Response instance. This differs from Undici.\n * Undici will forward the \"response.error\" custom property\n * as the rejection reason but for \"Response.error()\" static method\n * \"response.error\" will equal to undefined, making \"cause\" an empty Error.\n * @see https://github.com/nodejs/undici/blob/83cb522ae0157a19d149d72c7d03d46e34510d0a/lib/fetch/response.js#L344\n */\n errorWith(createNetworkError(mockedResponse))\n } else {\n respondWith(mockedResponse)\n }\n\n return responsePromise\n }\n\n this.logger.info('no mocked response received!')\n\n return pureFetch(request).then((response) => {\n this.logger.info('original fetch performed', response)\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n const responseClone = response.clone()\n\n this.emitter.emit('response', {\n response: responseClone,\n isMockedResponse: false,\n request: interactiveRequest,\n requestId,\n })\n }\n\n return response\n })\n }\n\n Object.defineProperty(globalThis.fetch, IS_PATCHED_MODULE, {\n enumerable: true,\n configurable: true,\n value: true,\n })\n\n this.subscriptions.push(() => {\n Object.defineProperty(globalThis.fetch, IS_PATCHED_MODULE, {\n value: undefined,\n })\n\n globalThis.fetch = pureFetch\n\n this.logger.info(\n 'restored native \"globalThis.fetch\"!',\n globalThis.fetch.name\n )\n })\n }\n}\n\nfunction createNetworkError(cause: unknown) {\n return Object.assign(new TypeError('Failed to fetch'), {\n cause,\n })\n}\n","/**\n * Returns a boolean indicating whether the given URL string\n * can be parsed into a `URL` instance.\n * A substitute for `URL.canParse()` for Node.js 18.\n */\nexport function canParseUrl(url: string): boolean {\n try {\n new URL(url)\n return true\n } catch (_error) {\n return false\n }\n}\n"],"mappings":"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","names":["mockedResponse"]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/chunk-MQJ3JOOK.js b/node_modules/@mswjs/interceptors/lib/browser/chunk-MQJ3JOOK.js new file mode 100644 index 0000000000000000000000000000000000000000..97c07c992c5b0f7f959cf10ace5cef097d5ae577 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/chunk-MQJ3JOOK.js @@ -0,0 +1,49 @@ +"use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/utils/RequestController.ts +var _outvariant = require('outvariant'); +var _deferredpromise = require('@open-draft/deferred-promise'); +var RequestController = class { + constructor(request) { + this.request = request; + this.responsePromise = new (0, _deferredpromise.DeferredPromise)(); + } + respondWith(response) { + _outvariant.invariant.call(void 0, + this.responsePromise.state === "pending", + 'Failed to respond to "%s %s" request: the "request" event has already been responded to.', + this.request.method, + this.request.url + ); + this.responsePromise.resolve(response); + } +}; + +// src/utils/toInteractiveRequest.ts +function toInteractiveRequest(request) { + const requestController = new RequestController(request); + Reflect.set( + request, + "respondWith", + requestController.respondWith.bind(requestController) + ); + return { + interactiveRequest: request, + requestController + }; +} + +// src/utils/emitAsync.ts +async function emitAsync(emitter, eventName, ...data) { + const listners = emitter.listeners(eventName); + if (listners.length === 0) { + return; + } + for (const listener of listners) { + await listener.apply(emitter, data); + } +} + + + + +exports.toInteractiveRequest = toInteractiveRequest; exports.emitAsync = emitAsync; +//# sourceMappingURL=chunk-MQJ3JOOK.js.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/chunk-MQJ3JOOK.js.map b/node_modules/@mswjs/interceptors/lib/browser/chunk-MQJ3JOOK.js.map new file mode 100644 index 0000000000000000000000000000000000000000..300c2a93afe208427c3fc164257f75747e843566 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/chunk-MQJ3JOOK.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/utils/RequestController.ts","../../src/utils/toInteractiveRequest.ts","../../src/utils/emitAsync.ts"],"names":[],"mappings":";AAAA,SAAS,iBAAiB;AAC1B,SAAS,uBAAuB;AAEzB,IAAM,oBAAN,MAAwB;AAAA,EAG7B,YAAsB,SAAkB;AAAlB;AACpB,SAAK,kBAAkB,IAAI,gBAAgB;AAAA,EAC7C;AAAA,EAEO,YAAY,UAA2B;AAC5C;AAAA,MACE,KAAK,gBAAgB,UAAU;AAAA,MAC/B;AAAA,MACA,KAAK,QAAQ;AAAA,MACb,KAAK,QAAQ;AAAA,IACf;AAEA,SAAK,gBAAgB,QAAQ,QAAQ;AAAA,EACvC;AACF;;;ACdO,SAAS,qBAAqB,SAGnC;AACA,QAAM,oBAAoB,IAAI,kBAAkB,OAAO;AAEvD,UAAQ;AAAA,IACN;AAAA,IACA;AAAA,IACA,kBAAkB,YAAY,KAAK,iBAAiB;AAAA,EACtD;AAEA,SAAO;AAAA,IACL,oBAAoB;AAAA,IACpB;AAAA,EACF;AACF;;;ACfA,eAAsB,UAIpB,SACA,cACG,MACY;AACf,QAAM,WAAW,QAAQ,UAAU,SAAS;AAE5C,MAAI,SAAS,WAAW,GAAG;AACzB;AAAA,EACF;AAEA,aAAW,YAAY,UAAU;AAC/B,UAAM,SAAS,MAAM,SAAS,IAAI;AAAA,EACpC;AACF","sourcesContent":["import { invariant } from 'outvariant'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\n\nexport class RequestController {\n public responsePromise: DeferredPromise\n\n constructor(protected request: Request) {\n this.responsePromise = new DeferredPromise()\n }\n\n public respondWith(response?: Response): void {\n invariant(\n this.responsePromise.state === 'pending',\n 'Failed to respond to \"%s %s\" request: the \"request\" event has already been responded to.',\n this.request.method,\n this.request.url\n )\n\n this.responsePromise.resolve(response)\n }\n}\n","import { RequestController } from './RequestController'\n\nexport type InteractiveRequest = globalThis.Request & {\n respondWith: RequestController['respondWith']\n}\n\nexport function toInteractiveRequest(request: Request): {\n interactiveRequest: InteractiveRequest\n requestController: RequestController\n} {\n const requestController = new RequestController(request)\n\n Reflect.set(\n request,\n 'respondWith',\n requestController.respondWith.bind(requestController)\n )\n\n return {\n interactiveRequest: request as InteractiveRequest,\n requestController,\n }\n}\n","import { Emitter, EventMap } from 'strict-event-emitter'\n\n/**\n * Emits an event on the given emitter but executes\n * the listeners sequentially. This accounts for asynchronous\n * listeners (e.g. those having \"sleep\" and handling the request).\n */\nexport async function emitAsync<\n Events extends EventMap,\n EventName extends keyof Events\n>(\n emitter: Emitter,\n eventName: EventName,\n ...data: Events[EventName]\n): Promise {\n const listners = emitter.listeners(eventName)\n\n if (listners.length === 0) {\n return\n }\n\n for (const listener of listners) {\n await listener.apply(emitter, data)\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/chunk-OMISYKWR.mjs b/node_modules/@mswjs/interceptors/lib/browser/chunk-OMISYKWR.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c93287b8c2c05f1ee80541715e0c2002f6f144c2 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/chunk-OMISYKWR.mjs @@ -0,0 +1,53 @@ +// src/glossary.ts +var IS_PATCHED_MODULE = Symbol("isPatchedModule"); + +// src/utils/isPropertyAccessible.ts +function isPropertyAccessible(obj, key) { + try { + obj[key]; + return true; + } catch (e) { + return false; + } +} + +// src/utils/responseUtils.ts +var RESPONSE_STATUS_CODES_WITHOUT_BODY = /* @__PURE__ */ new Set([ + 101, + 103, + 204, + 205, + 304 +]); +function isResponseWithoutBody(status) { + return RESPONSE_STATUS_CODES_WITHOUT_BODY.has(status); +} +function createServerErrorResponse(body) { + return new Response( + JSON.stringify( + body instanceof Error ? { + name: body.name, + message: body.message, + stack: body.stack + } : body + ), + { + status: 500, + statusText: "Unhandled Exception", + headers: { + "Content-Type": "application/json" + } + } + ); +} +function isResponseError(response) { + return isPropertyAccessible(response, "type") && response.type === "error"; +} + +export { + IS_PATCHED_MODULE, + isResponseWithoutBody, + createServerErrorResponse, + isResponseError +}; +//# sourceMappingURL=chunk-OMISYKWR.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/chunk-OMISYKWR.mjs.map b/node_modules/@mswjs/interceptors/lib/browser/chunk-OMISYKWR.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..4561e1576114bb202485a025dbb6308b26df6f37 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/chunk-OMISYKWR.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/glossary.ts","../../src/utils/isPropertyAccessible.ts","../../src/utils/responseUtils.ts"],"sourcesContent":["import type { InteractiveRequest } from './utils/toInteractiveRequest'\n\nexport const IS_PATCHED_MODULE: unique symbol = Symbol('isPatchedModule')\n\nexport type RequestCredentials = 'omit' | 'include' | 'same-origin'\n\nexport type HttpRequestEventMap = {\n request: [\n args: {\n request: InteractiveRequest\n requestId: string\n }\n ]\n response: [\n args: {\n response: Response\n isMockedResponse: boolean\n request: Request\n requestId: string\n }\n ]\n unhandledException: [\n args: {\n error: unknown\n request: Request\n requestId: string\n controller: {\n respondWith(response: Response): void\n errorWith(error?: Error): void\n }\n }\n ]\n}\n","/**\n * A function that validates if property access is possible on an object\n * without throwing. It returns `true` if the property access is possible\n * and `false` otherwise.\n *\n * Environments like miniflare will throw on property access on certain objects\n * like Request and Response, for unimplemented properties.\n */\nexport function isPropertyAccessible>(\n obj: Obj,\n key: keyof Obj\n) {\n try {\n obj[key]\n return true\n } catch {\n return false\n }\n}\n","import { isPropertyAccessible } from './isPropertyAccessible'\n\n/**\n * Response status codes for responses that cannot have body.\n * @see https://fetch.spec.whatwg.org/#statuses\n */\nexport const RESPONSE_STATUS_CODES_WITHOUT_BODY = new Set([\n 101, 103, 204, 205, 304,\n])\n\n/**\n * Returns a boolean indicating whether the given response status\n * code represents a response that cannot have a body.\n */\nexport function isResponseWithoutBody(status: number): boolean {\n return RESPONSE_STATUS_CODES_WITHOUT_BODY.has(status)\n}\n\n/**\n * Creates a generic 500 Unhandled Exception response.\n */\nexport function createServerErrorResponse(body: unknown): Response {\n return new Response(\n JSON.stringify(\n body instanceof Error\n ? {\n name: body.name,\n message: body.message,\n stack: body.stack,\n }\n : body\n ),\n {\n status: 500,\n statusText: 'Unhandled Exception',\n headers: {\n 'Content-Type': 'application/json',\n },\n }\n )\n}\n\n/**\n * Checks if the given response is a `Response.error()`.\n *\n * @note Some environments, like Miniflare (Cloudflare) do not\n * implement the \"Response.type\" property and throw on its access.\n * Safely check if we can access \"type\" on \"Response\" before continuing.\n * @see https://github.com/mswjs/msw/issues/1834\n */\nexport function isResponseError(\n response: Response\n): response is Response & { type: 'error' } {\n return isPropertyAccessible(response, 'type') && response.type === 'error'\n}\n"],"mappings":";AAEO,IAAM,oBAAmC,OAAO,iBAAiB;;;ACMjE,SAAS,qBACd,KACA,KACA;AACA,MAAI;AACF,QAAI,GAAG;AACP,WAAO;AAAA,EACT,SAAQ,GAAN;AACA,WAAO;AAAA,EACT;AACF;;;ACZO,IAAM,qCAAqC,oBAAI,IAAI;AAAA,EACxD;AAAA,EAAK;AAAA,EAAK;AAAA,EAAK;AAAA,EAAK;AACtB,CAAC;AAMM,SAAS,sBAAsB,QAAyB;AAC7D,SAAO,mCAAmC,IAAI,MAAM;AACtD;AAKO,SAAS,0BAA0B,MAAyB;AACjE,SAAO,IAAI;AAAA,IACT,KAAK;AAAA,MACH,gBAAgB,QACZ;AAAA,QACE,MAAM,KAAK;AAAA,QACX,SAAS,KAAK;AAAA,QACd,OAAO,KAAK;AAAA,MACd,IACA;AAAA,IACN;AAAA,IACA;AAAA,MACE,QAAQ;AAAA,MACR,YAAY;AAAA,MACZ,SAAS;AAAA,QACP,gBAAgB;AAAA,MAClB;AAAA,IACF;AAAA,EACF;AACF;AAUO,SAAS,gBACd,UAC0C;AAC1C,SAAO,qBAAqB,UAAU,MAAM,KAAK,SAAS,SAAS;AACrE;","names":[]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/chunk-OUWBQF3Z.mjs b/node_modules/@mswjs/interceptors/lib/browser/chunk-OUWBQF3Z.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1446bd22220684eb39d551da6f884cfc32e18d70 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/chunk-OUWBQF3Z.mjs @@ -0,0 +1,49 @@ +// src/utils/RequestController.ts +import { invariant } from "outvariant"; +import { DeferredPromise } from "@open-draft/deferred-promise"; +var RequestController = class { + constructor(request) { + this.request = request; + this.responsePromise = new DeferredPromise(); + } + respondWith(response) { + invariant( + this.responsePromise.state === "pending", + 'Failed to respond to "%s %s" request: the "request" event has already been responded to.', + this.request.method, + this.request.url + ); + this.responsePromise.resolve(response); + } +}; + +// src/utils/toInteractiveRequest.ts +function toInteractiveRequest(request) { + const requestController = new RequestController(request); + Reflect.set( + request, + "respondWith", + requestController.respondWith.bind(requestController) + ); + return { + interactiveRequest: request, + requestController + }; +} + +// src/utils/emitAsync.ts +async function emitAsync(emitter, eventName, ...data) { + const listners = emitter.listeners(eventName); + if (listners.length === 0) { + return; + } + for (const listener of listners) { + await listener.apply(emitter, data); + } +} + +export { + toInteractiveRequest, + emitAsync +}; +//# sourceMappingURL=chunk-OUWBQF3Z.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/chunk-OUWBQF3Z.mjs.map b/node_modules/@mswjs/interceptors/lib/browser/chunk-OUWBQF3Z.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..59c0e41729fb5411491de7308ab5ef869a3818dd --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/chunk-OUWBQF3Z.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/utils/RequestController.ts","../../src/utils/toInteractiveRequest.ts","../../src/utils/emitAsync.ts"],"sourcesContent":["import { invariant } from 'outvariant'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\n\nexport class RequestController {\n public responsePromise: DeferredPromise\n\n constructor(protected request: Request) {\n this.responsePromise = new DeferredPromise()\n }\n\n public respondWith(response?: Response): void {\n invariant(\n this.responsePromise.state === 'pending',\n 'Failed to respond to \"%s %s\" request: the \"request\" event has already been responded to.',\n this.request.method,\n this.request.url\n )\n\n this.responsePromise.resolve(response)\n }\n}\n","import { RequestController } from './RequestController'\n\nexport type InteractiveRequest = globalThis.Request & {\n respondWith: RequestController['respondWith']\n}\n\nexport function toInteractiveRequest(request: Request): {\n interactiveRequest: InteractiveRequest\n requestController: RequestController\n} {\n const requestController = new RequestController(request)\n\n Reflect.set(\n request,\n 'respondWith',\n requestController.respondWith.bind(requestController)\n )\n\n return {\n interactiveRequest: request as InteractiveRequest,\n requestController,\n }\n}\n","import { Emitter, EventMap } from 'strict-event-emitter'\n\n/**\n * Emits an event on the given emitter but executes\n * the listeners sequentially. This accounts for asynchronous\n * listeners (e.g. those having \"sleep\" and handling the request).\n */\nexport async function emitAsync<\n Events extends EventMap,\n EventName extends keyof Events\n>(\n emitter: Emitter,\n eventName: EventName,\n ...data: Events[EventName]\n): Promise {\n const listners = emitter.listeners(eventName)\n\n if (listners.length === 0) {\n return\n }\n\n for (const listener of listners) {\n await listener.apply(emitter, data)\n }\n}\n"],"mappings":";AAAA,SAAS,iBAAiB;AAC1B,SAAS,uBAAuB;AAEzB,IAAM,oBAAN,MAAwB;AAAA,EAG7B,YAAsB,SAAkB;AAAlB;AACpB,SAAK,kBAAkB,IAAI,gBAAgB;AAAA,EAC7C;AAAA,EAEO,YAAY,UAA2B;AAC5C;AAAA,MACE,KAAK,gBAAgB,UAAU;AAAA,MAC/B;AAAA,MACA,KAAK,QAAQ;AAAA,MACb,KAAK,QAAQ;AAAA,IACf;AAEA,SAAK,gBAAgB,QAAQ,QAAQ;AAAA,EACvC;AACF;;;ACdO,SAAS,qBAAqB,SAGnC;AACA,QAAM,oBAAoB,IAAI,kBAAkB,OAAO;AAEvD,UAAQ;AAAA,IACN;AAAA,IACA;AAAA,IACA,kBAAkB,YAAY,KAAK,iBAAiB;AAAA,EACtD;AAEA,SAAO;AAAA,IACL,oBAAoB;AAAA,IACpB;AAAA,EACF;AACF;;;ACfA,eAAsB,UAIpB,SACA,cACG,MACY;AACf,QAAM,WAAW,QAAQ,UAAU,SAAS;AAE5C,MAAI,SAAS,WAAW,GAAG;AACzB;AAAA,EACF;AAEA,aAAW,YAAY,UAAU;AAC/B,UAAM,SAAS,MAAM,SAAS,IAAI;AAAA,EACpC;AACF;","names":[]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/chunk-PSX5J3RF.js b/node_modules/@mswjs/interceptors/lib/browser/chunk-PSX5J3RF.js new file mode 100644 index 0000000000000000000000000000000000000000..37e2a0fb7c39d0e17a4963ffe32ba512874e7ae6 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/chunk-PSX5J3RF.js @@ -0,0 +1,820 @@ +"use strict";Object.defineProperty(exports, "__esModule", {value: true}); + + + +var _chunkLK6DILFKjs = require('./chunk-LK6DILFK.js'); + + + +var _chunkMQJ3JOOKjs = require('./chunk-MQJ3JOOK.js'); + + + + + +var _chunk2CRB3JAQjs = require('./chunk-2CRB3JAQ.js'); + + + + +var _chunkTIPR373Rjs = require('./chunk-TIPR373R.js'); + +// src/interceptors/XMLHttpRequest/index.ts +var _outvariant = require('outvariant'); + +// src/interceptors/XMLHttpRequest/XMLHttpRequestProxy.ts +var _until = require('@open-draft/until'); + +// src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts + +var _isnodeprocess = require('is-node-process'); + +// src/interceptors/XMLHttpRequest/utils/concatArrayBuffer.ts +function concatArrayBuffer(left, right) { + const result = new Uint8Array(left.byteLength + right.byteLength); + result.set(left, 0); + result.set(right, left.byteLength); + return result; +} + +// src/interceptors/XMLHttpRequest/polyfills/EventPolyfill.ts +var EventPolyfill = class { + constructor(type, options) { + this.AT_TARGET = 0; + this.BUBBLING_PHASE = 0; + this.CAPTURING_PHASE = 0; + this.NONE = 0; + this.type = ""; + this.srcElement = null; + this.currentTarget = null; + this.eventPhase = 0; + this.isTrusted = true; + this.composed = false; + this.cancelable = true; + this.defaultPrevented = false; + this.bubbles = true; + this.lengthComputable = true; + this.loaded = 0; + this.total = 0; + this.cancelBubble = false; + this.returnValue = true; + this.type = type; + this.target = (options == null ? void 0 : options.target) || null; + this.currentTarget = (options == null ? void 0 : options.currentTarget) || null; + this.timeStamp = Date.now(); + } + composedPath() { + return []; + } + initEvent(type, bubbles, cancelable) { + this.type = type; + this.bubbles = !!bubbles; + this.cancelable = !!cancelable; + } + preventDefault() { + this.defaultPrevented = true; + } + stopPropagation() { + } + stopImmediatePropagation() { + } +}; + +// src/interceptors/XMLHttpRequest/polyfills/ProgressEventPolyfill.ts +var ProgressEventPolyfill = class extends EventPolyfill { + constructor(type, init) { + super(type); + this.lengthComputable = (init == null ? void 0 : init.lengthComputable) || false; + this.composed = (init == null ? void 0 : init.composed) || false; + this.loaded = (init == null ? void 0 : init.loaded) || 0; + this.total = (init == null ? void 0 : init.total) || 0; + } +}; + +// src/interceptors/XMLHttpRequest/utils/createEvent.ts +var SUPPORTS_PROGRESS_EVENT = typeof ProgressEvent !== "undefined"; +function createEvent(target, type, init) { + const progressEvents = [ + "error", + "progress", + "loadstart", + "loadend", + "load", + "timeout", + "abort" + ]; + const ProgressEventClass = SUPPORTS_PROGRESS_EVENT ? ProgressEvent : ProgressEventPolyfill; + const event = progressEvents.includes(type) ? new ProgressEventClass(type, { + lengthComputable: true, + loaded: (init == null ? void 0 : init.loaded) || 0, + total: (init == null ? void 0 : init.total) || 0 + }) : new EventPolyfill(type, { + target, + currentTarget: target + }); + return event; +} + +// src/utils/findPropertySource.ts +function findPropertySource(target, propertyName) { + if (!(propertyName in target)) { + return null; + } + const hasProperty = Object.prototype.hasOwnProperty.call(target, propertyName); + if (hasProperty) { + return target; + } + const prototype = Reflect.getPrototypeOf(target); + return prototype ? findPropertySource(prototype, propertyName) : null; +} + +// src/utils/createProxy.ts +function createProxy(target, options) { + const proxy = new Proxy(target, optionsToProxyHandler(options)); + return proxy; +} +function optionsToProxyHandler(options) { + const { constructorCall, methodCall, getProperty, setProperty } = options; + const handler = {}; + if (typeof constructorCall !== "undefined") { + handler.construct = function(target, args, newTarget) { + const next = Reflect.construct.bind(null, target, args, newTarget); + return constructorCall.call(newTarget, args, next); + }; + } + handler.set = function(target, propertyName, nextValue) { + const next = () => { + const propertySource = findPropertySource(target, propertyName) || target; + const ownDescriptors = Reflect.getOwnPropertyDescriptor( + propertySource, + propertyName + ); + if (typeof (ownDescriptors == null ? void 0 : ownDescriptors.set) !== "undefined") { + ownDescriptors.set.apply(target, [nextValue]); + return true; + } + return Reflect.defineProperty(propertySource, propertyName, { + writable: true, + enumerable: true, + configurable: true, + value: nextValue + }); + }; + if (typeof setProperty !== "undefined") { + return setProperty.call(target, [propertyName, nextValue], next); + } + return next(); + }; + handler.get = function(target, propertyName, receiver) { + const next = () => target[propertyName]; + const value = typeof getProperty !== "undefined" ? getProperty.call(target, [propertyName, receiver], next) : next(); + if (typeof value === "function") { + return (...args) => { + const next2 = value.bind(target, ...args); + if (typeof methodCall !== "undefined") { + return methodCall.call(target, [propertyName, args], next2); + } + return next2(); + }; + } + return value; + }; + return handler; +} + +// src/interceptors/XMLHttpRequest/utils/isDomParserSupportedType.ts +function isDomParserSupportedType(type) { + const supportedTypes = [ + "application/xhtml+xml", + "application/xml", + "image/svg+xml", + "text/html", + "text/xml" + ]; + return supportedTypes.some((supportedType) => { + return type.startsWith(supportedType); + }); +} + +// src/utils/parseJson.ts +function parseJson(data) { + try { + const json = JSON.parse(data); + return json; + } catch (_) { + return null; + } +} + +// src/interceptors/XMLHttpRequest/utils/createResponse.ts +function createResponse(request, body) { + const responseBodyOrNull = _chunk2CRB3JAQjs.isResponseWithoutBody.call(void 0, request.status) ? null : body; + return new Response(responseBodyOrNull, { + status: request.status, + statusText: request.statusText, + headers: createHeadersFromXMLHttpReqestHeaders( + request.getAllResponseHeaders() + ) + }); +} +function createHeadersFromXMLHttpReqestHeaders(headersString) { + const headers = new Headers(); + const lines = headersString.split(/[\r\n]+/); + for (const line of lines) { + if (line.trim() === "") { + continue; + } + const [name, ...parts] = line.split(": "); + const value = parts.join(": "); + headers.append(name, value); + } + return headers; +} + +// src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts +var IS_MOCKED_RESPONSE = Symbol("isMockedResponse"); +var IS_NODE = _isnodeprocess.isNodeProcess.call(void 0, ); +var XMLHttpRequestController = class { + constructor(initialRequest, logger) { + this.initialRequest = initialRequest; + this.logger = logger; + this.method = "GET"; + this.url = null; + this.events = /* @__PURE__ */ new Map(); + this.requestId = _chunkTIPR373Rjs.createRequestId.call(void 0, ); + this.requestHeaders = new Headers(); + this.responseBuffer = new Uint8Array(); + this.request = createProxy(initialRequest, { + setProperty: ([propertyName, nextValue], invoke) => { + switch (propertyName) { + case "ontimeout": { + const eventName = propertyName.slice( + 2 + ); + this.request.addEventListener(eventName, nextValue); + return invoke(); + } + default: { + return invoke(); + } + } + }, + methodCall: ([methodName, args], invoke) => { + var _a; + switch (methodName) { + case "open": { + const [method, url] = args; + if (typeof url === "undefined") { + this.method = "GET"; + this.url = toAbsoluteUrl(method); + } else { + this.method = method; + this.url = toAbsoluteUrl(url); + } + this.logger = this.logger.extend(`${this.method} ${this.url.href}`); + this.logger.info("open", this.method, this.url.href); + return invoke(); + } + case "addEventListener": { + const [eventName, listener] = args; + this.registerEvent(eventName, listener); + this.logger.info("addEventListener", eventName, listener); + return invoke(); + } + case "setRequestHeader": { + const [name, value] = args; + this.requestHeaders.set(name, value); + this.logger.info("setRequestHeader", name, value); + return invoke(); + } + case "send": { + const [body] = args; + if (body != null) { + this.requestBody = typeof body === "string" ? _chunkLK6DILFKjs.encodeBuffer.call(void 0, body) : body; + } + this.request.addEventListener("load", () => { + if (typeof this.onResponse !== "undefined") { + const fetchResponse = createResponse( + this.request, + /** + * The `response` property is the right way to read + * the ambiguous response body, as the request's "responseType" may differ. + * @see https://xhr.spec.whatwg.org/#the-response-attribute + */ + this.request.response + ); + this.onResponse.call(this, { + response: fetchResponse, + isMockedResponse: IS_MOCKED_RESPONSE in this.request, + request: fetchRequest, + requestId: this.requestId + }); + } + }); + const fetchRequest = this.toFetchApiRequest(); + const onceRequestSettled = ((_a = this.onRequest) == null ? void 0 : _a.call(this, { + request: fetchRequest, + requestId: this.requestId + })) || Promise.resolve(); + onceRequestSettled.finally(() => { + if (this.request.readyState < this.request.LOADING) { + this.logger.info( + "request callback settled but request has not been handled (readystate %d), performing as-is...", + this.request.readyState + ); + if (IS_NODE) { + this.request.setRequestHeader( + _chunkTIPR373Rjs.INTERNAL_REQUEST_ID_HEADER_NAME, + this.requestId + ); + } + return invoke(); + } + }); + break; + } + default: { + return invoke(); + } + } + } + }); + } + registerEvent(eventName, listener) { + const prevEvents = this.events.get(eventName) || []; + const nextEvents = prevEvents.concat(listener); + this.events.set(eventName, nextEvents); + this.logger.info('registered event "%s"', eventName, listener); + } + /** + * Responds to the current request with the given + * Fetch API `Response` instance. + */ + respondWith(response) { + this.logger.info( + "responding with a mocked response: %d %s", + response.status, + response.statusText + ); + define(this.request, IS_MOCKED_RESPONSE, true); + define(this.request, "status", response.status); + define(this.request, "statusText", response.statusText); + define(this.request, "responseURL", this.url.href); + this.request.getResponseHeader = new Proxy(this.request.getResponseHeader, { + apply: (_, __, args) => { + this.logger.info("getResponseHeader", args[0]); + if (this.request.readyState < this.request.HEADERS_RECEIVED) { + this.logger.info("headers not received yet, returning null"); + return null; + } + const headerValue = response.headers.get(args[0]); + this.logger.info( + 'resolved response header "%s" to', + args[0], + headerValue + ); + return headerValue; + } + }); + this.request.getAllResponseHeaders = new Proxy( + this.request.getAllResponseHeaders, + { + apply: () => { + this.logger.info("getAllResponseHeaders"); + if (this.request.readyState < this.request.HEADERS_RECEIVED) { + this.logger.info("headers not received yet, returning empty string"); + return ""; + } + const headersList = Array.from(response.headers.entries()); + const allHeaders = headersList.map(([headerName, headerValue]) => { + return `${headerName}: ${headerValue}`; + }).join("\r\n"); + this.logger.info("resolved all response headers to", allHeaders); + return allHeaders; + } + } + ); + Object.defineProperties(this.request, { + response: { + enumerable: true, + configurable: false, + get: () => this.response + }, + responseText: { + enumerable: true, + configurable: false, + get: () => this.responseText + }, + responseXML: { + enumerable: true, + configurable: false, + get: () => this.responseXML + } + }); + const totalResponseBodyLength = response.headers.has("Content-Length") ? Number(response.headers.get("Content-Length")) : ( + /** + * @todo Infer the response body length from the response body. + */ + void 0 + ); + this.logger.info("calculated response body length", totalResponseBodyLength); + this.trigger("loadstart", { + loaded: 0, + total: totalResponseBodyLength + }); + this.setReadyState(this.request.HEADERS_RECEIVED); + this.setReadyState(this.request.LOADING); + const finalizeResponse = () => { + this.logger.info("finalizing the mocked response..."); + this.setReadyState(this.request.DONE); + this.trigger("load", { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength + }); + this.trigger("loadend", { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength + }); + }; + if (response.body) { + this.logger.info("mocked response has body, streaming..."); + const reader = response.body.getReader(); + const readNextResponseBodyChunk = async () => { + const { value, done } = await reader.read(); + if (done) { + this.logger.info("response body stream done!"); + finalizeResponse(); + return; + } + if (value) { + this.logger.info("read response body chunk:", value); + this.responseBuffer = concatArrayBuffer(this.responseBuffer, value); + this.trigger("progress", { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength + }); + } + readNextResponseBodyChunk(); + }; + readNextResponseBodyChunk(); + } else { + finalizeResponse(); + } + } + responseBufferToText() { + return _chunkLK6DILFKjs.decodeBuffer.call(void 0, this.responseBuffer); + } + get response() { + this.logger.info( + "getResponse (responseType: %s)", + this.request.responseType + ); + if (this.request.readyState !== this.request.DONE) { + return null; + } + switch (this.request.responseType) { + case "json": { + const responseJson = parseJson(this.responseBufferToText()); + this.logger.info("resolved response JSON", responseJson); + return responseJson; + } + case "arraybuffer": { + const arrayBuffer = _chunkLK6DILFKjs.toArrayBuffer.call(void 0, this.responseBuffer); + this.logger.info("resolved response ArrayBuffer", arrayBuffer); + return arrayBuffer; + } + case "blob": { + const mimeType = this.request.getResponseHeader("Content-Type") || "text/plain"; + const responseBlob = new Blob([this.responseBufferToText()], { + type: mimeType + }); + this.logger.info( + "resolved response Blob (mime type: %s)", + responseBlob, + mimeType + ); + return responseBlob; + } + default: { + const responseText = this.responseBufferToText(); + this.logger.info( + 'resolving "%s" response type as text', + this.request.responseType, + responseText + ); + return responseText; + } + } + } + get responseText() { + _outvariant.invariant.call(void 0, + this.request.responseType === "" || this.request.responseType === "text", + "InvalidStateError: The object is in invalid state." + ); + if (this.request.readyState !== this.request.LOADING && this.request.readyState !== this.request.DONE) { + return ""; + } + const responseText = this.responseBufferToText(); + this.logger.info('getResponseText: "%s"', responseText); + return responseText; + } + get responseXML() { + _outvariant.invariant.call(void 0, + this.request.responseType === "" || this.request.responseType === "document", + "InvalidStateError: The object is in invalid state." + ); + if (this.request.readyState !== this.request.DONE) { + return null; + } + const contentType = this.request.getResponseHeader("Content-Type") || ""; + if (typeof DOMParser === "undefined") { + console.warn( + "Cannot retrieve XMLHttpRequest response body as XML: DOMParser is not defined. You are likely using an environment that is not browser or does not polyfill browser globals correctly." + ); + return null; + } + if (isDomParserSupportedType(contentType)) { + return new DOMParser().parseFromString( + this.responseBufferToText(), + contentType + ); + } + return null; + } + errorWith(error) { + this.logger.info("responding with an error"); + this.setReadyState(this.request.DONE); + this.trigger("error"); + this.trigger("loadend"); + } + /** + * Transitions this request's `readyState` to the given one. + */ + setReadyState(nextReadyState) { + this.logger.info( + "setReadyState: %d -> %d", + this.request.readyState, + nextReadyState + ); + if (this.request.readyState === nextReadyState) { + this.logger.info("ready state identical, skipping transition..."); + return; + } + define(this.request, "readyState", nextReadyState); + this.logger.info("set readyState to: %d", nextReadyState); + if (nextReadyState !== this.request.UNSENT) { + this.logger.info('triggerring "readystatechange" event...'); + this.trigger("readystatechange"); + } + } + /** + * Triggers given event on the `XMLHttpRequest` instance. + */ + trigger(eventName, options) { + const callback = this.request[`on${eventName}`]; + const event = createEvent(this.request, eventName, options); + this.logger.info('trigger "%s"', eventName, options || ""); + if (typeof callback === "function") { + this.logger.info('found a direct "%s" callback, calling...', eventName); + callback.call(this.request, event); + } + for (const [registeredEventName, listeners] of this.events) { + if (registeredEventName === eventName) { + this.logger.info( + 'found %d listener(s) for "%s" event, calling...', + listeners.length, + eventName + ); + listeners.forEach((listener) => listener.call(this.request, event)); + } + } + } + /** + * Converts this `XMLHttpRequest` instance into a Fetch API `Request` instance. + */ + toFetchApiRequest() { + this.logger.info("converting request to a Fetch API Request..."); + const fetchRequest = new Request(this.url.href, { + method: this.method, + headers: this.requestHeaders, + /** + * @see https://xhr.spec.whatwg.org/#cross-origin-credentials + */ + credentials: this.request.withCredentials ? "include" : "same-origin", + body: ["GET", "HEAD"].includes(this.method) ? null : this.requestBody + }); + const proxyHeaders = createProxy(fetchRequest.headers, { + methodCall: ([methodName, args], invoke) => { + switch (methodName) { + case "append": + case "set": { + const [headerName, headerValue] = args; + this.request.setRequestHeader(headerName, headerValue); + break; + } + case "delete": { + const [headerName] = args; + console.warn( + `XMLHttpRequest: Cannot remove a "${headerName}" header from the Fetch API representation of the "${fetchRequest.method} ${fetchRequest.url}" request. XMLHttpRequest headers cannot be removed.` + ); + break; + } + } + return invoke(); + } + }); + define(fetchRequest, "headers", proxyHeaders); + this.logger.info("converted request to a Fetch API Request!", fetchRequest); + return fetchRequest; + } +}; +function toAbsoluteUrl(url) { + if (typeof location === "undefined") { + return new URL(url); + } + return new URL(url.toString(), location.href); +} +function define(target, property, value) { + Reflect.defineProperty(target, property, { + // Ensure writable properties to allow redefining readonly properties. + writable: true, + enumerable: true, + value + }); +} + +// src/interceptors/XMLHttpRequest/XMLHttpRequestProxy.ts +function createXMLHttpRequestProxy({ + emitter, + logger +}) { + const XMLHttpRequestProxy = new Proxy(globalThis.XMLHttpRequest, { + construct(target, args, newTarget) { + logger.info("constructed new XMLHttpRequest"); + const originalRequest = Reflect.construct( + target, + args, + newTarget + ); + const prototypeDescriptors = Object.getOwnPropertyDescriptors( + target.prototype + ); + for (const propertyName in prototypeDescriptors) { + Reflect.defineProperty( + originalRequest, + propertyName, + prototypeDescriptors[propertyName] + ); + } + const xhrRequestController = new XMLHttpRequestController( + originalRequest, + logger + ); + xhrRequestController.onRequest = async function({ request, requestId }) { + const { interactiveRequest, requestController } = _chunkMQJ3JOOKjs.toInteractiveRequest.call(void 0, request); + this.logger.info("awaiting mocked response..."); + emitter.once("request", ({ requestId: pendingRequestId }) => { + if (pendingRequestId !== requestId) { + return; + } + if (requestController.responsePromise.state === "pending") { + requestController.respondWith(void 0); + } + }); + const resolverResult = await _until.until.call(void 0, async () => { + this.logger.info( + 'emitting the "request" event for %s listener(s)...', + emitter.listenerCount("request") + ); + await _chunkMQJ3JOOKjs.emitAsync.call(void 0, emitter, "request", { + request: interactiveRequest, + requestId + }); + this.logger.info('all "request" listeners settled!'); + const mockedResponse2 = await requestController.responsePromise; + this.logger.info("event.respondWith called with:", mockedResponse2); + return mockedResponse2; + }); + if (resolverResult.error) { + this.logger.info( + "request listener threw an exception, aborting request...", + resolverResult.error + ); + if (resolverResult.error instanceof Response) { + if (_chunk2CRB3JAQjs.isResponseError.call(void 0, resolverResult.error)) { + xhrRequestController.errorWith(new TypeError("Network error")); + } else { + this.respondWith(resolverResult.error); + } + return; + } + if (emitter.listenerCount("unhandledException") > 0) { + await _chunkMQJ3JOOKjs.emitAsync.call(void 0, emitter, "unhandledException", { + error: resolverResult.error, + request, + requestId, + controller: { + respondWith: xhrRequestController.respondWith.bind(xhrRequestController), + errorWith: xhrRequestController.errorWith.bind(xhrRequestController) + } + }); + if (originalRequest.readyState > XMLHttpRequest.OPENED) { + return; + } + } + xhrRequestController.respondWith( + _chunk2CRB3JAQjs.createServerErrorResponse.call(void 0, resolverResult.error) + ); + return; + } + const mockedResponse = resolverResult.data; + if (typeof mockedResponse !== "undefined") { + this.logger.info( + "received mocked response: %d %s", + mockedResponse.status, + mockedResponse.statusText + ); + if (_chunk2CRB3JAQjs.isResponseError.call(void 0, mockedResponse)) { + this.logger.info( + "received a network error response, rejecting the request promise..." + ); + xhrRequestController.errorWith(new TypeError("Network error")); + return; + } + return xhrRequestController.respondWith(mockedResponse); + } + this.logger.info( + "no mocked response received, performing request as-is..." + ); + }; + xhrRequestController.onResponse = async function({ + response, + isMockedResponse, + request, + requestId + }) { + this.logger.info( + 'emitting the "response" event for %s listener(s)...', + emitter.listenerCount("response") + ); + emitter.emit("response", { + response, + isMockedResponse, + request, + requestId + }); + }; + return xhrRequestController.request; + } + }); + return XMLHttpRequestProxy; +} + +// src/interceptors/XMLHttpRequest/index.ts +var _XMLHttpRequestInterceptor = class extends _chunkTIPR373Rjs.Interceptor { + constructor() { + super(_XMLHttpRequestInterceptor.interceptorSymbol); + } + checkEnvironment() { + return typeof globalThis.XMLHttpRequest !== "undefined"; + } + setup() { + const logger = this.logger.extend("setup"); + logger.info('patching "XMLHttpRequest" module...'); + const PureXMLHttpRequest = globalThis.XMLHttpRequest; + _outvariant.invariant.call(void 0, + !PureXMLHttpRequest[_chunk2CRB3JAQjs.IS_PATCHED_MODULE], + 'Failed to patch the "XMLHttpRequest" module: already patched.' + ); + globalThis.XMLHttpRequest = createXMLHttpRequestProxy({ + emitter: this.emitter, + logger: this.logger + }); + logger.info( + 'native "XMLHttpRequest" module patched!', + globalThis.XMLHttpRequest.name + ); + Object.defineProperty(globalThis.XMLHttpRequest, _chunk2CRB3JAQjs.IS_PATCHED_MODULE, { + enumerable: true, + configurable: true, + value: true + }); + this.subscriptions.push(() => { + Object.defineProperty(globalThis.XMLHttpRequest, _chunk2CRB3JAQjs.IS_PATCHED_MODULE, { + value: void 0 + }); + globalThis.XMLHttpRequest = PureXMLHttpRequest; + logger.info( + 'native "XMLHttpRequest" module restored!', + globalThis.XMLHttpRequest.name + ); + }); + } +}; +var XMLHttpRequestInterceptor = _XMLHttpRequestInterceptor; +XMLHttpRequestInterceptor.interceptorSymbol = Symbol("xhr"); + + + +exports.XMLHttpRequestInterceptor = XMLHttpRequestInterceptor; +//# sourceMappingURL=chunk-PSX5J3RF.js.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/chunk-PSX5J3RF.js.map b/node_modules/@mswjs/interceptors/lib/browser/chunk-PSX5J3RF.js.map new file mode 100644 index 0000000000000000000000000000000000000000..0fcaaa0af08cc15102cf71985418d4fb53478044 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/chunk-PSX5J3RF.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/interceptors/XMLHttpRequest/index.ts","../../src/interceptors/XMLHttpRequest/XMLHttpRequestProxy.ts","../../src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts","../../src/interceptors/XMLHttpRequest/utils/concatArrayBuffer.ts","../../src/interceptors/XMLHttpRequest/polyfills/EventPolyfill.ts","../../src/interceptors/XMLHttpRequest/polyfills/ProgressEventPolyfill.ts","../../src/interceptors/XMLHttpRequest/utils/createEvent.ts","../../src/utils/findPropertySource.ts","../../src/utils/createProxy.ts","../../src/interceptors/XMLHttpRequest/utils/isDomParserSupportedType.ts","../../src/utils/parseJson.ts","../../src/interceptors/XMLHttpRequest/utils/createResponse.ts"],"names":["invariant","next","mockedResponse"],"mappings":"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","sourcesContent":["import { invariant } from 'outvariant'\nimport { Emitter } from 'strict-event-emitter'\nimport { HttpRequestEventMap, IS_PATCHED_MODULE } from '../../glossary'\nimport { InteractiveRequest } from '../../utils/toInteractiveRequest'\nimport { Interceptor } from '../../Interceptor'\nimport { createXMLHttpRequestProxy } from './XMLHttpRequestProxy'\n\nexport type XMLHttpRequestEventListener = (args: {\n request: InteractiveRequest\n requestId: string\n}) => Promise | void\n\nexport type XMLHttpRequestEmitter = Emitter\n\nexport class XMLHttpRequestInterceptor extends Interceptor {\n static interceptorSymbol = Symbol('xhr')\n\n constructor() {\n super(XMLHttpRequestInterceptor.interceptorSymbol)\n }\n\n protected checkEnvironment() {\n return typeof globalThis.XMLHttpRequest !== 'undefined'\n }\n\n protected setup() {\n const logger = this.logger.extend('setup')\n\n logger.info('patching \"XMLHttpRequest\" module...')\n\n const PureXMLHttpRequest = globalThis.XMLHttpRequest\n\n invariant(\n !(PureXMLHttpRequest as any)[IS_PATCHED_MODULE],\n 'Failed to patch the \"XMLHttpRequest\" module: already patched.'\n )\n\n globalThis.XMLHttpRequest = createXMLHttpRequestProxy({\n emitter: this.emitter,\n logger: this.logger,\n })\n\n logger.info(\n 'native \"XMLHttpRequest\" module patched!',\n globalThis.XMLHttpRequest.name\n )\n\n Object.defineProperty(globalThis.XMLHttpRequest, IS_PATCHED_MODULE, {\n enumerable: true,\n configurable: true,\n value: true,\n })\n\n this.subscriptions.push(() => {\n Object.defineProperty(globalThis.XMLHttpRequest, IS_PATCHED_MODULE, {\n value: undefined,\n })\n\n globalThis.XMLHttpRequest = PureXMLHttpRequest\n logger.info(\n 'native \"XMLHttpRequest\" module restored!',\n globalThis.XMLHttpRequest.name\n )\n })\n }\n}\n","import { until } from '@open-draft/until'\nimport type { Logger } from '@open-draft/logger'\nimport { XMLHttpRequestEmitter } from '.'\nimport { toInteractiveRequest } from '../../utils/toInteractiveRequest'\nimport { emitAsync } from '../../utils/emitAsync'\nimport { XMLHttpRequestController } from './XMLHttpRequestController'\nimport {\n createServerErrorResponse,\n isResponseError,\n} from '../../utils/responseUtils'\n\nexport interface XMLHttpRequestProxyOptions {\n emitter: XMLHttpRequestEmitter\n logger: Logger\n}\n\n/**\n * Create a proxied `XMLHttpRequest` class.\n * The proxied class establishes spies on certain methods,\n * allowing us to intercept requests and respond to them.\n */\nexport function createXMLHttpRequestProxy({\n emitter,\n logger,\n}: XMLHttpRequestProxyOptions) {\n const XMLHttpRequestProxy = new Proxy(globalThis.XMLHttpRequest, {\n construct(target, args, newTarget) {\n logger.info('constructed new XMLHttpRequest')\n\n const originalRequest = Reflect.construct(\n target,\n args,\n newTarget\n ) as XMLHttpRequest\n\n /**\n * @note Forward prototype descriptors onto the proxied object.\n * XMLHttpRequest is implemented in JSDOM in a way that assigns\n * a bunch of descriptors, like \"set responseType()\" on the prototype.\n * With this propagation, we make sure that those descriptors trigger\n * when the user operates with the proxied request instance.\n */\n const prototypeDescriptors = Object.getOwnPropertyDescriptors(\n target.prototype\n )\n for (const propertyName in prototypeDescriptors) {\n Reflect.defineProperty(\n originalRequest,\n propertyName,\n prototypeDescriptors[propertyName]\n )\n }\n\n const xhrRequestController = new XMLHttpRequestController(\n originalRequest,\n logger\n )\n\n xhrRequestController.onRequest = async function ({ request, requestId }) {\n const { interactiveRequest, requestController } =\n toInteractiveRequest(request)\n\n this.logger.info('awaiting mocked response...')\n\n emitter.once('request', ({ requestId: pendingRequestId }) => {\n if (pendingRequestId !== requestId) {\n return\n }\n\n if (requestController.responsePromise.state === 'pending') {\n requestController.respondWith(undefined)\n }\n })\n\n const resolverResult = await until(async () => {\n this.logger.info(\n 'emitting the \"request\" event for %s listener(s)...',\n emitter.listenerCount('request')\n )\n\n await emitAsync(emitter, 'request', {\n request: interactiveRequest,\n requestId,\n })\n\n this.logger.info('all \"request\" listeners settled!')\n\n const mockedResponse = await requestController.responsePromise\n\n this.logger.info('event.respondWith called with:', mockedResponse)\n\n return mockedResponse\n })\n\n if (resolverResult.error) {\n this.logger.info(\n 'request listener threw an exception, aborting request...',\n resolverResult.error\n )\n\n // Treat thrown Responses as mocked responses.\n if (resolverResult.error instanceof Response) {\n if (isResponseError(resolverResult.error)) {\n xhrRequestController.errorWith(new TypeError('Network error'))\n } else {\n this.respondWith(resolverResult.error)\n }\n\n return\n }\n\n if (emitter.listenerCount('unhandledException') > 0) {\n // Emit the \"unhandledException\" event so the client can opt-out\n // from the default exception handling (producing 500 error responses).\n await emitAsync(emitter, 'unhandledException', {\n error: resolverResult.error,\n request,\n requestId,\n controller: {\n respondWith:\n xhrRequestController.respondWith.bind(xhrRequestController),\n errorWith:\n xhrRequestController.errorWith.bind(xhrRequestController),\n },\n })\n\n // If any of the \"unhandledException\" listeners handled the request,\n // do nothing. Note that mocked responses will dispatch\n // HEADERS_RECEIVED (2), then LOADING (3), and DONE (4) can take\n // time as the mocked response body finishes streaming.\n if (originalRequest.readyState > XMLHttpRequest.OPENED) {\n return\n }\n }\n\n // Unhandled exceptions in the request listeners are\n // synonymous to unhandled exceptions on the server.\n // Those are represented as 500 error responses.\n xhrRequestController.respondWith(\n createServerErrorResponse(resolverResult.error)\n )\n\n return\n }\n\n const mockedResponse = resolverResult.data\n\n if (typeof mockedResponse !== 'undefined') {\n this.logger.info(\n 'received mocked response: %d %s',\n mockedResponse.status,\n mockedResponse.statusText\n )\n\n if (isResponseError(mockedResponse)) {\n this.logger.info(\n 'received a network error response, rejecting the request promise...'\n )\n\n xhrRequestController.errorWith(new TypeError('Network error'))\n return\n }\n\n return xhrRequestController.respondWith(mockedResponse)\n }\n\n this.logger.info(\n 'no mocked response received, performing request as-is...'\n )\n }\n\n xhrRequestController.onResponse = async function ({\n response,\n isMockedResponse,\n request,\n requestId,\n }) {\n this.logger.info(\n 'emitting the \"response\" event for %s listener(s)...',\n emitter.listenerCount('response')\n )\n\n emitter.emit('response', {\n response,\n isMockedResponse,\n request,\n requestId,\n })\n }\n\n // Return the proxied request from the controller\n // so that the controller can react to the consumer's interactions\n // with this request (opening/sending/etc).\n return xhrRequestController.request\n },\n })\n\n return XMLHttpRequestProxy\n}\n","import { invariant } from 'outvariant'\nimport { isNodeProcess } from 'is-node-process'\nimport type { Logger } from '@open-draft/logger'\nimport { concatArrayBuffer } from './utils/concatArrayBuffer'\nimport { createEvent } from './utils/createEvent'\nimport {\n decodeBuffer,\n encodeBuffer,\n toArrayBuffer,\n} from '../../utils/bufferUtils'\nimport { createProxy } from '../../utils/createProxy'\nimport { isDomParserSupportedType } from './utils/isDomParserSupportedType'\nimport { parseJson } from '../../utils/parseJson'\nimport { createResponse } from './utils/createResponse'\nimport { INTERNAL_REQUEST_ID_HEADER_NAME } from '../../Interceptor'\nimport { createRequestId } from '../../createRequestId'\n\nconst IS_MOCKED_RESPONSE = Symbol('isMockedResponse')\nconst IS_NODE = isNodeProcess()\n\n/**\n * An `XMLHttpRequest` instance controller that allows us\n * to handle any given request instance (e.g. responding to it).\n */\nexport class XMLHttpRequestController {\n public request: XMLHttpRequest\n public requestId: string\n public onRequest?: (\n this: XMLHttpRequestController,\n args: {\n request: Request\n requestId: string\n }\n ) => Promise\n public onResponse?: (\n this: XMLHttpRequestController,\n args: {\n response: Response\n isMockedResponse: boolean\n request: Request\n requestId: string\n }\n ) => void\n\n private method: string = 'GET'\n private url: URL = null as any\n private requestHeaders: Headers\n private requestBody?: XMLHttpRequestBodyInit | Document | null\n private responseBuffer: Uint8Array\n private events: Map>\n\n constructor(readonly initialRequest: XMLHttpRequest, public logger: Logger) {\n this.events = new Map()\n this.requestId = createRequestId()\n this.requestHeaders = new Headers()\n this.responseBuffer = new Uint8Array()\n\n this.request = createProxy(initialRequest, {\n setProperty: ([propertyName, nextValue], invoke) => {\n switch (propertyName) {\n case 'ontimeout': {\n const eventName = propertyName.slice(\n 2\n ) as keyof XMLHttpRequestEventTargetEventMap\n\n /**\n * @note Proxy callbacks to event listeners because JSDOM has trouble\n * translating these properties to callbacks. It seemed to be operating\n * on events exclusively.\n */\n this.request.addEventListener(eventName, nextValue as any)\n\n return invoke()\n }\n\n default: {\n return invoke()\n }\n }\n },\n methodCall: ([methodName, args], invoke) => {\n switch (methodName) {\n case 'open': {\n const [method, url] = args as [string, string | undefined]\n\n if (typeof url === 'undefined') {\n this.method = 'GET'\n this.url = toAbsoluteUrl(method)\n } else {\n this.method = method\n this.url = toAbsoluteUrl(url)\n }\n\n this.logger = this.logger.extend(`${this.method} ${this.url.href}`)\n this.logger.info('open', this.method, this.url.href)\n\n return invoke()\n }\n\n case 'addEventListener': {\n const [eventName, listener] = args as [\n keyof XMLHttpRequestEventTargetEventMap,\n Function\n ]\n\n this.registerEvent(eventName, listener)\n this.logger.info('addEventListener', eventName, listener)\n\n return invoke()\n }\n\n case 'setRequestHeader': {\n const [name, value] = args as [string, string]\n this.requestHeaders.set(name, value)\n\n this.logger.info('setRequestHeader', name, value)\n\n return invoke()\n }\n\n case 'send': {\n const [body] = args as [\n body?: XMLHttpRequestBodyInit | Document | null\n ]\n\n if (body != null) {\n this.requestBody =\n typeof body === 'string' ? encodeBuffer(body) : body\n }\n\n this.request.addEventListener('load', () => {\n if (typeof this.onResponse !== 'undefined') {\n // Create a Fetch API Response representation of whichever\n // response this XMLHttpRequest received. Note those may\n // be either a mocked and the original response.\n const fetchResponse = createResponse(\n this.request,\n /**\n * The `response` property is the right way to read\n * the ambiguous response body, as the request's \"responseType\" may differ.\n * @see https://xhr.spec.whatwg.org/#the-response-attribute\n */\n this.request.response\n )\n\n // Notify the consumer about the response.\n this.onResponse.call(this, {\n response: fetchResponse,\n isMockedResponse: IS_MOCKED_RESPONSE in this.request,\n request: fetchRequest,\n requestId: this.requestId!,\n })\n }\n })\n\n // Delegate request handling to the consumer.\n const fetchRequest = this.toFetchApiRequest()\n const onceRequestSettled =\n this.onRequest?.call(this, {\n request: fetchRequest,\n requestId: this.requestId!,\n }) || Promise.resolve()\n\n onceRequestSettled.finally(() => {\n // If the consumer didn't handle the request perform it as-is.\n // Note that the request may not yet be DONE and may, in fact,\n // be LOADING while the \"respondWith\" method does its magic.\n if (this.request.readyState < this.request.LOADING) {\n this.logger.info(\n 'request callback settled but request has not been handled (readystate %d), performing as-is...',\n this.request.readyState\n )\n\n /**\n * @note Set the intercepted request ID on the original request in Node.js\n * so that if it triggers any other interceptors, they don't attempt\n * to process it once again.\n *\n * For instance, XMLHttpRequest is often implemented via \"http.ClientRequest\"\n * and we don't want for both XHR and ClientRequest interceptors to\n * handle the same request at the same time (e.g. emit the \"response\" event twice).\n */\n if (IS_NODE) {\n this.request.setRequestHeader(\n INTERNAL_REQUEST_ID_HEADER_NAME,\n this.requestId!\n )\n }\n\n return invoke()\n }\n })\n\n break\n }\n\n default: {\n return invoke()\n }\n }\n },\n })\n }\n\n private registerEvent(\n eventName: keyof XMLHttpRequestEventTargetEventMap,\n listener: Function\n ): void {\n const prevEvents = this.events.get(eventName) || []\n const nextEvents = prevEvents.concat(listener)\n this.events.set(eventName, nextEvents)\n\n this.logger.info('registered event \"%s\"', eventName, listener)\n }\n\n /**\n * Responds to the current request with the given\n * Fetch API `Response` instance.\n */\n public respondWith(response: Response): void {\n this.logger.info(\n 'responding with a mocked response: %d %s',\n response.status,\n response.statusText\n )\n\n /**\n * @note Since `XMLHttpRequestController` delegates the handling of the responses\n * to the \"load\" event listener that doesn't distinguish between the mocked and original\n * responses, mark the request that had a mocked response with a corresponding symbol.\n */\n define(this.request, IS_MOCKED_RESPONSE, true)\n\n define(this.request, 'status', response.status)\n define(this.request, 'statusText', response.statusText)\n define(this.request, 'responseURL', this.url.href)\n\n this.request.getResponseHeader = new Proxy(this.request.getResponseHeader, {\n apply: (_, __, args: [name: string]) => {\n this.logger.info('getResponseHeader', args[0])\n\n if (this.request.readyState < this.request.HEADERS_RECEIVED) {\n this.logger.info('headers not received yet, returning null')\n\n // Headers not received yet, nothing to return.\n return null\n }\n\n const headerValue = response.headers.get(args[0])\n this.logger.info(\n 'resolved response header \"%s\" to',\n args[0],\n headerValue\n )\n\n return headerValue\n },\n })\n\n this.request.getAllResponseHeaders = new Proxy(\n this.request.getAllResponseHeaders,\n {\n apply: () => {\n this.logger.info('getAllResponseHeaders')\n\n if (this.request.readyState < this.request.HEADERS_RECEIVED) {\n this.logger.info('headers not received yet, returning empty string')\n\n // Headers not received yet, nothing to return.\n return ''\n }\n\n const headersList = Array.from(response.headers.entries())\n const allHeaders = headersList\n .map(([headerName, headerValue]) => {\n return `${headerName}: ${headerValue}`\n })\n .join('\\r\\n')\n\n this.logger.info('resolved all response headers to', allHeaders)\n\n return allHeaders\n },\n }\n )\n\n // Update the response getters to resolve against the mocked response.\n Object.defineProperties(this.request, {\n response: {\n enumerable: true,\n configurable: false,\n get: () => this.response,\n },\n responseText: {\n enumerable: true,\n configurable: false,\n get: () => this.responseText,\n },\n responseXML: {\n enumerable: true,\n configurable: false,\n get: () => this.responseXML,\n },\n })\n\n const totalResponseBodyLength = response.headers.has('Content-Length')\n ? Number(response.headers.get('Content-Length'))\n : /**\n * @todo Infer the response body length from the response body.\n */\n undefined\n\n this.logger.info('calculated response body length', totalResponseBodyLength)\n\n this.trigger('loadstart', {\n loaded: 0,\n total: totalResponseBodyLength,\n })\n\n this.setReadyState(this.request.HEADERS_RECEIVED)\n this.setReadyState(this.request.LOADING)\n\n const finalizeResponse = () => {\n this.logger.info('finalizing the mocked response...')\n\n this.setReadyState(this.request.DONE)\n\n this.trigger('load', {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n\n this.trigger('loadend', {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n }\n\n if (response.body) {\n this.logger.info('mocked response has body, streaming...')\n\n const reader = response.body.getReader()\n\n const readNextResponseBodyChunk = async () => {\n const { value, done } = await reader.read()\n\n if (done) {\n this.logger.info('response body stream done!')\n finalizeResponse()\n return\n }\n\n if (value) {\n this.logger.info('read response body chunk:', value)\n this.responseBuffer = concatArrayBuffer(this.responseBuffer, value)\n\n this.trigger('progress', {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n }\n\n readNextResponseBodyChunk()\n }\n\n readNextResponseBodyChunk()\n } else {\n finalizeResponse()\n }\n }\n\n private responseBufferToText(): string {\n return decodeBuffer(this.responseBuffer)\n }\n\n get response(): unknown {\n this.logger.info(\n 'getResponse (responseType: %s)',\n this.request.responseType\n )\n\n if (this.request.readyState !== this.request.DONE) {\n return null\n }\n\n switch (this.request.responseType) {\n case 'json': {\n const responseJson = parseJson(this.responseBufferToText())\n this.logger.info('resolved response JSON', responseJson)\n\n return responseJson\n }\n\n case 'arraybuffer': {\n const arrayBuffer = toArrayBuffer(this.responseBuffer)\n this.logger.info('resolved response ArrayBuffer', arrayBuffer)\n\n return arrayBuffer\n }\n\n case 'blob': {\n const mimeType =\n this.request.getResponseHeader('Content-Type') || 'text/plain'\n const responseBlob = new Blob([this.responseBufferToText()], {\n type: mimeType,\n })\n\n this.logger.info(\n 'resolved response Blob (mime type: %s)',\n responseBlob,\n mimeType\n )\n\n return responseBlob\n }\n\n default: {\n const responseText = this.responseBufferToText()\n this.logger.info(\n 'resolving \"%s\" response type as text',\n this.request.responseType,\n responseText\n )\n\n return responseText\n }\n }\n }\n\n get responseText(): string {\n /**\n * Throw when trying to read the response body as text when the\n * \"responseType\" doesn't expect text. This just respects the spec better.\n * @see https://xhr.spec.whatwg.org/#the-responsetext-attribute\n */\n invariant(\n this.request.responseType === '' || this.request.responseType === 'text',\n 'InvalidStateError: The object is in invalid state.'\n )\n\n if (\n this.request.readyState !== this.request.LOADING &&\n this.request.readyState !== this.request.DONE\n ) {\n return ''\n }\n\n const responseText = this.responseBufferToText()\n this.logger.info('getResponseText: \"%s\"', responseText)\n\n return responseText\n }\n\n get responseXML(): Document | null {\n invariant(\n this.request.responseType === '' ||\n this.request.responseType === 'document',\n 'InvalidStateError: The object is in invalid state.'\n )\n\n if (this.request.readyState !== this.request.DONE) {\n return null\n }\n\n const contentType = this.request.getResponseHeader('Content-Type') || ''\n\n if (typeof DOMParser === 'undefined') {\n console.warn(\n 'Cannot retrieve XMLHttpRequest response body as XML: DOMParser is not defined. You are likely using an environment that is not browser or does not polyfill browser globals correctly.'\n )\n return null\n }\n\n if (isDomParserSupportedType(contentType)) {\n return new DOMParser().parseFromString(\n this.responseBufferToText(),\n contentType\n )\n }\n\n return null\n }\n\n public errorWith(error: Error): void {\n this.logger.info('responding with an error')\n\n this.setReadyState(this.request.DONE)\n this.trigger('error')\n this.trigger('loadend')\n }\n\n /**\n * Transitions this request's `readyState` to the given one.\n */\n private setReadyState(nextReadyState: number): void {\n this.logger.info(\n 'setReadyState: %d -> %d',\n this.request.readyState,\n nextReadyState\n )\n\n if (this.request.readyState === nextReadyState) {\n this.logger.info('ready state identical, skipping transition...')\n return\n }\n\n define(this.request, 'readyState', nextReadyState)\n\n this.logger.info('set readyState to: %d', nextReadyState)\n\n if (nextReadyState !== this.request.UNSENT) {\n this.logger.info('triggerring \"readystatechange\" event...')\n\n this.trigger('readystatechange')\n }\n }\n\n /**\n * Triggers given event on the `XMLHttpRequest` instance.\n */\n private trigger<\n EventName extends keyof (XMLHttpRequestEventTargetEventMap & {\n readystatechange: ProgressEvent\n })\n >(eventName: EventName, options?: ProgressEventInit): void {\n const callback = this.request[`on${eventName}`]\n const event = createEvent(this.request, eventName, options)\n\n this.logger.info('trigger \"%s\"', eventName, options || '')\n\n // Invoke direct callbacks.\n if (typeof callback === 'function') {\n this.logger.info('found a direct \"%s\" callback, calling...', eventName)\n callback.call(this.request, event)\n }\n\n // Invoke event listeners.\n for (const [registeredEventName, listeners] of this.events) {\n if (registeredEventName === eventName) {\n this.logger.info(\n 'found %d listener(s) for \"%s\" event, calling...',\n listeners.length,\n eventName\n )\n\n listeners.forEach((listener) => listener.call(this.request, event))\n }\n }\n }\n\n /**\n * Converts this `XMLHttpRequest` instance into a Fetch API `Request` instance.\n */\n public toFetchApiRequest(): Request {\n this.logger.info('converting request to a Fetch API Request...')\n\n const fetchRequest = new Request(this.url.href, {\n method: this.method,\n headers: this.requestHeaders,\n /**\n * @see https://xhr.spec.whatwg.org/#cross-origin-credentials\n */\n credentials: this.request.withCredentials ? 'include' : 'same-origin',\n body: ['GET', 'HEAD'].includes(this.method)\n ? null\n : (this.requestBody as BodyInit),\n })\n\n const proxyHeaders = createProxy(fetchRequest.headers, {\n methodCall: ([methodName, args], invoke) => {\n // Forward the latest state of the internal request headers\n // because the interceptor might have modified them\n // without responding to the request.\n switch (methodName) {\n case 'append':\n case 'set': {\n const [headerName, headerValue] = args as [string, string]\n this.request.setRequestHeader(headerName, headerValue)\n break\n }\n\n case 'delete': {\n const [headerName] = args as [string]\n console.warn(\n `XMLHttpRequest: Cannot remove a \"${headerName}\" header from the Fetch API representation of the \"${fetchRequest.method} ${fetchRequest.url}\" request. XMLHttpRequest headers cannot be removed.`\n )\n break\n }\n }\n\n return invoke()\n },\n })\n define(fetchRequest, 'headers', proxyHeaders)\n\n this.logger.info('converted request to a Fetch API Request!', fetchRequest)\n\n return fetchRequest\n }\n}\n\nfunction toAbsoluteUrl(url: string | URL): URL {\n /**\n * @note XMLHttpRequest interceptor may run in environments\n * that implement XMLHttpRequest but don't implement \"location\"\n * (for example, React Native). If that's the case, return the\n * input URL as-is (nothing to be relative to).\n * @see https://github.com/mswjs/msw/issues/1777\n */\n if (typeof location === 'undefined') {\n return new URL(url)\n }\n\n return new URL(url.toString(), location.href)\n}\n\nfunction define(\n target: object,\n property: string | symbol,\n value: unknown\n): void {\n Reflect.defineProperty(target, property, {\n // Ensure writable properties to allow redefining readonly properties.\n writable: true,\n enumerable: true,\n value,\n })\n}\n","/**\n * Concatenate two `Uint8Array` buffers.\n */\nexport function concatArrayBuffer(\n left: Uint8Array,\n right: Uint8Array\n): Uint8Array {\n const result = new Uint8Array(left.byteLength + right.byteLength)\n result.set(left, 0)\n result.set(right, left.byteLength)\n return result\n}\n","export class EventPolyfill implements Event {\n readonly AT_TARGET: number = 0\n readonly BUBBLING_PHASE: number = 0\n readonly CAPTURING_PHASE: number = 0\n readonly NONE: number = 0\n\n public type: string = ''\n public srcElement: EventTarget | null = null\n public target: EventTarget | null\n public currentTarget: EventTarget | null = null\n public eventPhase: number = 0\n public timeStamp: number\n public isTrusted: boolean = true\n public composed: boolean = false\n public cancelable: boolean = true\n public defaultPrevented: boolean = false\n public bubbles: boolean = true\n public lengthComputable: boolean = true\n public loaded: number = 0\n public total: number = 0\n\n cancelBubble: boolean = false\n returnValue: boolean = true\n\n constructor(\n type: string,\n options?: { target: EventTarget; currentTarget: EventTarget }\n ) {\n this.type = type\n this.target = options?.target || null\n this.currentTarget = options?.currentTarget || null\n this.timeStamp = Date.now()\n }\n\n public composedPath(): EventTarget[] {\n return []\n }\n\n public initEvent(type: string, bubbles?: boolean, cancelable?: boolean) {\n this.type = type\n this.bubbles = !!bubbles\n this.cancelable = !!cancelable\n }\n\n public preventDefault() {\n this.defaultPrevented = true\n }\n\n public stopPropagation() {}\n public stopImmediatePropagation() {}\n}\n","import { EventPolyfill } from './EventPolyfill'\n\nexport class ProgressEventPolyfill extends EventPolyfill {\n readonly lengthComputable: boolean\n readonly composed: boolean\n readonly loaded: number\n readonly total: number\n\n constructor(type: string, init?: ProgressEventInit) {\n super(type)\n\n this.lengthComputable = init?.lengthComputable || false\n this.composed = init?.composed || false\n this.loaded = init?.loaded || 0\n this.total = init?.total || 0\n }\n}\n","import { EventPolyfill } from '../polyfills/EventPolyfill'\nimport { ProgressEventPolyfill } from '../polyfills/ProgressEventPolyfill'\n\nconst SUPPORTS_PROGRESS_EVENT = typeof ProgressEvent !== 'undefined'\n\nexport function createEvent(\n target: XMLHttpRequest,\n type: string,\n init?: ProgressEventInit\n): EventPolyfill {\n const progressEvents = [\n 'error',\n 'progress',\n 'loadstart',\n 'loadend',\n 'load',\n 'timeout',\n 'abort',\n ]\n\n /**\n * `ProgressEvent` is not supported in React Native.\n * @see https://github.com/mswjs/interceptors/issues/40\n */\n const ProgressEventClass = SUPPORTS_PROGRESS_EVENT\n ? ProgressEvent\n : ProgressEventPolyfill\n\n const event = progressEvents.includes(type)\n ? new ProgressEventClass(type, {\n lengthComputable: true,\n loaded: init?.loaded || 0,\n total: init?.total || 0,\n })\n : new EventPolyfill(type, {\n target,\n currentTarget: target,\n })\n\n return event\n}\n","/**\n * Returns the source object of the given property on the target object\n * (the target itself, any parent in its prototype, or null).\n */\nexport function findPropertySource(\n target: object,\n propertyName: string | symbol\n): object | null {\n if (!(propertyName in target)) {\n return null\n }\n\n const hasProperty = Object.prototype.hasOwnProperty.call(target, propertyName)\n if (hasProperty) {\n return target\n }\n\n const prototype = Reflect.getPrototypeOf(target)\n return prototype ? findPropertySource(prototype, propertyName) : null\n}\n","import { findPropertySource } from './findPropertySource'\n\nexport interface ProxyOptions> {\n constructorCall?(args: Array, next: NextFunction): Target\n\n methodCall?(\n this: Target,\n data: [methodName: F, args: Array],\n next: NextFunction\n ): void\n\n setProperty?(\n data: [propertyName: string | symbol, nextValue: unknown],\n next: NextFunction\n ): boolean\n\n getProperty?(\n data: [propertyName: string | symbol, receiver: Target],\n next: NextFunction\n ): void\n}\n\nexport type NextFunction = () => ReturnType\n\nexport function createProxy(\n target: Target,\n options: ProxyOptions\n): Target {\n const proxy = new Proxy(target, optionsToProxyHandler(options))\n\n return proxy\n}\n\nfunction optionsToProxyHandler>(\n options: ProxyOptions\n): ProxyHandler {\n const { constructorCall, methodCall, getProperty, setProperty } = options\n const handler: ProxyHandler = {}\n\n if (typeof constructorCall !== 'undefined') {\n handler.construct = function (target, args, newTarget) {\n const next = Reflect.construct.bind(null, target as any, args, newTarget)\n return constructorCall.call(newTarget, args, next)\n }\n }\n\n handler.set = function (target, propertyName, nextValue) {\n const next = () => {\n const propertySource = findPropertySource(target, propertyName) || target\n const ownDescriptors = Reflect.getOwnPropertyDescriptor(\n propertySource,\n propertyName\n )\n\n // Respect any custom setters present for this property.\n if (typeof ownDescriptors?.set !== 'undefined') {\n ownDescriptors.set.apply(target, [nextValue])\n return true\n }\n\n // Otherwise, set the property on the source.\n return Reflect.defineProperty(propertySource, propertyName, {\n writable: true,\n enumerable: true,\n configurable: true,\n value: nextValue,\n })\n }\n\n if (typeof setProperty !== 'undefined') {\n return setProperty.call(target, [propertyName, nextValue], next)\n }\n\n return next()\n }\n\n handler.get = function (target, propertyName, receiver) {\n /**\n * @note Using `Reflect.get()` here causes \"TypeError: Illegal invocation\".\n */\n const next = () => target[propertyName as any]\n\n const value =\n typeof getProperty !== 'undefined'\n ? getProperty.call(target, [propertyName, receiver], next)\n : next()\n\n if (typeof value === 'function') {\n return (...args: Array) => {\n const next = value.bind(target, ...args)\n\n if (typeof methodCall !== 'undefined') {\n return methodCall.call(target, [propertyName as any, args], next)\n }\n\n return next()\n }\n }\n\n return value\n }\n\n return handler\n}\n","export function isDomParserSupportedType(\n type: string\n): type is DOMParserSupportedType {\n const supportedTypes: Array = [\n 'application/xhtml+xml',\n 'application/xml',\n 'image/svg+xml',\n 'text/html',\n 'text/xml',\n ]\n return supportedTypes.some((supportedType) => {\n return type.startsWith(supportedType)\n })\n}\n","/**\n * Parses a given string into JSON.\n * Gracefully handles invalid JSON by returning `null`.\n */\nexport function parseJson(data: string): Record | null {\n try {\n const json = JSON.parse(data)\n return json\n } catch (_) {\n return null\n }\n}\n","import { isResponseWithoutBody } from '../../../utils/responseUtils'\n\n/**\n * Creates a Fetch API `Response` instance from the given\n * `XMLHttpRequest` instance and a response body.\n */\nexport function createResponse(\n request: XMLHttpRequest,\n body: BodyInit | null\n): Response {\n /**\n * Handle XMLHttpRequest responses that must have null as the\n * response body when represented using Fetch API Response.\n * XMLHttpRequest response will always have an empty string\n * as the \"request.response\" in those cases, resulting in an error\n * when constructing a Response instance.\n * @see https://github.com/mswjs/interceptors/issues/379\n */\n const responseBodyOrNull = isResponseWithoutBody(request.status) ? null : body\n\n return new Response(responseBodyOrNull, {\n status: request.status,\n statusText: request.statusText,\n headers: createHeadersFromXMLHttpReqestHeaders(\n request.getAllResponseHeaders()\n ),\n })\n}\n\nfunction createHeadersFromXMLHttpReqestHeaders(headersString: string): Headers {\n const headers = new Headers()\n\n const lines = headersString.split(/[\\r\\n]+/)\n for (const line of lines) {\n if (line.trim() === '') {\n continue\n }\n\n const [name, ...parts] = line.split(': ')\n const value = parts.join(': ')\n\n headers.append(name, value)\n }\n\n return headers\n}\n"]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/chunk-QED3Q6Z2.mjs b/node_modules/@mswjs/interceptors/lib/browser/chunk-QED3Q6Z2.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f71287cc2bb3c1a2b3e2e33bd976835de3dfeea0 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/chunk-QED3Q6Z2.mjs @@ -0,0 +1,169 @@ +// src/Interceptor.ts +import { Logger } from "@open-draft/logger"; +import { Emitter } from "strict-event-emitter"; +var INTERNAL_REQUEST_ID_HEADER_NAME = "x-interceptors-internal-request-id"; +function getGlobalSymbol(symbol) { + return ( + // @ts-ignore https://github.com/Microsoft/TypeScript/issues/24587 + globalThis[symbol] || void 0 + ); +} +function setGlobalSymbol(symbol, value) { + globalThis[symbol] = value; +} +function deleteGlobalSymbol(symbol) { + delete globalThis[symbol]; +} +var InterceptorReadyState = /* @__PURE__ */ ((InterceptorReadyState2) => { + InterceptorReadyState2["INACTIVE"] = "INACTIVE"; + InterceptorReadyState2["APPLYING"] = "APPLYING"; + InterceptorReadyState2["APPLIED"] = "APPLIED"; + InterceptorReadyState2["DISPOSING"] = "DISPOSING"; + InterceptorReadyState2["DISPOSED"] = "DISPOSED"; + return InterceptorReadyState2; +})(InterceptorReadyState || {}); +var Interceptor = class { + constructor(symbol) { + this.symbol = symbol; + this.readyState = "INACTIVE" /* INACTIVE */; + this.emitter = new Emitter(); + this.subscriptions = []; + this.logger = new Logger(symbol.description); + this.emitter.setMaxListeners(0); + this.logger.info("constructing the interceptor..."); + } + /** + * Determine if this interceptor can be applied + * in the current environment. + */ + checkEnvironment() { + return true; + } + /** + * Apply this interceptor to the current process. + * Returns an already running interceptor instance if it's present. + */ + apply() { + const logger = this.logger.extend("apply"); + logger.info("applying the interceptor..."); + if (this.readyState === "APPLIED" /* APPLIED */) { + logger.info("intercepted already applied!"); + return; + } + const shouldApply = this.checkEnvironment(); + if (!shouldApply) { + logger.info("the interceptor cannot be applied in this environment!"); + return; + } + this.readyState = "APPLYING" /* APPLYING */; + const runningInstance = this.getInstance(); + if (runningInstance) { + logger.info("found a running instance, reusing..."); + this.on = (event, listener) => { + logger.info('proxying the "%s" listener', event); + runningInstance.emitter.addListener(event, listener); + this.subscriptions.push(() => { + runningInstance.emitter.removeListener(event, listener); + logger.info('removed proxied "%s" listener!', event); + }); + return this; + }; + this.readyState = "APPLIED" /* APPLIED */; + return; + } + logger.info("no running instance found, setting up a new instance..."); + this.setup(); + this.setInstance(); + this.readyState = "APPLIED" /* APPLIED */; + } + /** + * Setup the module augments and stubs necessary for this interceptor. + * This method is not run if there's a running interceptor instance + * to prevent instantiating an interceptor multiple times. + */ + setup() { + } + /** + * Listen to the interceptor's public events. + */ + on(event, listener) { + const logger = this.logger.extend("on"); + if (this.readyState === "DISPOSING" /* DISPOSING */ || this.readyState === "DISPOSED" /* DISPOSED */) { + logger.info("cannot listen to events, already disposed!"); + return this; + } + logger.info('adding "%s" event listener:', event, listener); + this.emitter.on(event, listener); + return this; + } + once(event, listener) { + this.emitter.once(event, listener); + return this; + } + off(event, listener) { + this.emitter.off(event, listener); + return this; + } + removeAllListeners(event) { + this.emitter.removeAllListeners(event); + return this; + } + /** + * Disposes of any side-effects this interceptor has introduced. + */ + dispose() { + const logger = this.logger.extend("dispose"); + if (this.readyState === "DISPOSED" /* DISPOSED */) { + logger.info("cannot dispose, already disposed!"); + return; + } + logger.info("disposing the interceptor..."); + this.readyState = "DISPOSING" /* DISPOSING */; + if (!this.getInstance()) { + logger.info("no interceptors running, skipping dispose..."); + return; + } + this.clearInstance(); + logger.info("global symbol deleted:", getGlobalSymbol(this.symbol)); + if (this.subscriptions.length > 0) { + logger.info("disposing of %d subscriptions...", this.subscriptions.length); + for (const dispose of this.subscriptions) { + dispose(); + } + this.subscriptions = []; + logger.info("disposed of all subscriptions!", this.subscriptions.length); + } + this.emitter.removeAllListeners(); + logger.info("destroyed the listener!"); + this.readyState = "DISPOSED" /* DISPOSED */; + } + getInstance() { + var _a; + const instance = getGlobalSymbol(this.symbol); + this.logger.info("retrieved global instance:", (_a = instance == null ? void 0 : instance.constructor) == null ? void 0 : _a.name); + return instance; + } + setInstance() { + setGlobalSymbol(this.symbol, this); + this.logger.info("set global instance!", this.symbol.description); + } + clearInstance() { + deleteGlobalSymbol(this.symbol); + this.logger.info("cleared global instance!", this.symbol.description); + } +}; + +// src/createRequestId.ts +function createRequestId() { + return Math.random().toString(16).slice(2); +} + +export { + INTERNAL_REQUEST_ID_HEADER_NAME, + getGlobalSymbol, + deleteGlobalSymbol, + InterceptorReadyState, + Interceptor, + createRequestId +}; +//# sourceMappingURL=chunk-QED3Q6Z2.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/chunk-QED3Q6Z2.mjs.map b/node_modules/@mswjs/interceptors/lib/browser/chunk-QED3Q6Z2.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..1225c8315c0c1bf92027275ccc242fff6276743e --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/chunk-QED3Q6Z2.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/Interceptor.ts","../../src/createRequestId.ts"],"sourcesContent":["import { Logger } from '@open-draft/logger'\nimport { Emitter, Listener } from 'strict-event-emitter'\n\nexport type InterceptorEventMap = Record\nexport type InterceptorSubscription = () => void\n\n/**\n * Request header name to detect when a single request\n * is being handled by nested interceptors (XHR -> ClientRequest).\n * Obscure by design to prevent collisions with user-defined headers.\n * Ideally, come up with the Interceptor-level mechanism for this.\n * @see https://github.com/mswjs/interceptors/issues/378\n */\nexport const INTERNAL_REQUEST_ID_HEADER_NAME =\n 'x-interceptors-internal-request-id'\n\nexport function getGlobalSymbol(symbol: Symbol): V | undefined {\n return (\n // @ts-ignore https://github.com/Microsoft/TypeScript/issues/24587\n globalThis[symbol] || undefined\n )\n}\n\nfunction setGlobalSymbol(symbol: Symbol, value: any): void {\n // @ts-ignore\n globalThis[symbol] = value\n}\n\nexport function deleteGlobalSymbol(symbol: Symbol): void {\n // @ts-ignore\n delete globalThis[symbol]\n}\n\nexport enum InterceptorReadyState {\n INACTIVE = 'INACTIVE',\n APPLYING = 'APPLYING',\n APPLIED = 'APPLIED',\n DISPOSING = 'DISPOSING',\n DISPOSED = 'DISPOSED',\n}\n\nexport type ExtractEventNames> =\n Events extends Record ? EventName : never\n\nexport class Interceptor {\n protected emitter: Emitter\n protected subscriptions: Array\n protected logger: Logger\n\n public readyState: InterceptorReadyState\n\n constructor(private readonly symbol: symbol) {\n this.readyState = InterceptorReadyState.INACTIVE\n\n this.emitter = new Emitter()\n this.subscriptions = []\n this.logger = new Logger(symbol.description!)\n\n // Do not limit the maximum number of listeners\n // so not to limit the maximum amount of parallel events emitted.\n this.emitter.setMaxListeners(0)\n\n this.logger.info('constructing the interceptor...')\n }\n\n /**\n * Determine if this interceptor can be applied\n * in the current environment.\n */\n protected checkEnvironment(): boolean {\n return true\n }\n\n /**\n * Apply this interceptor to the current process.\n * Returns an already running interceptor instance if it's present.\n */\n public apply(): void {\n const logger = this.logger.extend('apply')\n logger.info('applying the interceptor...')\n\n if (this.readyState === InterceptorReadyState.APPLIED) {\n logger.info('intercepted already applied!')\n return\n }\n\n const shouldApply = this.checkEnvironment()\n\n if (!shouldApply) {\n logger.info('the interceptor cannot be applied in this environment!')\n return\n }\n\n this.readyState = InterceptorReadyState.APPLYING\n\n // Whenever applying a new interceptor, check if it hasn't been applied already.\n // This enables to apply the same interceptor multiple times, for example from a different\n // interceptor, only proxying events but keeping the stubs in a single place.\n const runningInstance = this.getInstance()\n\n if (runningInstance) {\n logger.info('found a running instance, reusing...')\n\n // Proxy any listeners you set on this instance to the running instance.\n this.on = (event, listener) => {\n logger.info('proxying the \"%s\" listener', event)\n\n // Add listeners to the running instance so they appear\n // at the top of the event listeners list and are executed first.\n runningInstance.emitter.addListener(event, listener)\n\n // Ensure that once this interceptor instance is disposed,\n // it removes all listeners it has appended to the running interceptor instance.\n this.subscriptions.push(() => {\n runningInstance.emitter.removeListener(event, listener)\n logger.info('removed proxied \"%s\" listener!', event)\n })\n\n return this\n }\n\n this.readyState = InterceptorReadyState.APPLIED\n\n return\n }\n\n logger.info('no running instance found, setting up a new instance...')\n\n // Setup the interceptor.\n this.setup()\n\n // Store the newly applied interceptor instance globally.\n this.setInstance()\n\n this.readyState = InterceptorReadyState.APPLIED\n }\n\n /**\n * Setup the module augments and stubs necessary for this interceptor.\n * This method is not run if there's a running interceptor instance\n * to prevent instantiating an interceptor multiple times.\n */\n protected setup(): void {}\n\n /**\n * Listen to the interceptor's public events.\n */\n public on>(\n event: EventName,\n listener: Listener\n ): this {\n const logger = this.logger.extend('on')\n\n if (\n this.readyState === InterceptorReadyState.DISPOSING ||\n this.readyState === InterceptorReadyState.DISPOSED\n ) {\n logger.info('cannot listen to events, already disposed!')\n return this\n }\n\n logger.info('adding \"%s\" event listener:', event, listener)\n\n this.emitter.on(event, listener)\n return this\n }\n\n public once>(\n event: EventName,\n listener: Listener\n ): this {\n this.emitter.once(event, listener)\n return this\n }\n\n public off>(\n event: EventName,\n listener: Listener\n ): this {\n this.emitter.off(event, listener)\n return this\n }\n\n public removeAllListeners>(\n event?: EventName\n ): this {\n this.emitter.removeAllListeners(event)\n return this\n }\n\n /**\n * Disposes of any side-effects this interceptor has introduced.\n */\n public dispose(): void {\n const logger = this.logger.extend('dispose')\n\n if (this.readyState === InterceptorReadyState.DISPOSED) {\n logger.info('cannot dispose, already disposed!')\n return\n }\n\n logger.info('disposing the interceptor...')\n this.readyState = InterceptorReadyState.DISPOSING\n\n if (!this.getInstance()) {\n logger.info('no interceptors running, skipping dispose...')\n return\n }\n\n // Delete the global symbol as soon as possible,\n // indicating that the interceptor is no longer running.\n this.clearInstance()\n\n logger.info('global symbol deleted:', getGlobalSymbol(this.symbol))\n\n if (this.subscriptions.length > 0) {\n logger.info('disposing of %d subscriptions...', this.subscriptions.length)\n\n for (const dispose of this.subscriptions) {\n dispose()\n }\n\n this.subscriptions = []\n\n logger.info('disposed of all subscriptions!', this.subscriptions.length)\n }\n\n this.emitter.removeAllListeners()\n logger.info('destroyed the listener!')\n\n this.readyState = InterceptorReadyState.DISPOSED\n }\n\n private getInstance(): this | undefined {\n const instance = getGlobalSymbol(this.symbol)\n this.logger.info('retrieved global instance:', instance?.constructor?.name)\n return instance\n }\n\n private setInstance(): void {\n setGlobalSymbol(this.symbol, this)\n this.logger.info('set global instance!', this.symbol.description)\n }\n\n private clearInstance(): void {\n deleteGlobalSymbol(this.symbol)\n this.logger.info('cleared global instance!', this.symbol.description)\n }\n}\n","/**\n * Generate a random ID string to represent a request.\n * @example\n * createRequestId()\n * // \"f774b6c9c600f\"\n */\nexport function createRequestId(): string {\n return Math.random().toString(16).slice(2)\n}\n"],"mappings":"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","names":["InterceptorReadyState"]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/chunk-TIPR373R.js b/node_modules/@mswjs/interceptors/lib/browser/chunk-TIPR373R.js new file mode 100644 index 0000000000000000000000000000000000000000..17ca97fd87f21f48b53121da520b6ddfe4e0d01c --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/chunk-TIPR373R.js @@ -0,0 +1,169 @@ +"use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/Interceptor.ts +var _logger = require('@open-draft/logger'); +var _stricteventemitter = require('strict-event-emitter'); +var INTERNAL_REQUEST_ID_HEADER_NAME = "x-interceptors-internal-request-id"; +function getGlobalSymbol(symbol) { + return ( + // @ts-ignore https://github.com/Microsoft/TypeScript/issues/24587 + globalThis[symbol] || void 0 + ); +} +function setGlobalSymbol(symbol, value) { + globalThis[symbol] = value; +} +function deleteGlobalSymbol(symbol) { + delete globalThis[symbol]; +} +var InterceptorReadyState = /* @__PURE__ */ ((InterceptorReadyState2) => { + InterceptorReadyState2["INACTIVE"] = "INACTIVE"; + InterceptorReadyState2["APPLYING"] = "APPLYING"; + InterceptorReadyState2["APPLIED"] = "APPLIED"; + InterceptorReadyState2["DISPOSING"] = "DISPOSING"; + InterceptorReadyState2["DISPOSED"] = "DISPOSED"; + return InterceptorReadyState2; +})(InterceptorReadyState || {}); +var Interceptor = class { + constructor(symbol) { + this.symbol = symbol; + this.readyState = "INACTIVE" /* INACTIVE */; + this.emitter = new (0, _stricteventemitter.Emitter)(); + this.subscriptions = []; + this.logger = new (0, _logger.Logger)(symbol.description); + this.emitter.setMaxListeners(0); + this.logger.info("constructing the interceptor..."); + } + /** + * Determine if this interceptor can be applied + * in the current environment. + */ + checkEnvironment() { + return true; + } + /** + * Apply this interceptor to the current process. + * Returns an already running interceptor instance if it's present. + */ + apply() { + const logger = this.logger.extend("apply"); + logger.info("applying the interceptor..."); + if (this.readyState === "APPLIED" /* APPLIED */) { + logger.info("intercepted already applied!"); + return; + } + const shouldApply = this.checkEnvironment(); + if (!shouldApply) { + logger.info("the interceptor cannot be applied in this environment!"); + return; + } + this.readyState = "APPLYING" /* APPLYING */; + const runningInstance = this.getInstance(); + if (runningInstance) { + logger.info("found a running instance, reusing..."); + this.on = (event, listener) => { + logger.info('proxying the "%s" listener', event); + runningInstance.emitter.addListener(event, listener); + this.subscriptions.push(() => { + runningInstance.emitter.removeListener(event, listener); + logger.info('removed proxied "%s" listener!', event); + }); + return this; + }; + this.readyState = "APPLIED" /* APPLIED */; + return; + } + logger.info("no running instance found, setting up a new instance..."); + this.setup(); + this.setInstance(); + this.readyState = "APPLIED" /* APPLIED */; + } + /** + * Setup the module augments and stubs necessary for this interceptor. + * This method is not run if there's a running interceptor instance + * to prevent instantiating an interceptor multiple times. + */ + setup() { + } + /** + * Listen to the interceptor's public events. + */ + on(event, listener) { + const logger = this.logger.extend("on"); + if (this.readyState === "DISPOSING" /* DISPOSING */ || this.readyState === "DISPOSED" /* DISPOSED */) { + logger.info("cannot listen to events, already disposed!"); + return this; + } + logger.info('adding "%s" event listener:', event, listener); + this.emitter.on(event, listener); + return this; + } + once(event, listener) { + this.emitter.once(event, listener); + return this; + } + off(event, listener) { + this.emitter.off(event, listener); + return this; + } + removeAllListeners(event) { + this.emitter.removeAllListeners(event); + return this; + } + /** + * Disposes of any side-effects this interceptor has introduced. + */ + dispose() { + const logger = this.logger.extend("dispose"); + if (this.readyState === "DISPOSED" /* DISPOSED */) { + logger.info("cannot dispose, already disposed!"); + return; + } + logger.info("disposing the interceptor..."); + this.readyState = "DISPOSING" /* DISPOSING */; + if (!this.getInstance()) { + logger.info("no interceptors running, skipping dispose..."); + return; + } + this.clearInstance(); + logger.info("global symbol deleted:", getGlobalSymbol(this.symbol)); + if (this.subscriptions.length > 0) { + logger.info("disposing of %d subscriptions...", this.subscriptions.length); + for (const dispose of this.subscriptions) { + dispose(); + } + this.subscriptions = []; + logger.info("disposed of all subscriptions!", this.subscriptions.length); + } + this.emitter.removeAllListeners(); + logger.info("destroyed the listener!"); + this.readyState = "DISPOSED" /* DISPOSED */; + } + getInstance() { + var _a; + const instance = getGlobalSymbol(this.symbol); + this.logger.info("retrieved global instance:", (_a = instance == null ? void 0 : instance.constructor) == null ? void 0 : _a.name); + return instance; + } + setInstance() { + setGlobalSymbol(this.symbol, this); + this.logger.info("set global instance!", this.symbol.description); + } + clearInstance() { + deleteGlobalSymbol(this.symbol); + this.logger.info("cleared global instance!", this.symbol.description); + } +}; + +// src/createRequestId.ts +function createRequestId() { + return Math.random().toString(16).slice(2); +} + + + + + + + + +exports.INTERNAL_REQUEST_ID_HEADER_NAME = INTERNAL_REQUEST_ID_HEADER_NAME; exports.getGlobalSymbol = getGlobalSymbol; exports.deleteGlobalSymbol = deleteGlobalSymbol; exports.InterceptorReadyState = InterceptorReadyState; exports.Interceptor = Interceptor; exports.createRequestId = createRequestId; +//# sourceMappingURL=chunk-TIPR373R.js.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/chunk-TIPR373R.js.map b/node_modules/@mswjs/interceptors/lib/browser/chunk-TIPR373R.js.map new file mode 100644 index 0000000000000000000000000000000000000000..0becb9b1b416a6f58a91a5e4b16674781dfda461 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/chunk-TIPR373R.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/Interceptor.ts","../../src/createRequestId.ts"],"names":["InterceptorReadyState"],"mappings":"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","sourcesContent":["import { Logger } from '@open-draft/logger'\nimport { Emitter, Listener } from 'strict-event-emitter'\n\nexport type InterceptorEventMap = Record\nexport type InterceptorSubscription = () => void\n\n/**\n * Request header name to detect when a single request\n * is being handled by nested interceptors (XHR -> ClientRequest).\n * Obscure by design to prevent collisions with user-defined headers.\n * Ideally, come up with the Interceptor-level mechanism for this.\n * @see https://github.com/mswjs/interceptors/issues/378\n */\nexport const INTERNAL_REQUEST_ID_HEADER_NAME =\n 'x-interceptors-internal-request-id'\n\nexport function getGlobalSymbol(symbol: Symbol): V | undefined {\n return (\n // @ts-ignore https://github.com/Microsoft/TypeScript/issues/24587\n globalThis[symbol] || undefined\n )\n}\n\nfunction setGlobalSymbol(symbol: Symbol, value: any): void {\n // @ts-ignore\n globalThis[symbol] = value\n}\n\nexport function deleteGlobalSymbol(symbol: Symbol): void {\n // @ts-ignore\n delete globalThis[symbol]\n}\n\nexport enum InterceptorReadyState {\n INACTIVE = 'INACTIVE',\n APPLYING = 'APPLYING',\n APPLIED = 'APPLIED',\n DISPOSING = 'DISPOSING',\n DISPOSED = 'DISPOSED',\n}\n\nexport type ExtractEventNames> =\n Events extends Record ? EventName : never\n\nexport class Interceptor {\n protected emitter: Emitter\n protected subscriptions: Array\n protected logger: Logger\n\n public readyState: InterceptorReadyState\n\n constructor(private readonly symbol: symbol) {\n this.readyState = InterceptorReadyState.INACTIVE\n\n this.emitter = new Emitter()\n this.subscriptions = []\n this.logger = new Logger(symbol.description!)\n\n // Do not limit the maximum number of listeners\n // so not to limit the maximum amount of parallel events emitted.\n this.emitter.setMaxListeners(0)\n\n this.logger.info('constructing the interceptor...')\n }\n\n /**\n * Determine if this interceptor can be applied\n * in the current environment.\n */\n protected checkEnvironment(): boolean {\n return true\n }\n\n /**\n * Apply this interceptor to the current process.\n * Returns an already running interceptor instance if it's present.\n */\n public apply(): void {\n const logger = this.logger.extend('apply')\n logger.info('applying the interceptor...')\n\n if (this.readyState === InterceptorReadyState.APPLIED) {\n logger.info('intercepted already applied!')\n return\n }\n\n const shouldApply = this.checkEnvironment()\n\n if (!shouldApply) {\n logger.info('the interceptor cannot be applied in this environment!')\n return\n }\n\n this.readyState = InterceptorReadyState.APPLYING\n\n // Whenever applying a new interceptor, check if it hasn't been applied already.\n // This enables to apply the same interceptor multiple times, for example from a different\n // interceptor, only proxying events but keeping the stubs in a single place.\n const runningInstance = this.getInstance()\n\n if (runningInstance) {\n logger.info('found a running instance, reusing...')\n\n // Proxy any listeners you set on this instance to the running instance.\n this.on = (event, listener) => {\n logger.info('proxying the \"%s\" listener', event)\n\n // Add listeners to the running instance so they appear\n // at the top of the event listeners list and are executed first.\n runningInstance.emitter.addListener(event, listener)\n\n // Ensure that once this interceptor instance is disposed,\n // it removes all listeners it has appended to the running interceptor instance.\n this.subscriptions.push(() => {\n runningInstance.emitter.removeListener(event, listener)\n logger.info('removed proxied \"%s\" listener!', event)\n })\n\n return this\n }\n\n this.readyState = InterceptorReadyState.APPLIED\n\n return\n }\n\n logger.info('no running instance found, setting up a new instance...')\n\n // Setup the interceptor.\n this.setup()\n\n // Store the newly applied interceptor instance globally.\n this.setInstance()\n\n this.readyState = InterceptorReadyState.APPLIED\n }\n\n /**\n * Setup the module augments and stubs necessary for this interceptor.\n * This method is not run if there's a running interceptor instance\n * to prevent instantiating an interceptor multiple times.\n */\n protected setup(): void {}\n\n /**\n * Listen to the interceptor's public events.\n */\n public on>(\n event: EventName,\n listener: Listener\n ): this {\n const logger = this.logger.extend('on')\n\n if (\n this.readyState === InterceptorReadyState.DISPOSING ||\n this.readyState === InterceptorReadyState.DISPOSED\n ) {\n logger.info('cannot listen to events, already disposed!')\n return this\n }\n\n logger.info('adding \"%s\" event listener:', event, listener)\n\n this.emitter.on(event, listener)\n return this\n }\n\n public once>(\n event: EventName,\n listener: Listener\n ): this {\n this.emitter.once(event, listener)\n return this\n }\n\n public off>(\n event: EventName,\n listener: Listener\n ): this {\n this.emitter.off(event, listener)\n return this\n }\n\n public removeAllListeners>(\n event?: EventName\n ): this {\n this.emitter.removeAllListeners(event)\n return this\n }\n\n /**\n * Disposes of any side-effects this interceptor has introduced.\n */\n public dispose(): void {\n const logger = this.logger.extend('dispose')\n\n if (this.readyState === InterceptorReadyState.DISPOSED) {\n logger.info('cannot dispose, already disposed!')\n return\n }\n\n logger.info('disposing the interceptor...')\n this.readyState = InterceptorReadyState.DISPOSING\n\n if (!this.getInstance()) {\n logger.info('no interceptors running, skipping dispose...')\n return\n }\n\n // Delete the global symbol as soon as possible,\n // indicating that the interceptor is no longer running.\n this.clearInstance()\n\n logger.info('global symbol deleted:', getGlobalSymbol(this.symbol))\n\n if (this.subscriptions.length > 0) {\n logger.info('disposing of %d subscriptions...', this.subscriptions.length)\n\n for (const dispose of this.subscriptions) {\n dispose()\n }\n\n this.subscriptions = []\n\n logger.info('disposed of all subscriptions!', this.subscriptions.length)\n }\n\n this.emitter.removeAllListeners()\n logger.info('destroyed the listener!')\n\n this.readyState = InterceptorReadyState.DISPOSED\n }\n\n private getInstance(): this | undefined {\n const instance = getGlobalSymbol(this.symbol)\n this.logger.info('retrieved global instance:', instance?.constructor?.name)\n return instance\n }\n\n private setInstance(): void {\n setGlobalSymbol(this.symbol, this)\n this.logger.info('set global instance!', this.symbol.description)\n }\n\n private clearInstance(): void {\n deleteGlobalSymbol(this.symbol)\n this.logger.info('cleared global instance!', this.symbol.description)\n }\n}\n","/**\n * Generate a random ID string to represent a request.\n * @example\n * createRequestId()\n * // \"f774b6c9c600f\"\n */\nexport function createRequestId(): string {\n return Math.random().toString(16).slice(2)\n}\n"]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/chunk-WBHIW62P.js b/node_modules/@mswjs/interceptors/lib/browser/chunk-WBHIW62P.js new file mode 100644 index 0000000000000000000000000000000000000000..941fd6441cfdbd1707bd8b183d59fb44c3eab07e --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/chunk-WBHIW62P.js @@ -0,0 +1,213 @@ +"use strict";Object.defineProperty(exports, "__esModule", {value: true}); + + +var _chunkMQJ3JOOKjs = require('./chunk-MQJ3JOOK.js'); + + + + +var _chunk2CRB3JAQjs = require('./chunk-2CRB3JAQ.js'); + + + +var _chunkTIPR373Rjs = require('./chunk-TIPR373R.js'); + +// src/interceptors/fetch/index.ts +var _outvariant = require('outvariant'); +var _deferredpromise = require('@open-draft/deferred-promise'); +var _until = require('@open-draft/until'); + +// src/utils/canParseUrl.ts +function canParseUrl(url) { + try { + new URL(url); + return true; + } catch (_error) { + return false; + } +} + +// src/interceptors/fetch/index.ts +var _FetchInterceptor = class extends _chunkTIPR373Rjs.Interceptor { + constructor() { + super(_FetchInterceptor.symbol); + } + checkEnvironment() { + return typeof globalThis !== "undefined" && typeof globalThis.fetch !== "undefined"; + } + async setup() { + const pureFetch = globalThis.fetch; + _outvariant.invariant.call(void 0, + !pureFetch[_chunk2CRB3JAQjs.IS_PATCHED_MODULE], + 'Failed to patch the "fetch" module: already patched.' + ); + globalThis.fetch = async (input, init) => { + var _a; + const requestId = _chunkTIPR373Rjs.createRequestId.call(void 0, ); + const resolvedInput = typeof input === "string" && typeof location !== "undefined" && !canParseUrl(input) ? new URL(input, location.origin) : input; + const request = new Request(resolvedInput, init); + this.logger.info("[%s] %s", request.method, request.url); + const { interactiveRequest, requestController } = _chunkMQJ3JOOKjs.toInteractiveRequest.call(void 0, request); + this.logger.info( + 'emitting the "request" event for %d listener(s)...', + this.emitter.listenerCount("request") + ); + this.emitter.once("request", ({ requestId: pendingRequestId }) => { + if (pendingRequestId !== requestId) { + return; + } + if (requestController.responsePromise.state === "pending") { + requestController.responsePromise.resolve(void 0); + } + }); + this.logger.info("awaiting for the mocked response..."); + const signal = interactiveRequest.signal; + const requestAborted = new (0, _deferredpromise.DeferredPromise)(); + if (signal) { + signal.addEventListener( + "abort", + () => { + requestAborted.reject(signal.reason); + }, + { once: true } + ); + } + const responsePromise = new (0, _deferredpromise.DeferredPromise)(); + const respondWith = (response) => { + this.logger.info("responding with a mock response:", response); + if (this.emitter.listenerCount("response") > 0) { + this.logger.info('emitting the "response" event...'); + const responseClone = response.clone(); + this.emitter.emit("response", { + response: responseClone, + isMockedResponse: true, + request: interactiveRequest, + requestId + }); + } + Object.defineProperty(response, "url", { + writable: false, + enumerable: true, + configurable: false, + value: request.url + }); + responsePromise.resolve(response); + }; + const errorWith = (reason) => { + responsePromise.reject(reason); + }; + const resolverResult = await _until.until.call(void 0, + async () => { + const listenersFinished = _chunkMQJ3JOOKjs.emitAsync.call(void 0, this.emitter, "request", { + request: interactiveRequest, + requestId + }); + await Promise.race([ + requestAborted, + // Put the listeners invocation Promise in the same race condition + // with the request abort Promise because otherwise awaiting the listeners + // would always yield some response (or undefined). + listenersFinished, + requestController.responsePromise + ]); + this.logger.info("all request listeners have been resolved!"); + const mockedResponse2 = await requestController.responsePromise; + this.logger.info("event.respondWith called with:", mockedResponse2); + return mockedResponse2; + } + ); + if (requestAborted.state === "rejected") { + this.logger.info( + "request has been aborted:", + requestAborted.rejectionReason + ); + responsePromise.reject(requestAborted.rejectionReason); + return responsePromise; + } + if (resolverResult.error) { + this.logger.info( + "request listerner threw an error:", + resolverResult.error + ); + if (resolverResult.error instanceof Response) { + if (_chunk2CRB3JAQjs.isResponseError.call(void 0, resolverResult.error)) { + errorWith(createNetworkError(resolverResult.error)); + } else { + respondWith(resolverResult.error); + } + } + if (this.emitter.listenerCount("unhandledException") > 0) { + await _chunkMQJ3JOOKjs.emitAsync.call(void 0, this.emitter, "unhandledException", { + error: resolverResult.error, + request, + requestId, + controller: { + respondWith, + errorWith + } + }); + if (responsePromise.state !== "pending") { + return responsePromise; + } + } + respondWith(_chunk2CRB3JAQjs.createServerErrorResponse.call(void 0, resolverResult.error)); + return responsePromise; + } + const mockedResponse = resolverResult.data; + if (mockedResponse && !((_a = request.signal) == null ? void 0 : _a.aborted)) { + this.logger.info("received mocked response:", mockedResponse); + if (_chunk2CRB3JAQjs.isResponseError.call(void 0, mockedResponse)) { + this.logger.info( + "received a network error response, rejecting the request promise..." + ); + errorWith(createNetworkError(mockedResponse)); + } else { + respondWith(mockedResponse); + } + return responsePromise; + } + this.logger.info("no mocked response received!"); + return pureFetch(request).then((response) => { + this.logger.info("original fetch performed", response); + if (this.emitter.listenerCount("response") > 0) { + this.logger.info('emitting the "response" event...'); + const responseClone = response.clone(); + this.emitter.emit("response", { + response: responseClone, + isMockedResponse: false, + request: interactiveRequest, + requestId + }); + } + return response; + }); + }; + Object.defineProperty(globalThis.fetch, _chunk2CRB3JAQjs.IS_PATCHED_MODULE, { + enumerable: true, + configurable: true, + value: true + }); + this.subscriptions.push(() => { + Object.defineProperty(globalThis.fetch, _chunk2CRB3JAQjs.IS_PATCHED_MODULE, { + value: void 0 + }); + globalThis.fetch = pureFetch; + this.logger.info( + 'restored native "globalThis.fetch"!', + globalThis.fetch.name + ); + }); + } +}; +var FetchInterceptor = _FetchInterceptor; +FetchInterceptor.symbol = Symbol("fetch"); +function createNetworkError(cause) { + return Object.assign(new TypeError("Failed to fetch"), { + cause + }); +} + + + +exports.FetchInterceptor = FetchInterceptor; +//# sourceMappingURL=chunk-WBHIW62P.js.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/chunk-WBHIW62P.js.map b/node_modules/@mswjs/interceptors/lib/browser/chunk-WBHIW62P.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a10ce6c0a3c813ee0577f7365d21509eb17b23b8 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/chunk-WBHIW62P.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/interceptors/fetch/index.ts","../../src/utils/canParseUrl.ts"],"names":["mockedResponse"],"mappings":";;;;;;;;;;;;;;;AAAA,SAAS,iBAAiB;AAC1B,SAAS,uBAAuB;AAChC,SAAS,aAAa;;;ACGf,SAAS,YAAY,KAAsB;AAChD,MAAI;AACF,QAAI,IAAI,GAAG;AACX,WAAO;AAAA,EACT,SAAS,QAAP;AACA,WAAO;AAAA,EACT;AACF;;;ADEO,IAAM,oBAAN,cAA+B,YAAiC;AAAA,EAGrE,cAAc;AACZ,UAAM,kBAAiB,MAAM;AAAA,EAC/B;AAAA,EAEU,mBAAmB;AAC3B,WACE,OAAO,eAAe,eACtB,OAAO,WAAW,UAAU;AAAA,EAEhC;AAAA,EAEA,MAAgB,QAAQ;AACtB,UAAM,YAAY,WAAW;AAE7B;AAAA,MACE,CAAE,UAAkB,iBAAiB;AAAA,MACrC;AAAA,IACF;AAEA,eAAW,QAAQ,OAAO,OAAO,SAAS;AApC9C;AAqCM,YAAM,YAAY,gBAAgB;AAQlC,YAAM,gBACJ,OAAO,UAAU,YACjB,OAAO,aAAa,eACpB,CAAC,YAAY,KAAK,IACd,IAAI,IAAI,OAAO,SAAS,MAAM,IAC9B;AAEN,YAAM,UAAU,IAAI,QAAQ,eAAe,IAAI;AAE/C,WAAK,OAAO,KAAK,WAAW,QAAQ,QAAQ,QAAQ,GAAG;AAEvD,YAAM,EAAE,oBAAoB,kBAAkB,IAC5C,qBAAqB,OAAO;AAE9B,WAAK,OAAO;AAAA,QACV;AAAA,QACA,KAAK,QAAQ,cAAc,SAAS;AAAA,MACtC;AAEA,WAAK,QAAQ,KAAK,WAAW,CAAC,EAAE,WAAW,iBAAiB,MAAM;AAChE,YAAI,qBAAqB,WAAW;AAClC;AAAA,QACF;AAEA,YAAI,kBAAkB,gBAAgB,UAAU,WAAW;AACzD,4BAAkB,gBAAgB,QAAQ,MAAS;AAAA,QACrD;AAAA,MACF,CAAC;AAED,WAAK,OAAO,KAAK,qCAAqC;AAEtD,YAAM,SAAS,mBAAmB;AAClC,YAAM,iBAAiB,IAAI,gBAAgB;AAG3C,UAAI,QAAQ;AACV,eAAO;AAAA,UACL;AAAA,UACA,MAAM;AACJ,2BAAe,OAAO,OAAO,MAAM;AAAA,UACrC;AAAA,UACA,EAAE,MAAM,KAAK;AAAA,QACf;AAAA,MACF;AAEA,YAAM,kBAAkB,IAAI,gBAA0B;AAEtD,YAAM,cAAc,CAAC,aAA6B;AAChD,aAAK,OAAO,KAAK,oCAAoC,QAAQ;AAE7D,YAAI,KAAK,QAAQ,cAAc,UAAU,IAAI,GAAG;AAC9C,eAAK,OAAO,KAAK,kCAAkC;AAKnD,gBAAM,gBAAgB,SAAS,MAAM;AAErC,eAAK,QAAQ,KAAK,YAAY;AAAA,YAC5B,UAAU;AAAA,YACV,kBAAkB;AAAA,YAClB,SAAS;AAAA,YACT;AAAA,UACF,CAAC;AAAA,QACH;AAGA,eAAO,eAAe,UAAU,OAAO;AAAA,UACrC,UAAU;AAAA,UACV,YAAY;AAAA,UACZ,cAAc;AAAA,UACd,OAAO,QAAQ;AAAA,QACjB,CAAC;AAED,wBAAgB,QAAQ,QAAQ;AAAA,MAClC;AAEA,YAAM,YAAY,CAAC,WAA0B;AAC3C,wBAAgB,OAAO,MAAM;AAAA,MAC/B;AAEA,YAAM,iBAAiB,MAAM;AAAA,QAC3B,YAAY;AACV,gBAAM,oBAAoB,UAAU,KAAK,SAAS,WAAW;AAAA,YAC3D,SAAS;AAAA,YACT;AAAA,UACF,CAAC;AAED,gBAAM,QAAQ,KAAK;AAAA,YACjB;AAAA;AAAA;AAAA;AAAA,YAIA;AAAA,YACA,kBAAkB;AAAA,UACpB,CAAC;AAED,eAAK,OAAO,KAAK,2CAA2C;AAE5D,gBAAMA,kBAAiB,MAAM,kBAAkB;AAC/C,eAAK,OAAO,KAAK,kCAAkCA,eAAc;AAEjE,iBAAOA;AAAA,QACT;AAAA,MACF;AAEA,UAAI,eAAe,UAAU,YAAY;AACvC,aAAK,OAAO;AAAA,UACV;AAAA,UACA,eAAe;AAAA,QACjB;AAEA,wBAAgB,OAAO,eAAe,eAAe;AACrD,eAAO;AAAA,MACT;AAEA,UAAI,eAAe,OAAO;AACxB,aAAK,OAAO;AAAA,UACV;AAAA,UACA,eAAe;AAAA,QACjB;AAGA,YAAI,eAAe,iBAAiB,UAAU;AAE5C,cAAI,gBAAgB,eAAe,KAAK,GAAG;AACzC,sBAAU,mBAAmB,eAAe,KAAK,CAAC;AAAA,UACpD,OAAO;AAEL,wBAAY,eAAe,KAAK;AAAA,UAClC;AAAA,QACF;AAKA,YAAI,KAAK,QAAQ,cAAc,oBAAoB,IAAI,GAAG;AACxD,gBAAM,UAAU,KAAK,SAAS,sBAAsB;AAAA,YAClD,OAAO,eAAe;AAAA,YACtB;AAAA,YACA;AAAA,YACA,YAAY;AAAA,cACV;AAAA,cACA;AAAA,YACF;AAAA,UACF,CAAC;AAED,cAAI,gBAAgB,UAAU,WAAW;AACvC,mBAAO;AAAA,UACT;AAAA,QACF;AAKA,oBAAY,0BAA0B,eAAe,KAAK,CAAC;AAC3D,eAAO;AAAA,MACT;AAEA,YAAM,iBAAiB,eAAe;AAEtC,UAAI,kBAAkB,GAAC,aAAQ,WAAR,mBAAgB,UAAS;AAC9C,aAAK,OAAO,KAAK,6BAA6B,cAAc;AAG5D,YAAI,gBAAgB,cAAc,GAAG;AACnC,eAAK,OAAO;AAAA,YACV;AAAA,UACF;AAUA,oBAAU,mBAAmB,cAAc,CAAC;AAAA,QAC9C,OAAO;AACL,sBAAY,cAAc;AAAA,QAC5B;AAEA,eAAO;AAAA,MACT;AAEA,WAAK,OAAO,KAAK,8BAA8B;AAE/C,aAAO,UAAU,OAAO,EAAE,KAAK,CAAC,aAAa;AAC3C,aAAK,OAAO,KAAK,4BAA4B,QAAQ;AAErD,YAAI,KAAK,QAAQ,cAAc,UAAU,IAAI,GAAG;AAC9C,eAAK,OAAO,KAAK,kCAAkC;AAEnD,gBAAM,gBAAgB,SAAS,MAAM;AAErC,eAAK,QAAQ,KAAK,YAAY;AAAA,YAC5B,UAAU;AAAA,YACV,kBAAkB;AAAA,YAClB,SAAS;AAAA,YACT;AAAA,UACF,CAAC;AAAA,QACH;AAEA,eAAO;AAAA,MACT,CAAC;AAAA,IACH;AAEA,WAAO,eAAe,WAAW,OAAO,mBAAmB;AAAA,MACzD,YAAY;AAAA,MACZ,cAAc;AAAA,MACd,OAAO;AAAA,IACT,CAAC;AAED,SAAK,cAAc,KAAK,MAAM;AAC5B,aAAO,eAAe,WAAW,OAAO,mBAAmB;AAAA,QACzD,OAAO;AAAA,MACT,CAAC;AAED,iBAAW,QAAQ;AAEnB,WAAK,OAAO;AAAA,QACV;AAAA,QACA,WAAW,MAAM;AAAA,MACnB;AAAA,IACF,CAAC;AAAA,EACH;AACF;AAlQO,IAAM,mBAAN;AAAM,iBACJ,SAAS,OAAO,OAAO;AAmQhC,SAAS,mBAAmB,OAAgB;AAC1C,SAAO,OAAO,OAAO,IAAI,UAAU,iBAAiB,GAAG;AAAA,IACrD;AAAA,EACF,CAAC;AACH","sourcesContent":["import { invariant } from 'outvariant'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { until } from '@open-draft/until'\nimport { HttpRequestEventMap, IS_PATCHED_MODULE } from '../../glossary'\nimport { Interceptor } from '../../Interceptor'\nimport { toInteractiveRequest } from '../../utils/toInteractiveRequest'\nimport { emitAsync } from '../../utils/emitAsync'\nimport { canParseUrl } from '../../utils/canParseUrl'\nimport { createRequestId } from '../../createRequestId'\nimport {\n createServerErrorResponse,\n isResponseError,\n} from '../../utils/responseUtils'\n\nexport class FetchInterceptor extends Interceptor {\n static symbol = Symbol('fetch')\n\n constructor() {\n super(FetchInterceptor.symbol)\n }\n\n protected checkEnvironment() {\n return (\n typeof globalThis !== 'undefined' &&\n typeof globalThis.fetch !== 'undefined'\n )\n }\n\n protected async setup() {\n const pureFetch = globalThis.fetch\n\n invariant(\n !(pureFetch as any)[IS_PATCHED_MODULE],\n 'Failed to patch the \"fetch\" module: already patched.'\n )\n\n globalThis.fetch = async (input, init) => {\n const requestId = createRequestId()\n\n /**\n * @note Resolve potentially relative request URL\n * against the present `location`. This is mainly\n * for native `fetch` in JSDOM.\n * @see https://github.com/mswjs/msw/issues/1625\n */\n const resolvedInput =\n typeof input === 'string' &&\n typeof location !== 'undefined' &&\n !canParseUrl(input)\n ? new URL(input, location.origin)\n : input\n\n const request = new Request(resolvedInput, init)\n\n this.logger.info('[%s] %s', request.method, request.url)\n\n const { interactiveRequest, requestController } =\n toInteractiveRequest(request)\n\n this.logger.info(\n 'emitting the \"request\" event for %d listener(s)...',\n this.emitter.listenerCount('request')\n )\n\n this.emitter.once('request', ({ requestId: pendingRequestId }) => {\n if (pendingRequestId !== requestId) {\n return\n }\n\n if (requestController.responsePromise.state === 'pending') {\n requestController.responsePromise.resolve(undefined)\n }\n })\n\n this.logger.info('awaiting for the mocked response...')\n\n const signal = interactiveRequest.signal\n const requestAborted = new DeferredPromise()\n\n // Signal isn't always defined in react-native.\n if (signal) {\n signal.addEventListener(\n 'abort',\n () => {\n requestAborted.reject(signal.reason)\n },\n { once: true }\n )\n }\n\n const responsePromise = new DeferredPromise()\n\n const respondWith = (response: Response): void => {\n this.logger.info('responding with a mock response:', response)\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n // Clone the mocked response for the \"response\" event listener.\n // This way, the listener can read the response and not lock its body\n // for the actual fetch consumer.\n const responseClone = response.clone()\n\n this.emitter.emit('response', {\n response: responseClone,\n isMockedResponse: true,\n request: interactiveRequest,\n requestId,\n })\n }\n\n // Set the \"response.url\" property to equal the intercepted request URL.\n Object.defineProperty(response, 'url', {\n writable: false,\n enumerable: true,\n configurable: false,\n value: request.url,\n })\n\n responsePromise.resolve(response)\n }\n\n const errorWith = (reason: unknown): void => {\n responsePromise.reject(reason)\n }\n\n const resolverResult = await until(\n async () => {\n const listenersFinished = emitAsync(this.emitter, 'request', {\n request: interactiveRequest,\n requestId,\n })\n\n await Promise.race([\n requestAborted,\n // Put the listeners invocation Promise in the same race condition\n // with the request abort Promise because otherwise awaiting the listeners\n // would always yield some response (or undefined).\n listenersFinished,\n requestController.responsePromise,\n ])\n\n this.logger.info('all request listeners have been resolved!')\n\n const mockedResponse = await requestController.responsePromise\n this.logger.info('event.respondWith called with:', mockedResponse)\n\n return mockedResponse\n }\n )\n\n if (requestAborted.state === 'rejected') {\n this.logger.info(\n 'request has been aborted:',\n requestAborted.rejectionReason\n )\n\n responsePromise.reject(requestAborted.rejectionReason)\n return responsePromise\n }\n\n if (resolverResult.error) {\n this.logger.info(\n 'request listerner threw an error:',\n resolverResult.error\n )\n\n // Treat thrown Responses as mocked responses.\n if (resolverResult.error instanceof Response) {\n // Treat thrown Response.error() as a request error.\n if (isResponseError(resolverResult.error)) {\n errorWith(createNetworkError(resolverResult.error))\n } else {\n // Treat the rest of thrown Responses as mocked responses.\n respondWith(resolverResult.error)\n }\n }\n\n // Emit the \"unhandledException\" interceptor event so the client\n // can opt-out from exceptions translating to 500 error responses.\n\n if (this.emitter.listenerCount('unhandledException') > 0) {\n await emitAsync(this.emitter, 'unhandledException', {\n error: resolverResult.error,\n request,\n requestId,\n controller: {\n respondWith,\n errorWith,\n },\n })\n\n if (responsePromise.state !== 'pending') {\n return responsePromise\n }\n }\n\n // Unhandled exceptions in the request listeners are\n // synonymous to unhandled exceptions on the server.\n // Those are represented as 500 error responses.\n respondWith(createServerErrorResponse(resolverResult.error))\n return responsePromise\n }\n\n const mockedResponse = resolverResult.data\n\n if (mockedResponse && !request.signal?.aborted) {\n this.logger.info('received mocked response:', mockedResponse)\n\n // Reject the request Promise on mocked \"Response.error\" responses.\n if (isResponseError(mockedResponse)) {\n this.logger.info(\n 'received a network error response, rejecting the request promise...'\n )\n\n /**\n * Set the cause of the request promise rejection to the\n * network error Response instance. This differs from Undici.\n * Undici will forward the \"response.error\" custom property\n * as the rejection reason but for \"Response.error()\" static method\n * \"response.error\" will equal to undefined, making \"cause\" an empty Error.\n * @see https://github.com/nodejs/undici/blob/83cb522ae0157a19d149d72c7d03d46e34510d0a/lib/fetch/response.js#L344\n */\n errorWith(createNetworkError(mockedResponse))\n } else {\n respondWith(mockedResponse)\n }\n\n return responsePromise\n }\n\n this.logger.info('no mocked response received!')\n\n return pureFetch(request).then((response) => {\n this.logger.info('original fetch performed', response)\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n const responseClone = response.clone()\n\n this.emitter.emit('response', {\n response: responseClone,\n isMockedResponse: false,\n request: interactiveRequest,\n requestId,\n })\n }\n\n return response\n })\n }\n\n Object.defineProperty(globalThis.fetch, IS_PATCHED_MODULE, {\n enumerable: true,\n configurable: true,\n value: true,\n })\n\n this.subscriptions.push(() => {\n Object.defineProperty(globalThis.fetch, IS_PATCHED_MODULE, {\n value: undefined,\n })\n\n globalThis.fetch = pureFetch\n\n this.logger.info(\n 'restored native \"globalThis.fetch\"!',\n globalThis.fetch.name\n )\n })\n }\n}\n\nfunction createNetworkError(cause: unknown) {\n return Object.assign(new TypeError('Failed to fetch'), {\n cause,\n })\n}\n","/**\n * Returns a boolean indicating whether the given URL string\n * can be parsed into a `URL` instance.\n * A substitute for `URL.canParse()` for Node.js 18.\n */\nexport function canParseUrl(url: string): boolean {\n try {\n new URL(url)\n return true\n } catch (_error) {\n return false\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/glossary-1c204f45.d.ts b/node_modules/@mswjs/interceptors/lib/browser/glossary-1c204f45.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a9bd3925dd66040e9e1eb5ce0866dfb377d14313 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/glossary-1c204f45.d.ts @@ -0,0 +1,44 @@ +import { DeferredPromise } from '@open-draft/deferred-promise'; + +declare class RequestController { + protected request: Request; + responsePromise: DeferredPromise; + constructor(request: Request); + respondWith(response?: Response): void; +} + +type InteractiveRequest = globalThis.Request & { + respondWith: RequestController['respondWith']; +}; + +declare const IS_PATCHED_MODULE: unique symbol; +type RequestCredentials = 'omit' | 'include' | 'same-origin'; +type HttpRequestEventMap = { + request: [ + args: { + request: InteractiveRequest; + requestId: string; + } + ]; + response: [ + args: { + response: Response; + isMockedResponse: boolean; + request: Request; + requestId: string; + } + ]; + unhandledException: [ + args: { + error: unknown; + request: Request; + requestId: string; + controller: { + respondWith(response: Response): void; + errorWith(error?: Error): void; + }; + } + ]; +}; + +export { HttpRequestEventMap as H, IS_PATCHED_MODULE as I, RequestCredentials as R, InteractiveRequest as a }; diff --git a/node_modules/@mswjs/interceptors/lib/browser/index.d.ts b/node_modules/@mswjs/interceptors/lib/browser/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7b9d366da6c881b1e9576472a2eabcb7e7ea8eac --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/index.d.ts @@ -0,0 +1,50 @@ +export { H as HttpRequestEventMap, I as IS_PATCHED_MODULE, R as RequestCredentials } from './glossary-1c204f45.js'; +import { I as Interceptor, E as ExtractEventNames } from './Interceptor-af98b768.js'; +export { c as INTERNAL_REQUEST_ID_HEADER_NAME, a as InterceptorEventMap, e as InterceptorReadyState, b as InterceptorSubscription, d as deleteGlobalSymbol, g as getGlobalSymbol } from './Interceptor-af98b768.js'; +import { EventMap, Listener } from 'strict-event-emitter'; +import '@open-draft/deferred-promise'; +import '@open-draft/logger'; + +interface BatchInterceptorOptions>> { + name: string; + interceptors: InterceptorList; +} +type ExtractEventMapType>> = InterceptorList extends ReadonlyArray ? InterceptorType extends Interceptor ? EventMap : never : never; +/** + * A batch interceptor that exposes a single interface + * to apply and operate with multiple interceptors at once. + */ +declare class BatchInterceptor>, Events extends EventMap = ExtractEventMapType> extends Interceptor { + static symbol: symbol; + private interceptors; + constructor(options: BatchInterceptorOptions); + protected setup(): void; + on>(event: EventName, listener: Listener): this; + once>(event: EventName, listener: Listener): this; + off>(event: EventName, listener: Listener): this; + removeAllListeners>(event?: EventName | undefined): this; +} + +/** + * Generate a random ID string to represent a request. + * @example + * createRequestId() + * // "f774b6c9c600f" + */ +declare function createRequestId(): string; + +/** + * Removes query parameters and hashes from a given URL. + */ +declare function getCleanUrl(url: URL, isAbsolute?: boolean): string; + +declare function encodeBuffer(text: string): Uint8Array; +declare function decodeBuffer(buffer: ArrayBuffer, encoding?: string): string; + +/** + * Returns a boolean indicating whether the given response status + * code represents a response that cannot have a body. + */ +declare function isResponseWithoutBody(status: number): boolean; + +export { BatchInterceptor, BatchInterceptorOptions, ExtractEventMapType, ExtractEventNames, Interceptor, createRequestId, decodeBuffer, encodeBuffer, getCleanUrl, isResponseWithoutBody }; diff --git a/node_modules/@mswjs/interceptors/lib/browser/index.js b/node_modules/@mswjs/interceptors/lib/browser/index.js new file mode 100644 index 0000000000000000000000000000000000000000..8ad0c3e3058b5d04f814579682ee5f293390dfbe --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/index.js @@ -0,0 +1,79 @@ +"use strict";Object.defineProperty(exports, "__esModule", {value: true}); + + +var _chunkLK6DILFKjs = require('./chunk-LK6DILFK.js'); + + + +var _chunk2CRB3JAQjs = require('./chunk-2CRB3JAQ.js'); + + + + + + + +var _chunkTIPR373Rjs = require('./chunk-TIPR373R.js'); + +// src/BatchInterceptor.ts +var BatchInterceptor = class extends _chunkTIPR373Rjs.Interceptor { + constructor(options) { + BatchInterceptor.symbol = Symbol(options.name); + super(BatchInterceptor.symbol); + this.interceptors = options.interceptors; + } + setup() { + const logger = this.logger.extend("setup"); + logger.info("applying all %d interceptors...", this.interceptors.length); + for (const interceptor of this.interceptors) { + logger.info('applying "%s" interceptor...', interceptor.constructor.name); + interceptor.apply(); + logger.info("adding interceptor dispose subscription"); + this.subscriptions.push(() => interceptor.dispose()); + } + } + on(event, listener) { + for (const interceptor of this.interceptors) { + interceptor.on(event, listener); + } + return this; + } + once(event, listener) { + for (const interceptor of this.interceptors) { + interceptor.once(event, listener); + } + return this; + } + off(event, listener) { + for (const interceptor of this.interceptors) { + interceptor.off(event, listener); + } + return this; + } + removeAllListeners(event) { + for (const interceptors of this.interceptors) { + interceptors.removeAllListeners(event); + } + return this; + } +}; + +// src/utils/getCleanUrl.ts +function getCleanUrl(url, isAbsolute = true) { + return [isAbsolute && url.origin, url.pathname].filter(Boolean).join(""); +} + + + + + + + + + + + + + +exports.BatchInterceptor = BatchInterceptor; exports.INTERNAL_REQUEST_ID_HEADER_NAME = _chunkTIPR373Rjs.INTERNAL_REQUEST_ID_HEADER_NAME; exports.IS_PATCHED_MODULE = _chunk2CRB3JAQjs.IS_PATCHED_MODULE; exports.Interceptor = _chunkTIPR373Rjs.Interceptor; exports.InterceptorReadyState = _chunkTIPR373Rjs.InterceptorReadyState; exports.createRequestId = _chunkTIPR373Rjs.createRequestId; exports.decodeBuffer = _chunkLK6DILFKjs.decodeBuffer; exports.deleteGlobalSymbol = _chunkTIPR373Rjs.deleteGlobalSymbol; exports.encodeBuffer = _chunkLK6DILFKjs.encodeBuffer; exports.getCleanUrl = getCleanUrl; exports.getGlobalSymbol = _chunkTIPR373Rjs.getGlobalSymbol; exports.isResponseWithoutBody = _chunk2CRB3JAQjs.isResponseWithoutBody; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/index.js.map b/node_modules/@mswjs/interceptors/lib/browser/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..34e4b31b1d249cbb7ca34026baa30d81f8aadedd --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/BatchInterceptor.ts","../../src/utils/getCleanUrl.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAsBO,IAAM,mBAAN,cAGG,YAAoB;AAAA,EAK5B,YAAY,SAAmD;AAC7D,qBAAiB,SAAS,OAAO,QAAQ,IAAI;AAC7C,UAAM,iBAAiB,MAAM;AAC7B,SAAK,eAAe,QAAQ;AAAA,EAC9B;AAAA,EAEU,QAAQ;AAChB,UAAM,SAAS,KAAK,OAAO,OAAO,OAAO;AAEzC,WAAO,KAAK,mCAAmC,KAAK,aAAa,MAAM;AAEvE,eAAW,eAAe,KAAK,cAAc;AAC3C,aAAO,KAAK,gCAAgC,YAAY,YAAY,IAAI;AACxE,kBAAY,MAAM;AAElB,aAAO,KAAK,yCAAyC;AACrD,WAAK,cAAc,KAAK,MAAM,YAAY,QAAQ,CAAC;AAAA,IACrD;AAAA,EACF;AAAA,EAEO,GACL,OACA,UACM;AAGN,eAAW,eAAe,KAAK,cAAc;AAC3C,kBAAY,GAAG,OAAO,QAAQ;AAAA,IAChC;AAEA,WAAO;AAAA,EACT;AAAA,EAEO,KACL,OACA,UACM;AACN,eAAW,eAAe,KAAK,cAAc;AAC3C,kBAAY,KAAK,OAAO,QAAQ;AAAA,IAClC;AAEA,WAAO;AAAA,EACT;AAAA,EAEO,IACL,OACA,UACM;AACN,eAAW,eAAe,KAAK,cAAc;AAC3C,kBAAY,IAAI,OAAO,QAAQ;AAAA,IACjC;AAEA,WAAO;AAAA,EACT;AAAA,EAEO,mBACL,OACM;AACN,eAAW,gBAAgB,KAAK,cAAc;AAC5C,mBAAa,mBAAmB,KAAK;AAAA,IACvC;AAEA,WAAO;AAAA,EACT;AACF;;;AC3FO,SAAS,YAAY,KAAU,aAAsB,MAAc;AACxE,SAAO,CAAC,cAAc,IAAI,QAAQ,IAAI,QAAQ,EAAE,OAAO,OAAO,EAAE,KAAK,EAAE;AACzE","sourcesContent":["import { EventMap, Listener } from 'strict-event-emitter'\nimport { Interceptor, ExtractEventNames } from './Interceptor'\n\nexport interface BatchInterceptorOptions<\n InterceptorList extends ReadonlyArray>\n> {\n name: string\n interceptors: InterceptorList\n}\n\nexport type ExtractEventMapType<\n InterceptorList extends ReadonlyArray>\n> = InterceptorList extends ReadonlyArray\n ? InterceptorType extends Interceptor\n ? EventMap\n : never\n : never\n\n/**\n * A batch interceptor that exposes a single interface\n * to apply and operate with multiple interceptors at once.\n */\nexport class BatchInterceptor<\n InterceptorList extends ReadonlyArray>,\n Events extends EventMap = ExtractEventMapType\n> extends Interceptor {\n static symbol: symbol\n\n private interceptors: InterceptorList\n\n constructor(options: BatchInterceptorOptions) {\n BatchInterceptor.symbol = Symbol(options.name)\n super(BatchInterceptor.symbol)\n this.interceptors = options.interceptors\n }\n\n protected setup() {\n const logger = this.logger.extend('setup')\n\n logger.info('applying all %d interceptors...', this.interceptors.length)\n\n for (const interceptor of this.interceptors) {\n logger.info('applying \"%s\" interceptor...', interceptor.constructor.name)\n interceptor.apply()\n\n logger.info('adding interceptor dispose subscription')\n this.subscriptions.push(() => interceptor.dispose())\n }\n }\n\n public on>(\n event: EventName,\n listener: Listener\n ): this {\n // Instead of adding a listener to the batch interceptor,\n // propagate the listener to each of the individual interceptors.\n for (const interceptor of this.interceptors) {\n interceptor.on(event, listener)\n }\n\n return this\n }\n\n public once>(\n event: EventName,\n listener: Listener\n ): this {\n for (const interceptor of this.interceptors) {\n interceptor.once(event, listener)\n }\n\n return this\n }\n\n public off>(\n event: EventName,\n listener: Listener\n ): this {\n for (const interceptor of this.interceptors) {\n interceptor.off(event, listener)\n }\n\n return this\n }\n\n public removeAllListeners>(\n event?: EventName | undefined\n ): this {\n for (const interceptors of this.interceptors) {\n interceptors.removeAllListeners(event)\n }\n\n return this\n }\n}\n","/**\n * Removes query parameters and hashes from a given URL.\n */\nexport function getCleanUrl(url: URL, isAbsolute: boolean = true): string {\n return [isAbsolute && url.origin, url.pathname].filter(Boolean).join('')\n}\n"]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/index.mjs b/node_modules/@mswjs/interceptors/lib/browser/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..98efc936465b23f1ddb70458901c998761fa83cd --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/index.mjs @@ -0,0 +1,79 @@ +import { + decodeBuffer, + encodeBuffer +} from "./chunk-6HYIRFX2.mjs"; +import { + IS_PATCHED_MODULE, + isResponseWithoutBody +} from "./chunk-OMISYKWR.mjs"; +import { + INTERNAL_REQUEST_ID_HEADER_NAME, + Interceptor, + InterceptorReadyState, + createRequestId, + deleteGlobalSymbol, + getGlobalSymbol +} from "./chunk-QED3Q6Z2.mjs"; + +// src/BatchInterceptor.ts +var BatchInterceptor = class extends Interceptor { + constructor(options) { + BatchInterceptor.symbol = Symbol(options.name); + super(BatchInterceptor.symbol); + this.interceptors = options.interceptors; + } + setup() { + const logger = this.logger.extend("setup"); + logger.info("applying all %d interceptors...", this.interceptors.length); + for (const interceptor of this.interceptors) { + logger.info('applying "%s" interceptor...', interceptor.constructor.name); + interceptor.apply(); + logger.info("adding interceptor dispose subscription"); + this.subscriptions.push(() => interceptor.dispose()); + } + } + on(event, listener) { + for (const interceptor of this.interceptors) { + interceptor.on(event, listener); + } + return this; + } + once(event, listener) { + for (const interceptor of this.interceptors) { + interceptor.once(event, listener); + } + return this; + } + off(event, listener) { + for (const interceptor of this.interceptors) { + interceptor.off(event, listener); + } + return this; + } + removeAllListeners(event) { + for (const interceptors of this.interceptors) { + interceptors.removeAllListeners(event); + } + return this; + } +}; + +// src/utils/getCleanUrl.ts +function getCleanUrl(url, isAbsolute = true) { + return [isAbsolute && url.origin, url.pathname].filter(Boolean).join(""); +} +export { + BatchInterceptor, + INTERNAL_REQUEST_ID_HEADER_NAME, + IS_PATCHED_MODULE, + Interceptor, + InterceptorReadyState, + createRequestId, + decodeBuffer, + deleteGlobalSymbol, + encodeBuffer, + getCleanUrl, + getGlobalSymbol, + isResponseWithoutBody +}; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/index.mjs.map b/node_modules/@mswjs/interceptors/lib/browser/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..4cc8acce11e1956ea8e80b2245200503af23f1d7 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/BatchInterceptor.ts","../../src/utils/getCleanUrl.ts"],"sourcesContent":["import { EventMap, Listener } from 'strict-event-emitter'\nimport { Interceptor, ExtractEventNames } from './Interceptor'\n\nexport interface BatchInterceptorOptions<\n InterceptorList extends ReadonlyArray>\n> {\n name: string\n interceptors: InterceptorList\n}\n\nexport type ExtractEventMapType<\n InterceptorList extends ReadonlyArray>\n> = InterceptorList extends ReadonlyArray\n ? InterceptorType extends Interceptor\n ? EventMap\n : never\n : never\n\n/**\n * A batch interceptor that exposes a single interface\n * to apply and operate with multiple interceptors at once.\n */\nexport class BatchInterceptor<\n InterceptorList extends ReadonlyArray>,\n Events extends EventMap = ExtractEventMapType\n> extends Interceptor {\n static symbol: symbol\n\n private interceptors: InterceptorList\n\n constructor(options: BatchInterceptorOptions) {\n BatchInterceptor.symbol = Symbol(options.name)\n super(BatchInterceptor.symbol)\n this.interceptors = options.interceptors\n }\n\n protected setup() {\n const logger = this.logger.extend('setup')\n\n logger.info('applying all %d interceptors...', this.interceptors.length)\n\n for (const interceptor of this.interceptors) {\n logger.info('applying \"%s\" interceptor...', interceptor.constructor.name)\n interceptor.apply()\n\n logger.info('adding interceptor dispose subscription')\n this.subscriptions.push(() => interceptor.dispose())\n }\n }\n\n public on>(\n event: EventName,\n listener: Listener\n ): this {\n // Instead of adding a listener to the batch interceptor,\n // propagate the listener to each of the individual interceptors.\n for (const interceptor of this.interceptors) {\n interceptor.on(event, listener)\n }\n\n return this\n }\n\n public once>(\n event: EventName,\n listener: Listener\n ): this {\n for (const interceptor of this.interceptors) {\n interceptor.once(event, listener)\n }\n\n return this\n }\n\n public off>(\n event: EventName,\n listener: Listener\n ): this {\n for (const interceptor of this.interceptors) {\n interceptor.off(event, listener)\n }\n\n return this\n }\n\n public removeAllListeners>(\n event?: EventName | undefined\n ): this {\n for (const interceptors of this.interceptors) {\n interceptors.removeAllListeners(event)\n }\n\n return this\n }\n}\n","/**\n * Removes query parameters and hashes from a given URL.\n */\nexport function getCleanUrl(url: URL, isAbsolute: boolean = true): string {\n return [isAbsolute && url.origin, url.pathname].filter(Boolean).join('')\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAsBO,IAAM,mBAAN,cAGG,YAAoB;AAAA,EAK5B,YAAY,SAAmD;AAC7D,qBAAiB,SAAS,OAAO,QAAQ,IAAI;AAC7C,UAAM,iBAAiB,MAAM;AAC7B,SAAK,eAAe,QAAQ;AAAA,EAC9B;AAAA,EAEU,QAAQ;AAChB,UAAM,SAAS,KAAK,OAAO,OAAO,OAAO;AAEzC,WAAO,KAAK,mCAAmC,KAAK,aAAa,MAAM;AAEvE,eAAW,eAAe,KAAK,cAAc;AAC3C,aAAO,KAAK,gCAAgC,YAAY,YAAY,IAAI;AACxE,kBAAY,MAAM;AAElB,aAAO,KAAK,yCAAyC;AACrD,WAAK,cAAc,KAAK,MAAM,YAAY,QAAQ,CAAC;AAAA,IACrD;AAAA,EACF;AAAA,EAEO,GACL,OACA,UACM;AAGN,eAAW,eAAe,KAAK,cAAc;AAC3C,kBAAY,GAAG,OAAO,QAAQ;AAAA,IAChC;AAEA,WAAO;AAAA,EACT;AAAA,EAEO,KACL,OACA,UACM;AACN,eAAW,eAAe,KAAK,cAAc;AAC3C,kBAAY,KAAK,OAAO,QAAQ;AAAA,IAClC;AAEA,WAAO;AAAA,EACT;AAAA,EAEO,IACL,OACA,UACM;AACN,eAAW,eAAe,KAAK,cAAc;AAC3C,kBAAY,IAAI,OAAO,QAAQ;AAAA,IACjC;AAEA,WAAO;AAAA,EACT;AAAA,EAEO,mBACL,OACM;AACN,eAAW,gBAAgB,KAAK,cAAc;AAC5C,mBAAa,mBAAmB,KAAK;AAAA,IACvC;AAEA,WAAO;AAAA,EACT;AACF;;;AC3FO,SAAS,YAAY,KAAU,aAAsB,MAAc;AACxE,SAAO,CAAC,cAAc,IAAI,QAAQ,IAAI,QAAQ,EAAE,OAAO,OAAO,EAAE,KAAK,EAAE;AACzE;","names":[]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.d.ts b/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3afd485e465e165d34aca9f7a77e5e548605a0e1 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.d.ts @@ -0,0 +1,221 @@ +import { I as Interceptor } from '../../Interceptor-af98b768.js'; +import '@open-draft/logger'; +import 'strict-event-emitter'; + +interface CloseEventInit extends EventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +declare class CloseEvent extends Event { + code: number; + reason: string; + wasClean: boolean; + constructor(type: string, init?: CloseEventInit); +} + +type WebSocketData = string | ArrayBufferLike | Blob | ArrayBufferView; +type WebSocketTransportEventMap = { + incoming: MessageEvent; + outgoing: MessageEvent; + close: CloseEvent; +}; +type StrictEventListenerOrEventListenerObject = ((this: WebSocket, event: EventType) => void) | { + handleEvent(this: WebSocket, event: EventType): void; +}; +interface WebSocketTransport { + addEventListener(event: EventType, listener: StrictEventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void; + dispatchEvent(event: WebSocketTransportEventMap[EventType]): boolean; + /** + * Send the data from the server to this client. + */ + send(data: WebSocketData): void; + /** + * Close the client connection. + */ + close(code?: number, reason?: string): void; +} + +type WebSocketEventListener = (this: WebSocket, event: EventType) => void; +declare const kOnSend: unique symbol; +declare const kClose: unique symbol; +declare class WebSocketOverride extends EventTarget implements WebSocket { + static readonly CONNECTING = 0; + static readonly OPEN = 1; + static readonly CLOSING = 2; + static readonly CLOSED = 3; + readonly CONNECTING = 0; + readonly OPEN = 1; + readonly CLOSING = 2; + readonly CLOSED = 3; + url: string; + protocol: string; + extensions: string; + binaryType: BinaryType; + readyState: number; + bufferedAmount: number; + private _onopen; + private _onmessage; + private _onerror; + private _onclose; + private [kOnSend]?; + constructor(url: string | URL, protocols?: string | Array); + set onopen(listener: WebSocketEventListener | null); + get onopen(): WebSocketEventListener | null; + set onmessage(listener: WebSocketEventListener> | null); + get onmessage(): WebSocketEventListener> | null; + set onerror(listener: WebSocketEventListener | null); + get onerror(): WebSocketEventListener | null; + set onclose(listener: WebSocketEventListener | null); + get onclose(): WebSocketEventListener | null; + /** + * @see https://websockets.spec.whatwg.org/#ref-for-dom-websocket-send%E2%91%A0 + */ + send(data: WebSocketData): void; + close(code?: number, reason?: string): void; + private [kClose]; + addEventListener(type: K, listener: (this: WebSocket, event: WebSocketEventMap[K]) => void, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, callback: EventListenerOrEventListenerObject | null, options?: boolean | EventListenerOptions): void; +} + +declare const kEmitter$1: unique symbol; +interface WebSocketClientEventMap { + message: MessageEvent; + close: CloseEvent; +} +interface WebSocketClientConnectionProtocol { + id: string; + url: URL; + send(data: WebSocketData): void; + close(code?: number, reason?: string): void; +} +/** + * The WebSocket client instance represents an incoming + * client connection. The user can control the connection, + * send and receive events. + */ +declare class WebSocketClientConnection implements WebSocketClientConnectionProtocol { + readonly socket: WebSocket; + private readonly transport; + readonly id: string; + readonly url: URL; + private [kEmitter$1]; + constructor(socket: WebSocket, transport: WebSocketTransport); + /** + * Listen for the outgoing events from the connected WebSocket client. + */ + addEventListener(type: EventType, listener: WebSocketEventListener, options?: AddEventListenerOptions | boolean): void; + /** + * Removes the listener for the given event. + */ + removeEventListener(event: EventType, listener: WebSocketEventListener, options?: EventListenerOptions | boolean): void; + /** + * Send data to the connected client. + */ + send(data: WebSocketData): void; + /** + * Close the WebSocket connection. + * @param {number} code A status code (see https://www.rfc-editor.org/rfc/rfc6455#section-7.4.1). + * @param {string} reason A custom connection close reason. + */ + close(code?: number, reason?: string): void; +} + +/** + * Abstraction over the given mock `WebSocket` instance that allows + * for controlling that instance (e.g. sending and receiving messages). + */ +declare class WebSocketClassTransport extends EventTarget implements WebSocketTransport { + protected readonly socket: WebSocketOverride; + constructor(socket: WebSocketOverride); + addEventListener(type: EventType, callback: StrictEventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void; + dispatchEvent(event: WebSocketTransportEventMap[EventType]): boolean; + send(data: WebSocketData): void; + close(code: number, reason?: string): void; +} + +declare const kEmitter: unique symbol; +interface WebSocketServerEventMap { + open: Event; + message: MessageEvent; + error: Event; + close: CloseEvent; +} +/** + * The WebSocket server instance represents the actual production + * WebSocket server connection. It's idle by default but you can + * establish it by calling `server.connect()`. + */ +declare class WebSocketServerConnection { + private readonly socket; + private readonly transport; + private readonly createConnection; + /** + * A WebSocket instance connected to the original server. + */ + private realWebSocket?; + private mockCloseController; + private [kEmitter]; + constructor(socket: WebSocketOverride, transport: WebSocketClassTransport, createConnection: () => WebSocket); + /** + * Server ready state. + * Proxies the ready state of the original WebSocket instance, + * if set. If the original connection hasn't been established, + * defaults to `-1`. + */ + get readyState(): number; + /** + * Open connection to the original WebSocket server. + */ + connect(): void; + /** + * Listen for the incoming events from the original WebSocket server. + */ + addEventListener(event: EventType, listener: WebSocketEventListener, options?: AddEventListenerOptions | boolean): void; + /** + * Remove the listener for the given event. + */ + removeEventListener(event: EventType, listener: WebSocketEventListener, options?: EventListenerOptions | boolean): void; + /** + * Send data to the original WebSocket server. + * @example + * server.send('hello') + * server.send(new Blob(['hello'])) + * server.send(new TextEncoder().encode('hello')) + */ + send(data: WebSocketData): void; + /** + * Close the actual server connection. + */ + close(): void; + private handleIncomingMessage; + private handleMockClose; + private handleRealClose; +} + +type WebSocketEventMap$1 = { + connection: [args: WebSocketConnectionData]; +}; +type WebSocketConnectionData = { + /** + * The incoming WebSocket client connection. + */ + client: WebSocketClientConnection; + /** + * The original WebSocket server connection. + */ + server: WebSocketServerConnection; +}; +/** + * Intercept the outgoing WebSocket connections created using + * the global `WebSocket` class. + */ +declare class WebSocketInterceptor extends Interceptor { + static symbol: symbol; + constructor(); + protected checkEnvironment(): boolean; + protected setup(): void; +} + +export { WebSocketClientConnection, WebSocketClientConnectionProtocol, WebSocketConnectionData, WebSocketData, WebSocketEventMap$1 as WebSocketEventMap, WebSocketInterceptor, WebSocketServerConnection, WebSocketTransport }; diff --git a/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.js b/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f62dae866e6e061e17b8663bcf97ebce6d28b75f --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.js @@ -0,0 +1,582 @@ +"use strict";Object.defineProperty(exports, "__esModule", {value: true}); + + +var _chunkTIPR373Rjs = require('../../chunk-TIPR373R.js'); + +// src/interceptors/WebSocket/utils/bindEvent.ts +function bindEvent(target, event) { + Object.defineProperties(event, { + target: { + value: target, + enumerable: true, + writable: true + }, + currentTarget: { + value: target, + enumerable: true, + writable: true + } + }); + return event; +} + +// src/interceptors/WebSocket/utils/events.ts +var kCancelable = Symbol("kCancelable"); +var kDefaultPrevented = Symbol("kDefaultPrevented"); +var CancelableMessageEvent = class extends MessageEvent { + constructor(type, init) { + super(type, init); + this[kCancelable] = !!init.cancelable; + this[kDefaultPrevented] = false; + } + get cancelable() { + return this[kCancelable]; + } + set cancelable(nextCancelable) { + this[kCancelable] = nextCancelable; + } + get defaultPrevented() { + return this[kDefaultPrevented]; + } + set defaultPrevented(nextDefaultPrevented) { + this[kDefaultPrevented] = nextDefaultPrevented; + } + preventDefault() { + if (this.cancelable && !this[kDefaultPrevented]) { + this[kDefaultPrevented] = true; + } + } +}; +kCancelable, kDefaultPrevented; +var CloseEvent = class extends Event { + constructor(type, init = {}) { + super(type, init); + this.code = init.code === void 0 ? 0 : init.code; + this.reason = init.reason === void 0 ? "" : init.reason; + this.wasClean = init.wasClean === void 0 ? false : init.wasClean; + } +}; + +// src/interceptors/WebSocket/WebSocketClientConnection.ts +var kEmitter = Symbol("kEmitter"); +var kBoundListener = Symbol("kBoundListener"); +var WebSocketClientConnection = class { + constructor(socket, transport) { + this.socket = socket; + this.transport = transport; + this.id = _chunkTIPR373Rjs.createRequestId.call(void 0, ); + this.url = new URL(socket.url); + this[kEmitter] = new EventTarget(); + this.transport.addEventListener("outgoing", (event) => { + const message = bindEvent( + this.socket, + new CancelableMessageEvent("message", { + data: event.data, + origin: event.origin, + cancelable: true + }) + ); + this[kEmitter].dispatchEvent(message); + if (message.defaultPrevented) { + event.preventDefault(); + } + }); + this.transport.addEventListener("close", (event) => { + this[kEmitter].dispatchEvent( + bindEvent(this.socket, new CloseEvent("close", event)) + ); + }); + } + /** + * Listen for the outgoing events from the connected WebSocket client. + */ + addEventListener(type, listener, options) { + const boundListener = listener.bind(this.socket); + Object.defineProperty(listener, kBoundListener, { + value: boundListener, + enumerable: false + }); + this[kEmitter].addEventListener( + type, + boundListener, + options + ); + } + /** + * Removes the listener for the given event. + */ + removeEventListener(event, listener, options) { + this[kEmitter].removeEventListener( + event, + Reflect.get(listener, kBoundListener), + options + ); + } + /** + * Send data to the connected client. + */ + send(data) { + this.transport.send(data); + } + /** + * Close the WebSocket connection. + * @param {number} code A status code (see https://www.rfc-editor.org/rfc/rfc6455#section-7.4.1). + * @param {string} reason A custom connection close reason. + */ + close(code, reason) { + this.transport.close(code, reason); + } +}; +kEmitter; + +// src/interceptors/WebSocket/WebSocketServerConnection.ts +var _outvariant = require('outvariant'); + +// src/interceptors/WebSocket/WebSocketOverride.ts + +var WEBSOCKET_CLOSE_CODE_RANGE_ERROR = "InvalidAccessError: close code out of user configurable range"; +var kOnSend = Symbol("kOnSend"); +var kClose = Symbol("kClose"); +var WebSocketOverride = class extends EventTarget { + constructor(url, protocols) { + super(); + this.CONNECTING = 0; + this.OPEN = 1; + this.CLOSING = 2; + this.CLOSED = 3; + this._onopen = null; + this._onmessage = null; + this._onerror = null; + this._onclose = null; + this.url = url.toString(); + this.protocol = ""; + this.extensions = ""; + this.binaryType = "blob"; + this.readyState = this.CONNECTING; + this.bufferedAmount = 0; + Reflect.set(this, "readyState", this.CONNECTING); + queueMicrotask(() => { + Reflect.set(this, "readyState", this.OPEN); + this.protocol = protocols ? protocols[0] : "ws"; + this.dispatchEvent(bindEvent(this, new Event("open"))); + }); + } + set onopen(listener) { + this.removeEventListener("open", this._onopen); + this._onopen = listener; + if (listener !== null) { + this.addEventListener("open", listener); + } + } + get onopen() { + return this._onopen; + } + set onmessage(listener) { + this.removeEventListener( + "message", + this._onmessage + ); + this._onmessage = listener; + if (listener !== null) { + this.addEventListener("message", listener); + } + } + get onmessage() { + return this._onmessage; + } + set onerror(listener) { + this.removeEventListener("error", this._onerror); + this._onerror = listener; + if (listener !== null) { + this.addEventListener("error", listener); + } + } + get onerror() { + return this._onerror; + } + set onclose(listener) { + this.removeEventListener("close", this._onclose); + this._onclose = listener; + if (listener !== null) { + this.addEventListener("close", listener); + } + } + get onclose() { + return this._onclose; + } + /** + * @see https://websockets.spec.whatwg.org/#ref-for-dom-websocket-send%E2%91%A0 + */ + send(data) { + if (this.readyState === this.CONNECTING) { + this.close(); + throw new DOMException("InvalidStateError"); + } + if (this.readyState === this.CLOSING || this.readyState === this.CLOSED) { + return; + } + this.bufferedAmount += getDataSize(data); + queueMicrotask(() => { + var _a; + this.bufferedAmount = 0; + (_a = this[kOnSend]) == null ? void 0 : _a.call(this, data); + }); + } + close(code = 1e3, reason) { + _outvariant.invariant.call(void 0, code, WEBSOCKET_CLOSE_CODE_RANGE_ERROR); + _outvariant.invariant.call(void 0, + code === 1e3 || code >= 3e3 && code <= 4999, + WEBSOCKET_CLOSE_CODE_RANGE_ERROR + ); + if (this.readyState === this.CLOSING || this.readyState === this.CLOSED) { + return; + } + this[kClose](code, reason); + } + [(kOnSend, kClose)](code = 1e3, reason) { + this.readyState = this.CLOSING; + queueMicrotask(() => { + this.readyState = this.CLOSED; + if (code > 1e3 && code <= 1015) { + this.dispatchEvent(bindEvent(this, new Event("error"))); + } + this.dispatchEvent( + bindEvent( + this, + new CloseEvent("close", { + code, + reason, + wasClean: code === 1e3 + }) + ) + ); + this._onopen = null; + this._onmessage = null; + this._onerror = null; + this._onclose = null; + }); + } + addEventListener(type, listener, options) { + return super.addEventListener( + type, + listener, + options + ); + } + removeEventListener(type, callback, options) { + return super.removeEventListener(type, callback, options); + } +}; +WebSocketOverride.CONNECTING = 0; +WebSocketOverride.OPEN = 1; +WebSocketOverride.CLOSING = 2; +WebSocketOverride.CLOSED = 3; +function getDataSize(data) { + if (typeof data === "string") { + return data.length; + } + if (data instanceof Blob) { + return data.size; + } + return data.byteLength; +} + +// src/interceptors/WebSocket/WebSocketServerConnection.ts +var kEmitter2 = Symbol("kEmitter"); +var kBoundListener2 = Symbol("kBoundListener"); +var WebSocketServerConnection = class { + constructor(socket, transport, createConnection) { + this.socket = socket; + this.transport = transport; + this.createConnection = createConnection; + this[kEmitter2] = new EventTarget(); + this.mockCloseController = new AbortController(); + this.transport.addEventListener("outgoing", (event) => { + if (this.readyState === -1) { + return; + } + queueMicrotask(() => { + if (!event.defaultPrevented) { + this.send(event.data); + } + }); + }); + this.transport.addEventListener( + "incoming", + this.handleIncomingMessage.bind(this) + ); + } + /** + * Server ready state. + * Proxies the ready state of the original WebSocket instance, + * if set. If the original connection hasn't been established, + * defaults to `-1`. + */ + get readyState() { + if (this.realWebSocket) { + return this.realWebSocket.readyState; + } + return -1; + } + /** + * Open connection to the original WebSocket server. + */ + connect() { + _outvariant.invariant.call(void 0, + !this.realWebSocket || this.realWebSocket.readyState !== WebSocket.OPEN, + 'Failed to call "connect()" on the original WebSocket instance: the connection already open' + ); + const realWebSocket = this.createConnection(); + realWebSocket.binaryType = this.socket.binaryType; + realWebSocket.addEventListener( + "open", + (event) => { + this[kEmitter2].dispatchEvent( + bindEvent(this.realWebSocket, new Event("open", event)) + ); + }, + { once: true } + ); + realWebSocket.addEventListener("message", (event) => { + this.transport.dispatchEvent( + bindEvent( + this.realWebSocket, + new MessageEvent("incoming", { + data: event.data, + origin: event.origin + }) + ) + ); + }); + this.socket.addEventListener("close", this.handleMockClose.bind(this), { + signal: this.mockCloseController.signal + }); + realWebSocket.addEventListener("close", this.handleRealClose.bind(this)); + realWebSocket.addEventListener("error", () => { + this.socket.dispatchEvent(bindEvent(this.socket, new Event("error"))); + }); + this.realWebSocket = realWebSocket; + } + /** + * Listen for the incoming events from the original WebSocket server. + */ + addEventListener(event, listener, options) { + const boundListener = listener.bind(this.socket); + Object.defineProperty(listener, kBoundListener2, { + value: boundListener, + enumerable: false + }); + this[kEmitter2].addEventListener( + event, + boundListener, + options + ); + } + /** + * Remove the listener for the given event. + */ + removeEventListener(event, listener, options) { + this[kEmitter2].removeEventListener( + event, + Reflect.get(listener, kBoundListener2), + options + ); + } + /** + * Send data to the original WebSocket server. + * @example + * server.send('hello') + * server.send(new Blob(['hello'])) + * server.send(new TextEncoder().encode('hello')) + */ + send(data) { + const { realWebSocket } = this; + _outvariant.invariant.call(void 0, + realWebSocket, + 'Failed to call "server.send()" for "%s": the connection is not open. Did you forget to call "server.connect()"?', + this.socket.url + ); + if (realWebSocket.readyState === WebSocket.CLOSING || realWebSocket.readyState === WebSocket.CLOSED) { + return; + } + if (realWebSocket.readyState === WebSocket.CONNECTING) { + realWebSocket.addEventListener( + "open", + () => { + realWebSocket.send(data); + }, + { once: true } + ); + return; + } + realWebSocket.send(data); + } + /** + * Close the actual server connection. + */ + close() { + const { realWebSocket } = this; + _outvariant.invariant.call(void 0, + realWebSocket, + 'Failed to close server connection for "%s": the connection is not open. Did you forget to call "server.connect()"?', + this.socket.url + ); + realWebSocket.removeEventListener("close", this.handleRealClose); + if (realWebSocket.readyState === WebSocket.CLOSING || realWebSocket.readyState === WebSocket.CLOSED) { + return; + } + realWebSocket.close(); + queueMicrotask(() => { + this[kEmitter2].dispatchEvent( + bindEvent(this.realWebSocket, new CloseEvent("close")) + ); + }); + } + handleIncomingMessage(event) { + const messageEvent = bindEvent( + event.target, + new CancelableMessageEvent("message", { + data: event.data, + origin: event.origin, + cancelable: true + }) + ); + this[kEmitter2].dispatchEvent(messageEvent); + if (!messageEvent.defaultPrevented) { + this.socket.dispatchEvent( + bindEvent( + /** + * @note Bind the forwarded original server events + * to the mock WebSocket instance so it would + * dispatch them straight away. + */ + this.socket, + // Clone the message event again to prevent + // the "already being dispatched" exception. + new MessageEvent("message", { + data: event.data, + origin: event.origin + }) + ) + ); + } + } + handleMockClose(_event) { + if (this.realWebSocket) { + this.realWebSocket.close(); + } + } + handleRealClose(event) { + this.mockCloseController.abort(); + const closeEvent = bindEvent( + this.realWebSocket, + new CloseEvent("close", event) + ); + this[kEmitter2].dispatchEvent(closeEvent); + if (!closeEvent.defaultPrevented) { + this.socket[kClose](event.code, event.reason); + } + } +}; +kEmitter2; + +// src/interceptors/WebSocket/WebSocketClassTransport.ts +var WebSocketClassTransport = class extends EventTarget { + constructor(socket) { + super(); + this.socket = socket; + this.socket.addEventListener("close", (event) => { + this.dispatchEvent(bindEvent(this.socket, new CloseEvent("close", event))); + }); + this.socket[kOnSend] = (data) => { + this.dispatchEvent( + bindEvent( + this.socket, + // Dispatch this as cancelable because "client" connection + // re-creates this message event (cannot dispatch the same event). + new CancelableMessageEvent("outgoing", { + data, + origin: this.socket.url, + cancelable: true + }) + ) + ); + }; + } + addEventListener(type, callback, options) { + return super.addEventListener(type, callback, options); + } + dispatchEvent(event) { + return super.dispatchEvent(event); + } + send(data) { + queueMicrotask(() => { + this.socket.dispatchEvent( + bindEvent( + /** + * @note Setting this event's "target" to the + * WebSocket override instance is important. + * This way it can tell apart original incoming events + * (must be forwarded to the transport) from the + * mocked message events like the one below + * (must be dispatched on the client instance). + */ + this.socket, + new MessageEvent("message", { + data, + origin: this.socket.url + }) + ) + ); + }); + } + close(code, reason) { + this.socket[kClose](code, reason); + } +}; + +// src/interceptors/WebSocket/index.ts +var _WebSocketInterceptor = class extends _chunkTIPR373Rjs.Interceptor { + constructor() { + super(_WebSocketInterceptor.symbol); + } + checkEnvironment() { + return typeof globalThis.WebSocket !== "undefined"; + } + setup() { + const originalWebSocket = globalThis.WebSocket; + const webSocketProxy = new Proxy(globalThis.WebSocket, { + construct: (target, args, newTarget) => { + const [url, protocols] = args; + const createConnection = () => { + return Reflect.construct(target, args, newTarget); + }; + const socket = new WebSocketOverride(url, protocols); + const transport = new WebSocketClassTransport(socket); + queueMicrotask(() => { + this.emitter.emit("connection", { + client: new WebSocketClientConnection(socket, transport), + server: new WebSocketServerConnection( + socket, + transport, + createConnection + ) + }); + }); + return socket; + } + }); + globalThis.WebSocket = webSocketProxy; + this.subscriptions.push(() => { + globalThis.WebSocket = originalWebSocket; + }); + } +}; +var WebSocketInterceptor = _WebSocketInterceptor; +WebSocketInterceptor.symbol = Symbol("websocket"); + + + + +exports.WebSocketClientConnection = WebSocketClientConnection; exports.WebSocketInterceptor = WebSocketInterceptor; exports.WebSocketServerConnection = WebSocketServerConnection; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.js.map b/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..10175a5d4c95e9ebc4d2abe24194fb4c2fc23af6 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/interceptors/WebSocket/utils/bindEvent.ts","../../../../src/interceptors/WebSocket/utils/events.ts","../../../../src/interceptors/WebSocket/WebSocketClientConnection.ts","../../../../src/interceptors/WebSocket/WebSocketServerConnection.ts","../../../../src/interceptors/WebSocket/WebSocketOverride.ts","../../../../src/interceptors/WebSocket/WebSocketClassTransport.ts","../../../../src/interceptors/WebSocket/index.ts"],"names":["invariant","kEmitter","kBoundListener"],"mappings":"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","sourcesContent":["type EventWithTarget = E & { target: T }\n\nexport function bindEvent(\n target: T,\n event: E\n): EventWithTarget {\n Object.defineProperties(event, {\n target: {\n value: target,\n enumerable: true,\n writable: true,\n },\n currentTarget: {\n value: target,\n enumerable: true,\n writable: true,\n },\n })\n\n return event as EventWithTarget\n}\n","const kCancelable = Symbol('kCancelable')\nconst kDefaultPrevented = Symbol('kDefaultPrevented')\n\n/**\n * A `MessageEvent` superset that supports event cancellation\n * in Node.js. It's rather non-intrusive so it can be safely\n * used in the browser as well.\n *\n * @see https://github.com/nodejs/node/issues/51767\n */\nexport class CancelableMessageEvent extends MessageEvent {\n [kCancelable]: boolean;\n [kDefaultPrevented]: boolean\n\n constructor(type: string, init: MessageEventInit) {\n super(type, init)\n this[kCancelable] = !!init.cancelable\n this[kDefaultPrevented] = false\n }\n\n get cancelable() {\n return this[kCancelable]\n }\n\n set cancelable(nextCancelable) {\n this[kCancelable] = nextCancelable\n }\n\n get defaultPrevented() {\n return this[kDefaultPrevented]\n }\n\n set defaultPrevented(nextDefaultPrevented) {\n this[kDefaultPrevented] = nextDefaultPrevented\n }\n\n public preventDefault(): void {\n if (this.cancelable && !this[kDefaultPrevented]) {\n this[kDefaultPrevented] = true\n }\n }\n}\n\ninterface CloseEventInit extends EventInit {\n code?: number\n reason?: string\n wasClean?: boolean\n}\n\nexport class CloseEvent extends Event {\n public code: number\n public reason: string\n public wasClean: boolean\n\n constructor(type: string, init: CloseEventInit = {}) {\n super(type, init)\n this.code = init.code === undefined ? 0 : init.code\n this.reason = init.reason === undefined ? '' : init.reason\n this.wasClean = init.wasClean === undefined ? false : init.wasClean\n }\n}\n","import type { WebSocketData, WebSocketTransport } from './WebSocketTransport'\nimport type { WebSocketEventListener } from './WebSocketOverride'\nimport { bindEvent } from './utils/bindEvent'\nimport { CancelableMessageEvent, CloseEvent } from './utils/events'\nimport { createRequestId } from '../../createRequestId'\n\nconst kEmitter = Symbol('kEmitter')\nconst kBoundListener = Symbol('kBoundListener')\n\ninterface WebSocketClientEventMap {\n message: MessageEvent\n close: CloseEvent\n}\n\nexport interface WebSocketClientConnectionProtocol {\n id: string\n url: URL\n send(data: WebSocketData): void\n close(code?: number, reason?: string): void\n}\n\n/**\n * The WebSocket client instance represents an incoming\n * client connection. The user can control the connection,\n * send and receive events.\n */\nexport class WebSocketClientConnection\n implements WebSocketClientConnectionProtocol\n{\n public readonly id: string\n public readonly url: URL\n\n private [kEmitter]: EventTarget\n\n constructor(\n public readonly socket: WebSocket,\n private readonly transport: WebSocketTransport\n ) {\n this.id = createRequestId()\n this.url = new URL(socket.url)\n this[kEmitter] = new EventTarget()\n\n // Emit outgoing client data (\"ws.send()\") as \"message\"\n // events on the \"client\" connection.\n this.transport.addEventListener('outgoing', (event) => {\n const message = bindEvent(\n this.socket,\n new CancelableMessageEvent('message', {\n data: event.data,\n origin: event.origin,\n cancelable: true,\n })\n )\n\n this[kEmitter].dispatchEvent(message)\n\n // This is a bit silly but forward the cancellation state\n // of the \"client\" message event to the \"outgoing\" transport event.\n // This way, other agens (like \"server\" connection) can know\n // whether the client listener has pervented the default.\n if (message.defaultPrevented) {\n event.preventDefault()\n }\n })\n\n /**\n * Emit the \"close\" event on the \"client\" connection\n * whenever the underlying transport is closed.\n * @note \"client.close()\" does NOT dispatch the \"close\"\n * event on the WebSocket because it uses non-configurable\n * close status code. Thus, we listen to the transport\n * instead of the WebSocket's \"close\" event.\n */\n this.transport.addEventListener('close', (event) => {\n this[kEmitter].dispatchEvent(\n bindEvent(this.socket, new CloseEvent('close', event))\n )\n })\n }\n\n /**\n * Listen for the outgoing events from the connected WebSocket client.\n */\n public addEventListener(\n type: EventType,\n listener: WebSocketEventListener,\n options?: AddEventListenerOptions | boolean\n ): void {\n const boundListener = listener.bind(this.socket)\n\n // Store the bound listener on the original listener\n // so the exact bound function can be accessed in \"removeEventListener()\".\n Object.defineProperty(listener, kBoundListener, {\n value: boundListener,\n enumerable: false,\n })\n\n this[kEmitter].addEventListener(\n type,\n boundListener as EventListener,\n options\n )\n }\n\n /**\n * Removes the listener for the given event.\n */\n public removeEventListener(\n event: EventType,\n listener: WebSocketEventListener,\n options?: EventListenerOptions | boolean\n ): void {\n this[kEmitter].removeEventListener(\n event,\n Reflect.get(listener, kBoundListener) as EventListener,\n options\n )\n }\n\n /**\n * Send data to the connected client.\n */\n public send(data: WebSocketData): void {\n this.transport.send(data)\n }\n\n /**\n * Close the WebSocket connection.\n * @param {number} code A status code (see https://www.rfc-editor.org/rfc/rfc6455#section-7.4.1).\n * @param {string} reason A custom connection close reason.\n */\n public close(code?: number, reason?: string): void {\n this.transport.close(code, reason)\n }\n}\n","import { invariant } from 'outvariant'\nimport {\n kClose,\n WebSocketEventListener,\n WebSocketOverride,\n} from './WebSocketOverride'\nimport type { WebSocketData } from './WebSocketTransport'\nimport type { WebSocketClassTransport } from './WebSocketClassTransport'\nimport { bindEvent } from './utils/bindEvent'\nimport { CancelableMessageEvent, CloseEvent } from './utils/events'\n\nconst kEmitter = Symbol('kEmitter')\nconst kBoundListener = Symbol('kBoundListener')\n\ninterface WebSocketServerEventMap {\n open: Event\n message: MessageEvent\n error: Event\n close: CloseEvent\n}\n\n/**\n * The WebSocket server instance represents the actual production\n * WebSocket server connection. It's idle by default but you can\n * establish it by calling `server.connect()`.\n */\nexport class WebSocketServerConnection {\n /**\n * A WebSocket instance connected to the original server.\n */\n private realWebSocket?: WebSocket\n private mockCloseController: AbortController\n private [kEmitter]: EventTarget\n\n constructor(\n private readonly socket: WebSocketOverride,\n private readonly transport: WebSocketClassTransport,\n private readonly createConnection: () => WebSocket\n ) {\n this[kEmitter] = new EventTarget()\n this.mockCloseController = new AbortController()\n\n // Automatically forward outgoing client events\n // to the actual server unless the outgoing message event\n // has been prevented. The \"outgoing\" transport event it\n // dispatched by the \"client\" connection.\n this.transport.addEventListener('outgoing', (event) => {\n // Ignore client messages if the server connection\n // hasn't been established yet. Nowhere to forward.\n if (this.readyState === -1) {\n return\n }\n\n // Every outgoing client message can prevent this forwarding\n // by preventing the default of the outgoing message event.\n // This listener will be added before user-defined listeners,\n // so execute the logic on the next tick.\n queueMicrotask(() => {\n if (!event.defaultPrevented) {\n this.send(event.data)\n }\n })\n })\n\n this.transport.addEventListener(\n 'incoming',\n this.handleIncomingMessage.bind(this)\n )\n }\n\n /**\n * Server ready state.\n * Proxies the ready state of the original WebSocket instance,\n * if set. If the original connection hasn't been established,\n * defaults to `-1`.\n */\n public get readyState(): number {\n if (this.realWebSocket) {\n return this.realWebSocket.readyState\n }\n\n return -1\n }\n\n /**\n * Open connection to the original WebSocket server.\n */\n public connect(): void {\n invariant(\n !this.realWebSocket || this.realWebSocket.readyState !== WebSocket.OPEN,\n 'Failed to call \"connect()\" on the original WebSocket instance: the connection already open'\n )\n\n const realWebSocket = this.createConnection()\n\n // Inherit the binary type from the mock WebSocket client.\n realWebSocket.binaryType = this.socket.binaryType\n\n // Allow the interceptor to listen to when the server connection\n // has been established. This isn't necessary to operate with the connection\n // but may be beneficial in some cases (like conditionally adding logging).\n realWebSocket.addEventListener(\n 'open',\n (event) => {\n this[kEmitter].dispatchEvent(\n bindEvent(this.realWebSocket!, new Event('open', event))\n )\n },\n { once: true }\n )\n\n realWebSocket.addEventListener('message', (event) => {\n // Dispatch the \"incoming\" transport event instead of\n // invoking the internal handler directly. This way,\n // anyone can listen to the \"incoming\" event but this\n // class is the one resulting in it.\n this.transport.dispatchEvent(\n bindEvent(\n this.realWebSocket!,\n new MessageEvent('incoming', {\n data: event.data,\n origin: event.origin,\n })\n )\n )\n })\n\n // Close the original connection when the mock client closes.\n // E.g. \"client.close()\" was called.\n this.socket.addEventListener('close', this.handleMockClose.bind(this), {\n signal: this.mockCloseController.signal,\n })\n\n // Forward the \"close\" event to let the interceptor handle\n // closures initiated by the original server.\n realWebSocket.addEventListener('close', this.handleRealClose.bind(this))\n\n // Forward server errors to the WebSocket client as-is.\n // We may consider exposing them to the interceptor in the future.\n realWebSocket.addEventListener('error', () => {\n this.socket.dispatchEvent(bindEvent(this.socket, new Event('error')))\n })\n\n this.realWebSocket = realWebSocket\n }\n\n /**\n * Listen for the incoming events from the original WebSocket server.\n */\n public addEventListener(\n event: EventType,\n listener: WebSocketEventListener,\n options?: AddEventListenerOptions | boolean\n ): void {\n const boundListener = listener.bind(this.socket)\n\n // Store the bound listener on the original listener\n // so the exact bound function can be accessed in \"removeEventListener()\".\n Object.defineProperty(listener, kBoundListener, {\n value: boundListener,\n enumerable: false,\n })\n\n this[kEmitter].addEventListener(\n event,\n boundListener as EventListener,\n options\n )\n }\n\n /**\n * Remove the listener for the given event.\n */\n public removeEventListener(\n event: EventType,\n listener: WebSocketEventListener,\n options?: EventListenerOptions | boolean\n ): void {\n this[kEmitter].removeEventListener(\n event,\n Reflect.get(listener, kBoundListener) as EventListener,\n options\n )\n }\n\n /**\n * Send data to the original WebSocket server.\n * @example\n * server.send('hello')\n * server.send(new Blob(['hello']))\n * server.send(new TextEncoder().encode('hello'))\n */\n public send(data: WebSocketData): void {\n const { realWebSocket } = this\n\n invariant(\n realWebSocket,\n 'Failed to call \"server.send()\" for \"%s\": the connection is not open. Did you forget to call \"server.connect()\"?',\n this.socket.url\n )\n\n // Silently ignore writes on the closed original WebSocket.\n if (\n realWebSocket.readyState === WebSocket.CLOSING ||\n realWebSocket.readyState === WebSocket.CLOSED\n ) {\n return\n }\n\n // Delegate the send to when the original connection is open.\n // Unlike the mock, connecting to the original server may take time\n // so we cannot call this on the next tick.\n if (realWebSocket.readyState === WebSocket.CONNECTING) {\n realWebSocket.addEventListener(\n 'open',\n () => {\n realWebSocket.send(data)\n },\n { once: true }\n )\n return\n }\n\n // Send the data to the original WebSocket server.\n realWebSocket.send(data)\n }\n\n /**\n * Close the actual server connection.\n */\n public close(): void {\n const { realWebSocket } = this\n\n invariant(\n realWebSocket,\n 'Failed to close server connection for \"%s\": the connection is not open. Did you forget to call \"server.connect()\"?',\n this.socket.url\n )\n\n // Remove the \"close\" event listener from the server\n // so it doesn't close the underlying WebSocket client\n // when you call \"server.close()\".\n realWebSocket.removeEventListener('close', this.handleRealClose)\n\n if (\n realWebSocket.readyState === WebSocket.CLOSING ||\n realWebSocket.readyState === WebSocket.CLOSED\n ) {\n return\n }\n\n realWebSocket.close()\n\n // Dispatch the \"close\" event on the server connection.\n queueMicrotask(() => {\n this[kEmitter].dispatchEvent(\n bindEvent(this.realWebSocket, new CloseEvent('close'))\n )\n })\n }\n\n private handleIncomingMessage(event: MessageEvent): void {\n // Clone the event to dispatch it on this class\n // once again and prevent the \"already being dispatched\"\n // exception. Clone it here so we can observe this event\n // being prevented in the \"server.on()\" listeners.\n const messageEvent = bindEvent(\n event.target,\n new CancelableMessageEvent('message', {\n data: event.data,\n origin: event.origin,\n cancelable: true,\n })\n )\n\n /**\n * @note Emit \"message\" event on the server connection\n * instance to let the interceptor know about these\n * incoming events from the original server. In that listener,\n * the interceptor can modify or skip the event forwarding\n * to the mock WebSocket instance.\n */\n this[kEmitter].dispatchEvent(messageEvent)\n\n /**\n * @note Forward the incoming server events to the client.\n * Preventing the default on the message event stops this.\n */\n if (!messageEvent.defaultPrevented) {\n this.socket.dispatchEvent(\n bindEvent(\n /**\n * @note Bind the forwarded original server events\n * to the mock WebSocket instance so it would\n * dispatch them straight away.\n */\n this.socket,\n // Clone the message event again to prevent\n // the \"already being dispatched\" exception.\n new MessageEvent('message', {\n data: event.data,\n origin: event.origin,\n })\n )\n )\n }\n }\n\n private handleMockClose(_event: Event): void {\n // Close the original connection if the mock client closes.\n if (this.realWebSocket) {\n this.realWebSocket.close()\n }\n }\n\n private handleRealClose(event: CloseEvent): void {\n // For closures originating from the original server,\n // remove the \"close\" listener from the mock client.\n // original close -> (?) client[kClose]() --X-> \"close\" (again).\n this.mockCloseController.abort()\n\n const closeEvent = bindEvent(\n this.realWebSocket,\n new CloseEvent('close', event)\n )\n\n this[kEmitter].dispatchEvent(closeEvent)\n\n // If the close event from the server hasn't been prevented,\n // forward the closure to the mock client.\n if (!closeEvent.defaultPrevented) {\n // Close the intercepted client forcefully to\n // allow non-configurable status codes from the server.\n // If the socket has been closed by now, no harm calling\n // this again—it will have no effect.\n this.socket[kClose](event.code, event.reason)\n }\n }\n}\n","import { invariant } from 'outvariant'\nimport type { WebSocketData } from './WebSocketTransport'\nimport { bindEvent } from './utils/bindEvent'\nimport { CloseEvent } from './utils/events'\n\nexport type WebSocketEventListener<\n EventType extends WebSocketEventMap[keyof WebSocketEventMap] = Event\n> = (this: WebSocket, event: EventType) => void\n\nconst WEBSOCKET_CLOSE_CODE_RANGE_ERROR =\n 'InvalidAccessError: close code out of user configurable range'\n\nexport const kOnSend = Symbol('kOnSend')\nexport const kClose = Symbol('kClose')\n\nexport class WebSocketOverride extends EventTarget implements WebSocket {\n static readonly CONNECTING = 0\n static readonly OPEN = 1\n static readonly CLOSING = 2\n static readonly CLOSED = 3\n readonly CONNECTING = 0\n readonly OPEN = 1\n readonly CLOSING = 2\n readonly CLOSED = 3\n\n public url: string\n public protocol: string\n public extensions: string\n public binaryType: BinaryType\n public readyState: number\n public bufferedAmount: number\n\n private _onopen: WebSocketEventListener | null = null\n private _onmessage: WebSocketEventListener<\n MessageEvent\n > | null = null\n private _onerror: WebSocketEventListener | null = null\n private _onclose: WebSocketEventListener | null = null\n\n private [kOnSend]?: (data: WebSocketData) => void\n\n constructor(url: string | URL, protocols?: string | Array) {\n super()\n this.url = url.toString()\n this.protocol = ''\n this.extensions = ''\n this.binaryType = 'blob'\n this.readyState = this.CONNECTING\n this.bufferedAmount = 0\n\n Reflect.set(this, 'readyState', this.CONNECTING)\n queueMicrotask(() => {\n Reflect.set(this, 'readyState', this.OPEN)\n this.protocol = protocols ? protocols[0] : 'ws'\n\n this.dispatchEvent(bindEvent(this, new Event('open')))\n })\n }\n\n set onopen(listener: WebSocketEventListener | null) {\n this.removeEventListener('open', this._onopen)\n this._onopen = listener\n if (listener !== null) {\n this.addEventListener('open', listener)\n }\n }\n get onopen(): WebSocketEventListener | null {\n return this._onopen\n }\n\n set onmessage(\n listener: WebSocketEventListener> | null\n ) {\n this.removeEventListener(\n 'message',\n this._onmessage as WebSocketEventListener\n )\n this._onmessage = listener\n if (listener !== null) {\n this.addEventListener('message', listener)\n }\n }\n get onmessage(): WebSocketEventListener> | null {\n return this._onmessage\n }\n\n set onerror(listener: WebSocketEventListener | null) {\n this.removeEventListener('error', this._onerror)\n this._onerror = listener\n if (listener !== null) {\n this.addEventListener('error', listener)\n }\n }\n get onerror(): WebSocketEventListener | null {\n return this._onerror\n }\n\n set onclose(listener: WebSocketEventListener | null) {\n this.removeEventListener('close', this._onclose as WebSocketEventListener)\n this._onclose = listener\n if (listener !== null) {\n this.addEventListener('close', listener)\n }\n }\n get onclose(): WebSocketEventListener | null {\n return this._onclose\n }\n\n /**\n * @see https://websockets.spec.whatwg.org/#ref-for-dom-websocket-send%E2%91%A0\n */\n public send(data: WebSocketData): void {\n if (this.readyState === this.CONNECTING) {\n this.close()\n throw new DOMException('InvalidStateError')\n }\n\n // Sending when the socket is about to close\n // discards the sent data.\n if (this.readyState === this.CLOSING || this.readyState === this.CLOSED) {\n return\n }\n\n // Buffer the data to send in this even loop\n // but send it in the next.\n this.bufferedAmount += getDataSize(data)\n\n queueMicrotask(() => {\n // This is a bit optimistic but since no actual data transfer\n // is involved, all the data will be \"sent\" on the next tick.\n this.bufferedAmount = 0\n\n /**\n * @note Notify the parent about outgoing data.\n * This notifies the transport and the connection\n * listens to the outgoing data to emit the \"message\" event.\n */\n this[kOnSend]?.(data)\n })\n }\n\n public close(code: number = 1000, reason?: string): void {\n invariant(code, WEBSOCKET_CLOSE_CODE_RANGE_ERROR)\n invariant(\n code === 1000 || (code >= 3000 && code <= 4999),\n WEBSOCKET_CLOSE_CODE_RANGE_ERROR\n )\n\n if (this.readyState === this.CLOSING || this.readyState === this.CLOSED) {\n return\n }\n\n this[kClose](code, reason)\n }\n\n private [kClose](code: number = 1000, reason?: string): void {\n this.readyState = this.CLOSING\n\n queueMicrotask(() => {\n this.readyState = this.CLOSED\n\n // Non-user-configurable close status codes\n // represent connection termination and must\n // emit the \"error\" event before closing.\n if (code > 1000 && code <= 1015) {\n this.dispatchEvent(bindEvent(this, new Event('error')))\n }\n\n this.dispatchEvent(\n bindEvent(\n this,\n new CloseEvent('close', {\n code,\n reason,\n wasClean: code === 1000,\n })\n )\n )\n\n // Remove all event listeners once the socket is closed.\n this._onopen = null\n this._onmessage = null\n this._onerror = null\n this._onclose = null\n })\n }\n\n public addEventListener(\n type: K,\n listener: (this: WebSocket, event: WebSocketEventMap[K]) => void,\n options?: boolean | AddEventListenerOptions\n ): void\n public addEventListener(\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions\n ): void\n public addEventListener(\n type: unknown,\n listener: unknown,\n options?: unknown\n ): void {\n return super.addEventListener(\n type as string,\n listener as EventListener,\n options as AddEventListenerOptions\n )\n }\n\n removeEventListener(\n type: K,\n callback: EventListenerOrEventListenerObject | null,\n options?: boolean | EventListenerOptions\n ): void {\n return super.removeEventListener(type, callback, options)\n }\n}\n\nfunction getDataSize(data: WebSocketData): number {\n if (typeof data === 'string') {\n return data.length\n }\n\n if (data instanceof Blob) {\n return data.size\n }\n\n return data.byteLength\n}\n","import { bindEvent } from './utils/bindEvent'\nimport {\n StrictEventListenerOrEventListenerObject,\n WebSocketData,\n WebSocketTransport,\n WebSocketTransportEventMap,\n} from './WebSocketTransport'\nimport { kOnSend, kClose, WebSocketOverride } from './WebSocketOverride'\nimport { CancelableMessageEvent, CloseEvent } from './utils/events'\n\n/**\n * Abstraction over the given mock `WebSocket` instance that allows\n * for controlling that instance (e.g. sending and receiving messages).\n */\nexport class WebSocketClassTransport\n extends EventTarget\n implements WebSocketTransport\n{\n constructor(protected readonly socket: WebSocketOverride) {\n super()\n\n // Emit the \"close\" event on the transport if the close\n // originates from the WebSocket client. E.g. the application\n // calls \"ws.close()\", not the interceptor.\n this.socket.addEventListener('close', (event) => {\n this.dispatchEvent(bindEvent(this.socket, new CloseEvent('close', event)))\n })\n\n /**\n * Emit the \"outgoing\" event on the transport\n * whenever the WebSocket client sends data (\"ws.send()\").\n */\n this.socket[kOnSend] = (data) => {\n this.dispatchEvent(\n bindEvent(\n this.socket,\n // Dispatch this as cancelable because \"client\" connection\n // re-creates this message event (cannot dispatch the same event).\n new CancelableMessageEvent('outgoing', {\n data,\n origin: this.socket.url,\n cancelable: true,\n })\n )\n )\n }\n }\n\n public addEventListener(\n type: EventType,\n callback: StrictEventListenerOrEventListenerObject<\n WebSocketTransportEventMap[EventType]\n > | null,\n options?: boolean | AddEventListenerOptions\n ): void {\n return super.addEventListener(type, callback as EventListener, options)\n }\n\n public dispatchEvent(\n event: WebSocketTransportEventMap[EventType]\n ): boolean {\n return super.dispatchEvent(event)\n }\n\n public send(data: WebSocketData): void {\n queueMicrotask(() => {\n this.socket.dispatchEvent(\n bindEvent(\n /**\n * @note Setting this event's \"target\" to the\n * WebSocket override instance is important.\n * This way it can tell apart original incoming events\n * (must be forwarded to the transport) from the\n * mocked message events like the one below\n * (must be dispatched on the client instance).\n */\n this.socket,\n new MessageEvent('message', {\n data,\n origin: this.socket.url,\n })\n )\n )\n })\n }\n\n public close(code: number, reason?: string): void {\n /**\n * @note Call the internal close method directly\n * to allow closing the connection with the status codes\n * that are non-configurable by the user (> 1000 <= 1015).\n */\n this.socket[kClose](code, reason)\n }\n}\n","import { Interceptor } from '../../Interceptor'\nimport {\n type WebSocketClientConnectionProtocol,\n WebSocketClientConnection,\n} from './WebSocketClientConnection'\nimport { WebSocketServerConnection } from './WebSocketServerConnection'\nimport { WebSocketClassTransport } from './WebSocketClassTransport'\nimport { WebSocketOverride } from './WebSocketOverride'\n\nexport { type WebSocketData, WebSocketTransport } from './WebSocketTransport'\nexport {\n WebSocketClientConnection,\n WebSocketClientConnectionProtocol,\n WebSocketServerConnection,\n}\n\nexport type WebSocketEventMap = {\n connection: [args: WebSocketConnectionData]\n}\n\nexport type WebSocketConnectionData = {\n /**\n * The incoming WebSocket client connection.\n */\n client: WebSocketClientConnection\n\n /**\n * The original WebSocket server connection.\n */\n server: WebSocketServerConnection\n}\n\n/**\n * Intercept the outgoing WebSocket connections created using\n * the global `WebSocket` class.\n */\nexport class WebSocketInterceptor extends Interceptor {\n static symbol = Symbol('websocket')\n\n constructor() {\n super(WebSocketInterceptor.symbol)\n }\n\n protected checkEnvironment(): boolean {\n // Enable this interceptor in any environment\n // that has a global WebSocket API.\n return typeof globalThis.WebSocket !== 'undefined'\n }\n\n protected setup(): void {\n const originalWebSocket = globalThis.WebSocket\n\n const webSocketProxy = new Proxy(globalThis.WebSocket, {\n construct: (\n target,\n args: ConstructorParameters,\n newTarget\n ) => {\n const [url, protocols] = args\n\n const createConnection = (): WebSocket => {\n return Reflect.construct(target, args, newTarget)\n }\n\n // All WebSocket instances are mocked and don't forward\n // any events to the original server (no connection established).\n // To forward the events, the user must use the \"server.send()\" API.\n const socket = new WebSocketOverride(url, protocols)\n const transport = new WebSocketClassTransport(socket)\n\n // Emit the \"connection\" event to the interceptor on the next tick\n // so the client can modify WebSocket options, like \"binaryType\"\n // while the connection is already pending.\n queueMicrotask(() => {\n // The \"globalThis.WebSocket\" class stands for\n // the client-side connection. Assume it's established\n // as soon as the WebSocket instance is constructed.\n this.emitter.emit('connection', {\n client: new WebSocketClientConnection(socket, transport),\n server: new WebSocketServerConnection(\n socket,\n transport,\n createConnection\n ),\n })\n })\n\n return socket\n },\n })\n\n globalThis.WebSocket = webSocketProxy\n\n this.subscriptions.push(() => {\n globalThis.WebSocket = originalWebSocket\n })\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.mjs b/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7fb3fa02773866dcfb2237e5462b4dcd0334f574 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.mjs @@ -0,0 +1,582 @@ +import { + Interceptor, + createRequestId +} from "../../chunk-QED3Q6Z2.mjs"; + +// src/interceptors/WebSocket/utils/bindEvent.ts +function bindEvent(target, event) { + Object.defineProperties(event, { + target: { + value: target, + enumerable: true, + writable: true + }, + currentTarget: { + value: target, + enumerable: true, + writable: true + } + }); + return event; +} + +// src/interceptors/WebSocket/utils/events.ts +var kCancelable = Symbol("kCancelable"); +var kDefaultPrevented = Symbol("kDefaultPrevented"); +var CancelableMessageEvent = class extends MessageEvent { + constructor(type, init) { + super(type, init); + this[kCancelable] = !!init.cancelable; + this[kDefaultPrevented] = false; + } + get cancelable() { + return this[kCancelable]; + } + set cancelable(nextCancelable) { + this[kCancelable] = nextCancelable; + } + get defaultPrevented() { + return this[kDefaultPrevented]; + } + set defaultPrevented(nextDefaultPrevented) { + this[kDefaultPrevented] = nextDefaultPrevented; + } + preventDefault() { + if (this.cancelable && !this[kDefaultPrevented]) { + this[kDefaultPrevented] = true; + } + } +}; +kCancelable, kDefaultPrevented; +var CloseEvent = class extends Event { + constructor(type, init = {}) { + super(type, init); + this.code = init.code === void 0 ? 0 : init.code; + this.reason = init.reason === void 0 ? "" : init.reason; + this.wasClean = init.wasClean === void 0 ? false : init.wasClean; + } +}; + +// src/interceptors/WebSocket/WebSocketClientConnection.ts +var kEmitter = Symbol("kEmitter"); +var kBoundListener = Symbol("kBoundListener"); +var WebSocketClientConnection = class { + constructor(socket, transport) { + this.socket = socket; + this.transport = transport; + this.id = createRequestId(); + this.url = new URL(socket.url); + this[kEmitter] = new EventTarget(); + this.transport.addEventListener("outgoing", (event) => { + const message = bindEvent( + this.socket, + new CancelableMessageEvent("message", { + data: event.data, + origin: event.origin, + cancelable: true + }) + ); + this[kEmitter].dispatchEvent(message); + if (message.defaultPrevented) { + event.preventDefault(); + } + }); + this.transport.addEventListener("close", (event) => { + this[kEmitter].dispatchEvent( + bindEvent(this.socket, new CloseEvent("close", event)) + ); + }); + } + /** + * Listen for the outgoing events from the connected WebSocket client. + */ + addEventListener(type, listener, options) { + const boundListener = listener.bind(this.socket); + Object.defineProperty(listener, kBoundListener, { + value: boundListener, + enumerable: false + }); + this[kEmitter].addEventListener( + type, + boundListener, + options + ); + } + /** + * Removes the listener for the given event. + */ + removeEventListener(event, listener, options) { + this[kEmitter].removeEventListener( + event, + Reflect.get(listener, kBoundListener), + options + ); + } + /** + * Send data to the connected client. + */ + send(data) { + this.transport.send(data); + } + /** + * Close the WebSocket connection. + * @param {number} code A status code (see https://www.rfc-editor.org/rfc/rfc6455#section-7.4.1). + * @param {string} reason A custom connection close reason. + */ + close(code, reason) { + this.transport.close(code, reason); + } +}; +kEmitter; + +// src/interceptors/WebSocket/WebSocketServerConnection.ts +import { invariant as invariant2 } from "outvariant"; + +// src/interceptors/WebSocket/WebSocketOverride.ts +import { invariant } from "outvariant"; +var WEBSOCKET_CLOSE_CODE_RANGE_ERROR = "InvalidAccessError: close code out of user configurable range"; +var kOnSend = Symbol("kOnSend"); +var kClose = Symbol("kClose"); +var WebSocketOverride = class extends EventTarget { + constructor(url, protocols) { + super(); + this.CONNECTING = 0; + this.OPEN = 1; + this.CLOSING = 2; + this.CLOSED = 3; + this._onopen = null; + this._onmessage = null; + this._onerror = null; + this._onclose = null; + this.url = url.toString(); + this.protocol = ""; + this.extensions = ""; + this.binaryType = "blob"; + this.readyState = this.CONNECTING; + this.bufferedAmount = 0; + Reflect.set(this, "readyState", this.CONNECTING); + queueMicrotask(() => { + Reflect.set(this, "readyState", this.OPEN); + this.protocol = protocols ? protocols[0] : "ws"; + this.dispatchEvent(bindEvent(this, new Event("open"))); + }); + } + set onopen(listener) { + this.removeEventListener("open", this._onopen); + this._onopen = listener; + if (listener !== null) { + this.addEventListener("open", listener); + } + } + get onopen() { + return this._onopen; + } + set onmessage(listener) { + this.removeEventListener( + "message", + this._onmessage + ); + this._onmessage = listener; + if (listener !== null) { + this.addEventListener("message", listener); + } + } + get onmessage() { + return this._onmessage; + } + set onerror(listener) { + this.removeEventListener("error", this._onerror); + this._onerror = listener; + if (listener !== null) { + this.addEventListener("error", listener); + } + } + get onerror() { + return this._onerror; + } + set onclose(listener) { + this.removeEventListener("close", this._onclose); + this._onclose = listener; + if (listener !== null) { + this.addEventListener("close", listener); + } + } + get onclose() { + return this._onclose; + } + /** + * @see https://websockets.spec.whatwg.org/#ref-for-dom-websocket-send%E2%91%A0 + */ + send(data) { + if (this.readyState === this.CONNECTING) { + this.close(); + throw new DOMException("InvalidStateError"); + } + if (this.readyState === this.CLOSING || this.readyState === this.CLOSED) { + return; + } + this.bufferedAmount += getDataSize(data); + queueMicrotask(() => { + var _a; + this.bufferedAmount = 0; + (_a = this[kOnSend]) == null ? void 0 : _a.call(this, data); + }); + } + close(code = 1e3, reason) { + invariant(code, WEBSOCKET_CLOSE_CODE_RANGE_ERROR); + invariant( + code === 1e3 || code >= 3e3 && code <= 4999, + WEBSOCKET_CLOSE_CODE_RANGE_ERROR + ); + if (this.readyState === this.CLOSING || this.readyState === this.CLOSED) { + return; + } + this[kClose](code, reason); + } + [(kOnSend, kClose)](code = 1e3, reason) { + this.readyState = this.CLOSING; + queueMicrotask(() => { + this.readyState = this.CLOSED; + if (code > 1e3 && code <= 1015) { + this.dispatchEvent(bindEvent(this, new Event("error"))); + } + this.dispatchEvent( + bindEvent( + this, + new CloseEvent("close", { + code, + reason, + wasClean: code === 1e3 + }) + ) + ); + this._onopen = null; + this._onmessage = null; + this._onerror = null; + this._onclose = null; + }); + } + addEventListener(type, listener, options) { + return super.addEventListener( + type, + listener, + options + ); + } + removeEventListener(type, callback, options) { + return super.removeEventListener(type, callback, options); + } +}; +WebSocketOverride.CONNECTING = 0; +WebSocketOverride.OPEN = 1; +WebSocketOverride.CLOSING = 2; +WebSocketOverride.CLOSED = 3; +function getDataSize(data) { + if (typeof data === "string") { + return data.length; + } + if (data instanceof Blob) { + return data.size; + } + return data.byteLength; +} + +// src/interceptors/WebSocket/WebSocketServerConnection.ts +var kEmitter2 = Symbol("kEmitter"); +var kBoundListener2 = Symbol("kBoundListener"); +var WebSocketServerConnection = class { + constructor(socket, transport, createConnection) { + this.socket = socket; + this.transport = transport; + this.createConnection = createConnection; + this[kEmitter2] = new EventTarget(); + this.mockCloseController = new AbortController(); + this.transport.addEventListener("outgoing", (event) => { + if (this.readyState === -1) { + return; + } + queueMicrotask(() => { + if (!event.defaultPrevented) { + this.send(event.data); + } + }); + }); + this.transport.addEventListener( + "incoming", + this.handleIncomingMessage.bind(this) + ); + } + /** + * Server ready state. + * Proxies the ready state of the original WebSocket instance, + * if set. If the original connection hasn't been established, + * defaults to `-1`. + */ + get readyState() { + if (this.realWebSocket) { + return this.realWebSocket.readyState; + } + return -1; + } + /** + * Open connection to the original WebSocket server. + */ + connect() { + invariant2( + !this.realWebSocket || this.realWebSocket.readyState !== WebSocket.OPEN, + 'Failed to call "connect()" on the original WebSocket instance: the connection already open' + ); + const realWebSocket = this.createConnection(); + realWebSocket.binaryType = this.socket.binaryType; + realWebSocket.addEventListener( + "open", + (event) => { + this[kEmitter2].dispatchEvent( + bindEvent(this.realWebSocket, new Event("open", event)) + ); + }, + { once: true } + ); + realWebSocket.addEventListener("message", (event) => { + this.transport.dispatchEvent( + bindEvent( + this.realWebSocket, + new MessageEvent("incoming", { + data: event.data, + origin: event.origin + }) + ) + ); + }); + this.socket.addEventListener("close", this.handleMockClose.bind(this), { + signal: this.mockCloseController.signal + }); + realWebSocket.addEventListener("close", this.handleRealClose.bind(this)); + realWebSocket.addEventListener("error", () => { + this.socket.dispatchEvent(bindEvent(this.socket, new Event("error"))); + }); + this.realWebSocket = realWebSocket; + } + /** + * Listen for the incoming events from the original WebSocket server. + */ + addEventListener(event, listener, options) { + const boundListener = listener.bind(this.socket); + Object.defineProperty(listener, kBoundListener2, { + value: boundListener, + enumerable: false + }); + this[kEmitter2].addEventListener( + event, + boundListener, + options + ); + } + /** + * Remove the listener for the given event. + */ + removeEventListener(event, listener, options) { + this[kEmitter2].removeEventListener( + event, + Reflect.get(listener, kBoundListener2), + options + ); + } + /** + * Send data to the original WebSocket server. + * @example + * server.send('hello') + * server.send(new Blob(['hello'])) + * server.send(new TextEncoder().encode('hello')) + */ + send(data) { + const { realWebSocket } = this; + invariant2( + realWebSocket, + 'Failed to call "server.send()" for "%s": the connection is not open. Did you forget to call "server.connect()"?', + this.socket.url + ); + if (realWebSocket.readyState === WebSocket.CLOSING || realWebSocket.readyState === WebSocket.CLOSED) { + return; + } + if (realWebSocket.readyState === WebSocket.CONNECTING) { + realWebSocket.addEventListener( + "open", + () => { + realWebSocket.send(data); + }, + { once: true } + ); + return; + } + realWebSocket.send(data); + } + /** + * Close the actual server connection. + */ + close() { + const { realWebSocket } = this; + invariant2( + realWebSocket, + 'Failed to close server connection for "%s": the connection is not open. Did you forget to call "server.connect()"?', + this.socket.url + ); + realWebSocket.removeEventListener("close", this.handleRealClose); + if (realWebSocket.readyState === WebSocket.CLOSING || realWebSocket.readyState === WebSocket.CLOSED) { + return; + } + realWebSocket.close(); + queueMicrotask(() => { + this[kEmitter2].dispatchEvent( + bindEvent(this.realWebSocket, new CloseEvent("close")) + ); + }); + } + handleIncomingMessage(event) { + const messageEvent = bindEvent( + event.target, + new CancelableMessageEvent("message", { + data: event.data, + origin: event.origin, + cancelable: true + }) + ); + this[kEmitter2].dispatchEvent(messageEvent); + if (!messageEvent.defaultPrevented) { + this.socket.dispatchEvent( + bindEvent( + /** + * @note Bind the forwarded original server events + * to the mock WebSocket instance so it would + * dispatch them straight away. + */ + this.socket, + // Clone the message event again to prevent + // the "already being dispatched" exception. + new MessageEvent("message", { + data: event.data, + origin: event.origin + }) + ) + ); + } + } + handleMockClose(_event) { + if (this.realWebSocket) { + this.realWebSocket.close(); + } + } + handleRealClose(event) { + this.mockCloseController.abort(); + const closeEvent = bindEvent( + this.realWebSocket, + new CloseEvent("close", event) + ); + this[kEmitter2].dispatchEvent(closeEvent); + if (!closeEvent.defaultPrevented) { + this.socket[kClose](event.code, event.reason); + } + } +}; +kEmitter2; + +// src/interceptors/WebSocket/WebSocketClassTransport.ts +var WebSocketClassTransport = class extends EventTarget { + constructor(socket) { + super(); + this.socket = socket; + this.socket.addEventListener("close", (event) => { + this.dispatchEvent(bindEvent(this.socket, new CloseEvent("close", event))); + }); + this.socket[kOnSend] = (data) => { + this.dispatchEvent( + bindEvent( + this.socket, + // Dispatch this as cancelable because "client" connection + // re-creates this message event (cannot dispatch the same event). + new CancelableMessageEvent("outgoing", { + data, + origin: this.socket.url, + cancelable: true + }) + ) + ); + }; + } + addEventListener(type, callback, options) { + return super.addEventListener(type, callback, options); + } + dispatchEvent(event) { + return super.dispatchEvent(event); + } + send(data) { + queueMicrotask(() => { + this.socket.dispatchEvent( + bindEvent( + /** + * @note Setting this event's "target" to the + * WebSocket override instance is important. + * This way it can tell apart original incoming events + * (must be forwarded to the transport) from the + * mocked message events like the one below + * (must be dispatched on the client instance). + */ + this.socket, + new MessageEvent("message", { + data, + origin: this.socket.url + }) + ) + ); + }); + } + close(code, reason) { + this.socket[kClose](code, reason); + } +}; + +// src/interceptors/WebSocket/index.ts +var _WebSocketInterceptor = class extends Interceptor { + constructor() { + super(_WebSocketInterceptor.symbol); + } + checkEnvironment() { + return typeof globalThis.WebSocket !== "undefined"; + } + setup() { + const originalWebSocket = globalThis.WebSocket; + const webSocketProxy = new Proxy(globalThis.WebSocket, { + construct: (target, args, newTarget) => { + const [url, protocols] = args; + const createConnection = () => { + return Reflect.construct(target, args, newTarget); + }; + const socket = new WebSocketOverride(url, protocols); + const transport = new WebSocketClassTransport(socket); + queueMicrotask(() => { + this.emitter.emit("connection", { + client: new WebSocketClientConnection(socket, transport), + server: new WebSocketServerConnection( + socket, + transport, + createConnection + ) + }); + }); + return socket; + } + }); + globalThis.WebSocket = webSocketProxy; + this.subscriptions.push(() => { + globalThis.WebSocket = originalWebSocket; + }); + } +}; +var WebSocketInterceptor = _WebSocketInterceptor; +WebSocketInterceptor.symbol = Symbol("websocket"); +export { + WebSocketClientConnection, + WebSocketInterceptor, + WebSocketServerConnection +}; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.mjs.map b/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..0768010dc9445147a68b9b6eb7df5e7e4a1379b0 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/interceptors/WebSocket/utils/bindEvent.ts","../../../../src/interceptors/WebSocket/utils/events.ts","../../../../src/interceptors/WebSocket/WebSocketClientConnection.ts","../../../../src/interceptors/WebSocket/WebSocketServerConnection.ts","../../../../src/interceptors/WebSocket/WebSocketOverride.ts","../../../../src/interceptors/WebSocket/WebSocketClassTransport.ts","../../../../src/interceptors/WebSocket/index.ts"],"sourcesContent":["type EventWithTarget = E & { target: T }\n\nexport function bindEvent(\n target: T,\n event: E\n): EventWithTarget {\n Object.defineProperties(event, {\n target: {\n value: target,\n enumerable: true,\n writable: true,\n },\n currentTarget: {\n value: target,\n enumerable: true,\n writable: true,\n },\n })\n\n return event as EventWithTarget\n}\n","const kCancelable = Symbol('kCancelable')\nconst kDefaultPrevented = Symbol('kDefaultPrevented')\n\n/**\n * A `MessageEvent` superset that supports event cancellation\n * in Node.js. It's rather non-intrusive so it can be safely\n * used in the browser as well.\n *\n * @see https://github.com/nodejs/node/issues/51767\n */\nexport class CancelableMessageEvent extends MessageEvent {\n [kCancelable]: boolean;\n [kDefaultPrevented]: boolean\n\n constructor(type: string, init: MessageEventInit) {\n super(type, init)\n this[kCancelable] = !!init.cancelable\n this[kDefaultPrevented] = false\n }\n\n get cancelable() {\n return this[kCancelable]\n }\n\n set cancelable(nextCancelable) {\n this[kCancelable] = nextCancelable\n }\n\n get defaultPrevented() {\n return this[kDefaultPrevented]\n }\n\n set defaultPrevented(nextDefaultPrevented) {\n this[kDefaultPrevented] = nextDefaultPrevented\n }\n\n public preventDefault(): void {\n if (this.cancelable && !this[kDefaultPrevented]) {\n this[kDefaultPrevented] = true\n }\n }\n}\n\ninterface CloseEventInit extends EventInit {\n code?: number\n reason?: string\n wasClean?: boolean\n}\n\nexport class CloseEvent extends Event {\n public code: number\n public reason: string\n public wasClean: boolean\n\n constructor(type: string, init: CloseEventInit = {}) {\n super(type, init)\n this.code = init.code === undefined ? 0 : init.code\n this.reason = init.reason === undefined ? '' : init.reason\n this.wasClean = init.wasClean === undefined ? false : init.wasClean\n }\n}\n","import type { WebSocketData, WebSocketTransport } from './WebSocketTransport'\nimport type { WebSocketEventListener } from './WebSocketOverride'\nimport { bindEvent } from './utils/bindEvent'\nimport { CancelableMessageEvent, CloseEvent } from './utils/events'\nimport { createRequestId } from '../../createRequestId'\n\nconst kEmitter = Symbol('kEmitter')\nconst kBoundListener = Symbol('kBoundListener')\n\ninterface WebSocketClientEventMap {\n message: MessageEvent\n close: CloseEvent\n}\n\nexport interface WebSocketClientConnectionProtocol {\n id: string\n url: URL\n send(data: WebSocketData): void\n close(code?: number, reason?: string): void\n}\n\n/**\n * The WebSocket client instance represents an incoming\n * client connection. The user can control the connection,\n * send and receive events.\n */\nexport class WebSocketClientConnection\n implements WebSocketClientConnectionProtocol\n{\n public readonly id: string\n public readonly url: URL\n\n private [kEmitter]: EventTarget\n\n constructor(\n public readonly socket: WebSocket,\n private readonly transport: WebSocketTransport\n ) {\n this.id = createRequestId()\n this.url = new URL(socket.url)\n this[kEmitter] = new EventTarget()\n\n // Emit outgoing client data (\"ws.send()\") as \"message\"\n // events on the \"client\" connection.\n this.transport.addEventListener('outgoing', (event) => {\n const message = bindEvent(\n this.socket,\n new CancelableMessageEvent('message', {\n data: event.data,\n origin: event.origin,\n cancelable: true,\n })\n )\n\n this[kEmitter].dispatchEvent(message)\n\n // This is a bit silly but forward the cancellation state\n // of the \"client\" message event to the \"outgoing\" transport event.\n // This way, other agens (like \"server\" connection) can know\n // whether the client listener has pervented the default.\n if (message.defaultPrevented) {\n event.preventDefault()\n }\n })\n\n /**\n * Emit the \"close\" event on the \"client\" connection\n * whenever the underlying transport is closed.\n * @note \"client.close()\" does NOT dispatch the \"close\"\n * event on the WebSocket because it uses non-configurable\n * close status code. Thus, we listen to the transport\n * instead of the WebSocket's \"close\" event.\n */\n this.transport.addEventListener('close', (event) => {\n this[kEmitter].dispatchEvent(\n bindEvent(this.socket, new CloseEvent('close', event))\n )\n })\n }\n\n /**\n * Listen for the outgoing events from the connected WebSocket client.\n */\n public addEventListener(\n type: EventType,\n listener: WebSocketEventListener,\n options?: AddEventListenerOptions | boolean\n ): void {\n const boundListener = listener.bind(this.socket)\n\n // Store the bound listener on the original listener\n // so the exact bound function can be accessed in \"removeEventListener()\".\n Object.defineProperty(listener, kBoundListener, {\n value: boundListener,\n enumerable: false,\n })\n\n this[kEmitter].addEventListener(\n type,\n boundListener as EventListener,\n options\n )\n }\n\n /**\n * Removes the listener for the given event.\n */\n public removeEventListener(\n event: EventType,\n listener: WebSocketEventListener,\n options?: EventListenerOptions | boolean\n ): void {\n this[kEmitter].removeEventListener(\n event,\n Reflect.get(listener, kBoundListener) as EventListener,\n options\n )\n }\n\n /**\n * Send data to the connected client.\n */\n public send(data: WebSocketData): void {\n this.transport.send(data)\n }\n\n /**\n * Close the WebSocket connection.\n * @param {number} code A status code (see https://www.rfc-editor.org/rfc/rfc6455#section-7.4.1).\n * @param {string} reason A custom connection close reason.\n */\n public close(code?: number, reason?: string): void {\n this.transport.close(code, reason)\n }\n}\n","import { invariant } from 'outvariant'\nimport {\n kClose,\n WebSocketEventListener,\n WebSocketOverride,\n} from './WebSocketOverride'\nimport type { WebSocketData } from './WebSocketTransport'\nimport type { WebSocketClassTransport } from './WebSocketClassTransport'\nimport { bindEvent } from './utils/bindEvent'\nimport { CancelableMessageEvent, CloseEvent } from './utils/events'\n\nconst kEmitter = Symbol('kEmitter')\nconst kBoundListener = Symbol('kBoundListener')\n\ninterface WebSocketServerEventMap {\n open: Event\n message: MessageEvent\n error: Event\n close: CloseEvent\n}\n\n/**\n * The WebSocket server instance represents the actual production\n * WebSocket server connection. It's idle by default but you can\n * establish it by calling `server.connect()`.\n */\nexport class WebSocketServerConnection {\n /**\n * A WebSocket instance connected to the original server.\n */\n private realWebSocket?: WebSocket\n private mockCloseController: AbortController\n private [kEmitter]: EventTarget\n\n constructor(\n private readonly socket: WebSocketOverride,\n private readonly transport: WebSocketClassTransport,\n private readonly createConnection: () => WebSocket\n ) {\n this[kEmitter] = new EventTarget()\n this.mockCloseController = new AbortController()\n\n // Automatically forward outgoing client events\n // to the actual server unless the outgoing message event\n // has been prevented. The \"outgoing\" transport event it\n // dispatched by the \"client\" connection.\n this.transport.addEventListener('outgoing', (event) => {\n // Ignore client messages if the server connection\n // hasn't been established yet. Nowhere to forward.\n if (this.readyState === -1) {\n return\n }\n\n // Every outgoing client message can prevent this forwarding\n // by preventing the default of the outgoing message event.\n // This listener will be added before user-defined listeners,\n // so execute the logic on the next tick.\n queueMicrotask(() => {\n if (!event.defaultPrevented) {\n this.send(event.data)\n }\n })\n })\n\n this.transport.addEventListener(\n 'incoming',\n this.handleIncomingMessage.bind(this)\n )\n }\n\n /**\n * Server ready state.\n * Proxies the ready state of the original WebSocket instance,\n * if set. If the original connection hasn't been established,\n * defaults to `-1`.\n */\n public get readyState(): number {\n if (this.realWebSocket) {\n return this.realWebSocket.readyState\n }\n\n return -1\n }\n\n /**\n * Open connection to the original WebSocket server.\n */\n public connect(): void {\n invariant(\n !this.realWebSocket || this.realWebSocket.readyState !== WebSocket.OPEN,\n 'Failed to call \"connect()\" on the original WebSocket instance: the connection already open'\n )\n\n const realWebSocket = this.createConnection()\n\n // Inherit the binary type from the mock WebSocket client.\n realWebSocket.binaryType = this.socket.binaryType\n\n // Allow the interceptor to listen to when the server connection\n // has been established. This isn't necessary to operate with the connection\n // but may be beneficial in some cases (like conditionally adding logging).\n realWebSocket.addEventListener(\n 'open',\n (event) => {\n this[kEmitter].dispatchEvent(\n bindEvent(this.realWebSocket!, new Event('open', event))\n )\n },\n { once: true }\n )\n\n realWebSocket.addEventListener('message', (event) => {\n // Dispatch the \"incoming\" transport event instead of\n // invoking the internal handler directly. This way,\n // anyone can listen to the \"incoming\" event but this\n // class is the one resulting in it.\n this.transport.dispatchEvent(\n bindEvent(\n this.realWebSocket!,\n new MessageEvent('incoming', {\n data: event.data,\n origin: event.origin,\n })\n )\n )\n })\n\n // Close the original connection when the mock client closes.\n // E.g. \"client.close()\" was called.\n this.socket.addEventListener('close', this.handleMockClose.bind(this), {\n signal: this.mockCloseController.signal,\n })\n\n // Forward the \"close\" event to let the interceptor handle\n // closures initiated by the original server.\n realWebSocket.addEventListener('close', this.handleRealClose.bind(this))\n\n // Forward server errors to the WebSocket client as-is.\n // We may consider exposing them to the interceptor in the future.\n realWebSocket.addEventListener('error', () => {\n this.socket.dispatchEvent(bindEvent(this.socket, new Event('error')))\n })\n\n this.realWebSocket = realWebSocket\n }\n\n /**\n * Listen for the incoming events from the original WebSocket server.\n */\n public addEventListener(\n event: EventType,\n listener: WebSocketEventListener,\n options?: AddEventListenerOptions | boolean\n ): void {\n const boundListener = listener.bind(this.socket)\n\n // Store the bound listener on the original listener\n // so the exact bound function can be accessed in \"removeEventListener()\".\n Object.defineProperty(listener, kBoundListener, {\n value: boundListener,\n enumerable: false,\n })\n\n this[kEmitter].addEventListener(\n event,\n boundListener as EventListener,\n options\n )\n }\n\n /**\n * Remove the listener for the given event.\n */\n public removeEventListener(\n event: EventType,\n listener: WebSocketEventListener,\n options?: EventListenerOptions | boolean\n ): void {\n this[kEmitter].removeEventListener(\n event,\n Reflect.get(listener, kBoundListener) as EventListener,\n options\n )\n }\n\n /**\n * Send data to the original WebSocket server.\n * @example\n * server.send('hello')\n * server.send(new Blob(['hello']))\n * server.send(new TextEncoder().encode('hello'))\n */\n public send(data: WebSocketData): void {\n const { realWebSocket } = this\n\n invariant(\n realWebSocket,\n 'Failed to call \"server.send()\" for \"%s\": the connection is not open. Did you forget to call \"server.connect()\"?',\n this.socket.url\n )\n\n // Silently ignore writes on the closed original WebSocket.\n if (\n realWebSocket.readyState === WebSocket.CLOSING ||\n realWebSocket.readyState === WebSocket.CLOSED\n ) {\n return\n }\n\n // Delegate the send to when the original connection is open.\n // Unlike the mock, connecting to the original server may take time\n // so we cannot call this on the next tick.\n if (realWebSocket.readyState === WebSocket.CONNECTING) {\n realWebSocket.addEventListener(\n 'open',\n () => {\n realWebSocket.send(data)\n },\n { once: true }\n )\n return\n }\n\n // Send the data to the original WebSocket server.\n realWebSocket.send(data)\n }\n\n /**\n * Close the actual server connection.\n */\n public close(): void {\n const { realWebSocket } = this\n\n invariant(\n realWebSocket,\n 'Failed to close server connection for \"%s\": the connection is not open. Did you forget to call \"server.connect()\"?',\n this.socket.url\n )\n\n // Remove the \"close\" event listener from the server\n // so it doesn't close the underlying WebSocket client\n // when you call \"server.close()\".\n realWebSocket.removeEventListener('close', this.handleRealClose)\n\n if (\n realWebSocket.readyState === WebSocket.CLOSING ||\n realWebSocket.readyState === WebSocket.CLOSED\n ) {\n return\n }\n\n realWebSocket.close()\n\n // Dispatch the \"close\" event on the server connection.\n queueMicrotask(() => {\n this[kEmitter].dispatchEvent(\n bindEvent(this.realWebSocket, new CloseEvent('close'))\n )\n })\n }\n\n private handleIncomingMessage(event: MessageEvent): void {\n // Clone the event to dispatch it on this class\n // once again and prevent the \"already being dispatched\"\n // exception. Clone it here so we can observe this event\n // being prevented in the \"server.on()\" listeners.\n const messageEvent = bindEvent(\n event.target,\n new CancelableMessageEvent('message', {\n data: event.data,\n origin: event.origin,\n cancelable: true,\n })\n )\n\n /**\n * @note Emit \"message\" event on the server connection\n * instance to let the interceptor know about these\n * incoming events from the original server. In that listener,\n * the interceptor can modify or skip the event forwarding\n * to the mock WebSocket instance.\n */\n this[kEmitter].dispatchEvent(messageEvent)\n\n /**\n * @note Forward the incoming server events to the client.\n * Preventing the default on the message event stops this.\n */\n if (!messageEvent.defaultPrevented) {\n this.socket.dispatchEvent(\n bindEvent(\n /**\n * @note Bind the forwarded original server events\n * to the mock WebSocket instance so it would\n * dispatch them straight away.\n */\n this.socket,\n // Clone the message event again to prevent\n // the \"already being dispatched\" exception.\n new MessageEvent('message', {\n data: event.data,\n origin: event.origin,\n })\n )\n )\n }\n }\n\n private handleMockClose(_event: Event): void {\n // Close the original connection if the mock client closes.\n if (this.realWebSocket) {\n this.realWebSocket.close()\n }\n }\n\n private handleRealClose(event: CloseEvent): void {\n // For closures originating from the original server,\n // remove the \"close\" listener from the mock client.\n // original close -> (?) client[kClose]() --X-> \"close\" (again).\n this.mockCloseController.abort()\n\n const closeEvent = bindEvent(\n this.realWebSocket,\n new CloseEvent('close', event)\n )\n\n this[kEmitter].dispatchEvent(closeEvent)\n\n // If the close event from the server hasn't been prevented,\n // forward the closure to the mock client.\n if (!closeEvent.defaultPrevented) {\n // Close the intercepted client forcefully to\n // allow non-configurable status codes from the server.\n // If the socket has been closed by now, no harm calling\n // this again—it will have no effect.\n this.socket[kClose](event.code, event.reason)\n }\n }\n}\n","import { invariant } from 'outvariant'\nimport type { WebSocketData } from './WebSocketTransport'\nimport { bindEvent } from './utils/bindEvent'\nimport { CloseEvent } from './utils/events'\n\nexport type WebSocketEventListener<\n EventType extends WebSocketEventMap[keyof WebSocketEventMap] = Event\n> = (this: WebSocket, event: EventType) => void\n\nconst WEBSOCKET_CLOSE_CODE_RANGE_ERROR =\n 'InvalidAccessError: close code out of user configurable range'\n\nexport const kOnSend = Symbol('kOnSend')\nexport const kClose = Symbol('kClose')\n\nexport class WebSocketOverride extends EventTarget implements WebSocket {\n static readonly CONNECTING = 0\n static readonly OPEN = 1\n static readonly CLOSING = 2\n static readonly CLOSED = 3\n readonly CONNECTING = 0\n readonly OPEN = 1\n readonly CLOSING = 2\n readonly CLOSED = 3\n\n public url: string\n public protocol: string\n public extensions: string\n public binaryType: BinaryType\n public readyState: number\n public bufferedAmount: number\n\n private _onopen: WebSocketEventListener | null = null\n private _onmessage: WebSocketEventListener<\n MessageEvent\n > | null = null\n private _onerror: WebSocketEventListener | null = null\n private _onclose: WebSocketEventListener | null = null\n\n private [kOnSend]?: (data: WebSocketData) => void\n\n constructor(url: string | URL, protocols?: string | Array) {\n super()\n this.url = url.toString()\n this.protocol = ''\n this.extensions = ''\n this.binaryType = 'blob'\n this.readyState = this.CONNECTING\n this.bufferedAmount = 0\n\n Reflect.set(this, 'readyState', this.CONNECTING)\n queueMicrotask(() => {\n Reflect.set(this, 'readyState', this.OPEN)\n this.protocol = protocols ? protocols[0] : 'ws'\n\n this.dispatchEvent(bindEvent(this, new Event('open')))\n })\n }\n\n set onopen(listener: WebSocketEventListener | null) {\n this.removeEventListener('open', this._onopen)\n this._onopen = listener\n if (listener !== null) {\n this.addEventListener('open', listener)\n }\n }\n get onopen(): WebSocketEventListener | null {\n return this._onopen\n }\n\n set onmessage(\n listener: WebSocketEventListener> | null\n ) {\n this.removeEventListener(\n 'message',\n this._onmessage as WebSocketEventListener\n )\n this._onmessage = listener\n if (listener !== null) {\n this.addEventListener('message', listener)\n }\n }\n get onmessage(): WebSocketEventListener> | null {\n return this._onmessage\n }\n\n set onerror(listener: WebSocketEventListener | null) {\n this.removeEventListener('error', this._onerror)\n this._onerror = listener\n if (listener !== null) {\n this.addEventListener('error', listener)\n }\n }\n get onerror(): WebSocketEventListener | null {\n return this._onerror\n }\n\n set onclose(listener: WebSocketEventListener | null) {\n this.removeEventListener('close', this._onclose as WebSocketEventListener)\n this._onclose = listener\n if (listener !== null) {\n this.addEventListener('close', listener)\n }\n }\n get onclose(): WebSocketEventListener | null {\n return this._onclose\n }\n\n /**\n * @see https://websockets.spec.whatwg.org/#ref-for-dom-websocket-send%E2%91%A0\n */\n public send(data: WebSocketData): void {\n if (this.readyState === this.CONNECTING) {\n this.close()\n throw new DOMException('InvalidStateError')\n }\n\n // Sending when the socket is about to close\n // discards the sent data.\n if (this.readyState === this.CLOSING || this.readyState === this.CLOSED) {\n return\n }\n\n // Buffer the data to send in this even loop\n // but send it in the next.\n this.bufferedAmount += getDataSize(data)\n\n queueMicrotask(() => {\n // This is a bit optimistic but since no actual data transfer\n // is involved, all the data will be \"sent\" on the next tick.\n this.bufferedAmount = 0\n\n /**\n * @note Notify the parent about outgoing data.\n * This notifies the transport and the connection\n * listens to the outgoing data to emit the \"message\" event.\n */\n this[kOnSend]?.(data)\n })\n }\n\n public close(code: number = 1000, reason?: string): void {\n invariant(code, WEBSOCKET_CLOSE_CODE_RANGE_ERROR)\n invariant(\n code === 1000 || (code >= 3000 && code <= 4999),\n WEBSOCKET_CLOSE_CODE_RANGE_ERROR\n )\n\n if (this.readyState === this.CLOSING || this.readyState === this.CLOSED) {\n return\n }\n\n this[kClose](code, reason)\n }\n\n private [kClose](code: number = 1000, reason?: string): void {\n this.readyState = this.CLOSING\n\n queueMicrotask(() => {\n this.readyState = this.CLOSED\n\n // Non-user-configurable close status codes\n // represent connection termination and must\n // emit the \"error\" event before closing.\n if (code > 1000 && code <= 1015) {\n this.dispatchEvent(bindEvent(this, new Event('error')))\n }\n\n this.dispatchEvent(\n bindEvent(\n this,\n new CloseEvent('close', {\n code,\n reason,\n wasClean: code === 1000,\n })\n )\n )\n\n // Remove all event listeners once the socket is closed.\n this._onopen = null\n this._onmessage = null\n this._onerror = null\n this._onclose = null\n })\n }\n\n public addEventListener(\n type: K,\n listener: (this: WebSocket, event: WebSocketEventMap[K]) => void,\n options?: boolean | AddEventListenerOptions\n ): void\n public addEventListener(\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions\n ): void\n public addEventListener(\n type: unknown,\n listener: unknown,\n options?: unknown\n ): void {\n return super.addEventListener(\n type as string,\n listener as EventListener,\n options as AddEventListenerOptions\n )\n }\n\n removeEventListener(\n type: K,\n callback: EventListenerOrEventListenerObject | null,\n options?: boolean | EventListenerOptions\n ): void {\n return super.removeEventListener(type, callback, options)\n }\n}\n\nfunction getDataSize(data: WebSocketData): number {\n if (typeof data === 'string') {\n return data.length\n }\n\n if (data instanceof Blob) {\n return data.size\n }\n\n return data.byteLength\n}\n","import { bindEvent } from './utils/bindEvent'\nimport {\n StrictEventListenerOrEventListenerObject,\n WebSocketData,\n WebSocketTransport,\n WebSocketTransportEventMap,\n} from './WebSocketTransport'\nimport { kOnSend, kClose, WebSocketOverride } from './WebSocketOverride'\nimport { CancelableMessageEvent, CloseEvent } from './utils/events'\n\n/**\n * Abstraction over the given mock `WebSocket` instance that allows\n * for controlling that instance (e.g. sending and receiving messages).\n */\nexport class WebSocketClassTransport\n extends EventTarget\n implements WebSocketTransport\n{\n constructor(protected readonly socket: WebSocketOverride) {\n super()\n\n // Emit the \"close\" event on the transport if the close\n // originates from the WebSocket client. E.g. the application\n // calls \"ws.close()\", not the interceptor.\n this.socket.addEventListener('close', (event) => {\n this.dispatchEvent(bindEvent(this.socket, new CloseEvent('close', event)))\n })\n\n /**\n * Emit the \"outgoing\" event on the transport\n * whenever the WebSocket client sends data (\"ws.send()\").\n */\n this.socket[kOnSend] = (data) => {\n this.dispatchEvent(\n bindEvent(\n this.socket,\n // Dispatch this as cancelable because \"client\" connection\n // re-creates this message event (cannot dispatch the same event).\n new CancelableMessageEvent('outgoing', {\n data,\n origin: this.socket.url,\n cancelable: true,\n })\n )\n )\n }\n }\n\n public addEventListener(\n type: EventType,\n callback: StrictEventListenerOrEventListenerObject<\n WebSocketTransportEventMap[EventType]\n > | null,\n options?: boolean | AddEventListenerOptions\n ): void {\n return super.addEventListener(type, callback as EventListener, options)\n }\n\n public dispatchEvent(\n event: WebSocketTransportEventMap[EventType]\n ): boolean {\n return super.dispatchEvent(event)\n }\n\n public send(data: WebSocketData): void {\n queueMicrotask(() => {\n this.socket.dispatchEvent(\n bindEvent(\n /**\n * @note Setting this event's \"target\" to the\n * WebSocket override instance is important.\n * This way it can tell apart original incoming events\n * (must be forwarded to the transport) from the\n * mocked message events like the one below\n * (must be dispatched on the client instance).\n */\n this.socket,\n new MessageEvent('message', {\n data,\n origin: this.socket.url,\n })\n )\n )\n })\n }\n\n public close(code: number, reason?: string): void {\n /**\n * @note Call the internal close method directly\n * to allow closing the connection with the status codes\n * that are non-configurable by the user (> 1000 <= 1015).\n */\n this.socket[kClose](code, reason)\n }\n}\n","import { Interceptor } from '../../Interceptor'\nimport {\n type WebSocketClientConnectionProtocol,\n WebSocketClientConnection,\n} from './WebSocketClientConnection'\nimport { WebSocketServerConnection } from './WebSocketServerConnection'\nimport { WebSocketClassTransport } from './WebSocketClassTransport'\nimport { WebSocketOverride } from './WebSocketOverride'\n\nexport { type WebSocketData, WebSocketTransport } from './WebSocketTransport'\nexport {\n WebSocketClientConnection,\n WebSocketClientConnectionProtocol,\n WebSocketServerConnection,\n}\n\nexport type WebSocketEventMap = {\n connection: [args: WebSocketConnectionData]\n}\n\nexport type WebSocketConnectionData = {\n /**\n * The incoming WebSocket client connection.\n */\n client: WebSocketClientConnection\n\n /**\n * The original WebSocket server connection.\n */\n server: WebSocketServerConnection\n}\n\n/**\n * Intercept the outgoing WebSocket connections created using\n * the global `WebSocket` class.\n */\nexport class WebSocketInterceptor extends Interceptor {\n static symbol = Symbol('websocket')\n\n constructor() {\n super(WebSocketInterceptor.symbol)\n }\n\n protected checkEnvironment(): boolean {\n // Enable this interceptor in any environment\n // that has a global WebSocket API.\n return typeof globalThis.WebSocket !== 'undefined'\n }\n\n protected setup(): void {\n const originalWebSocket = globalThis.WebSocket\n\n const webSocketProxy = new Proxy(globalThis.WebSocket, {\n construct: (\n target,\n args: ConstructorParameters,\n newTarget\n ) => {\n const [url, protocols] = args\n\n const createConnection = (): WebSocket => {\n return Reflect.construct(target, args, newTarget)\n }\n\n // All WebSocket instances are mocked and don't forward\n // any events to the original server (no connection established).\n // To forward the events, the user must use the \"server.send()\" API.\n const socket = new WebSocketOverride(url, protocols)\n const transport = new WebSocketClassTransport(socket)\n\n // Emit the \"connection\" event to the interceptor on the next tick\n // so the client can modify WebSocket options, like \"binaryType\"\n // while the connection is already pending.\n queueMicrotask(() => {\n // The \"globalThis.WebSocket\" class stands for\n // the client-side connection. Assume it's established\n // as soon as the WebSocket instance is constructed.\n this.emitter.emit('connection', {\n client: new WebSocketClientConnection(socket, transport),\n server: new WebSocketServerConnection(\n socket,\n transport,\n createConnection\n ),\n })\n })\n\n return socket\n },\n })\n\n globalThis.WebSocket = webSocketProxy\n\n this.subscriptions.push(() => {\n globalThis.WebSocket = originalWebSocket\n })\n }\n}\n"],"mappings":"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","names":["invariant","kEmitter","kBoundListener","invariant"]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/interceptors/XMLHttpRequest/index.d.ts b/node_modules/@mswjs/interceptors/lib/browser/interceptors/XMLHttpRequest/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..66319fa3dcff20ebae48474fc7db754e00af520b --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/interceptors/XMLHttpRequest/index.d.ts @@ -0,0 +1,19 @@ +import { Emitter } from 'strict-event-emitter'; +import { a as InteractiveRequest, H as HttpRequestEventMap } from '../../glossary-1c204f45.js'; +import { I as Interceptor } from '../../Interceptor-af98b768.js'; +import '@open-draft/deferred-promise'; +import '@open-draft/logger'; + +type XMLHttpRequestEventListener = (args: { + request: InteractiveRequest; + requestId: string; +}) => Promise | void; +type XMLHttpRequestEmitter = Emitter; +declare class XMLHttpRequestInterceptor extends Interceptor { + static interceptorSymbol: symbol; + constructor(); + protected checkEnvironment(): boolean; + protected setup(): void; +} + +export { XMLHttpRequestEmitter, XMLHttpRequestEventListener, XMLHttpRequestInterceptor }; diff --git a/node_modules/@mswjs/interceptors/lib/browser/interceptors/XMLHttpRequest/index.js b/node_modules/@mswjs/interceptors/lib/browser/interceptors/XMLHttpRequest/index.js new file mode 100644 index 0000000000000000000000000000000000000000..7ceb0b4361d5c2782d0e4ac7c2bfdd946ba08fc2 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/interceptors/XMLHttpRequest/index.js @@ -0,0 +1,11 @@ +"use strict";Object.defineProperty(exports, "__esModule", {value: true}); + +var _chunkPSX5J3RFjs = require('../../chunk-PSX5J3RF.js'); +require('../../chunk-LK6DILFK.js'); +require('../../chunk-MQJ3JOOK.js'); +require('../../chunk-2CRB3JAQ.js'); +require('../../chunk-TIPR373R.js'); + + +exports.XMLHttpRequestInterceptor = _chunkPSX5J3RFjs.XMLHttpRequestInterceptor; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/interceptors/XMLHttpRequest/index.js.map b/node_modules/@mswjs/interceptors/lib/browser/interceptors/XMLHttpRequest/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a464c6732ec9fa9ef5cf78917d42f90f2200eb58 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/interceptors/XMLHttpRequest/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/interceptors/XMLHttpRequest/index.mjs b/node_modules/@mswjs/interceptors/lib/browser/interceptors/XMLHttpRequest/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2265306e675943a2f284ce44148d7f102f4f23c8 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/interceptors/XMLHttpRequest/index.mjs @@ -0,0 +1,11 @@ +import { + XMLHttpRequestInterceptor +} from "../../chunk-732REFPX.mjs"; +import "../../chunk-6HYIRFX2.mjs"; +import "../../chunk-OUWBQF3Z.mjs"; +import "../../chunk-OMISYKWR.mjs"; +import "../../chunk-QED3Q6Z2.mjs"; +export { + XMLHttpRequestInterceptor +}; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/interceptors/XMLHttpRequest/index.mjs.map b/node_modules/@mswjs/interceptors/lib/browser/interceptors/XMLHttpRequest/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..84c51b288c478ac0d18748007ccfb8cddc797f3a --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/interceptors/XMLHttpRequest/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/interceptors/fetch/index.d.ts b/node_modules/@mswjs/interceptors/lib/browser/interceptors/fetch/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..27958e6f4f6e25654f99d254f0eed35a60f77304 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/interceptors/fetch/index.d.ts @@ -0,0 +1,14 @@ +import { H as HttpRequestEventMap } from '../../glossary-1c204f45.js'; +import { I as Interceptor } from '../../Interceptor-af98b768.js'; +import '@open-draft/deferred-promise'; +import '@open-draft/logger'; +import 'strict-event-emitter'; + +declare class FetchInterceptor extends Interceptor { + static symbol: symbol; + constructor(); + protected checkEnvironment(): boolean; + protected setup(): Promise; +} + +export { FetchInterceptor }; diff --git a/node_modules/@mswjs/interceptors/lib/browser/interceptors/fetch/index.js b/node_modules/@mswjs/interceptors/lib/browser/interceptors/fetch/index.js new file mode 100644 index 0000000000000000000000000000000000000000..121e6436eb3f7dbc0c17a058d4e72aa6f1636b2a --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/interceptors/fetch/index.js @@ -0,0 +1,10 @@ +"use strict";Object.defineProperty(exports, "__esModule", {value: true}); + +var _chunkWBHIW62Pjs = require('../../chunk-WBHIW62P.js'); +require('../../chunk-MQJ3JOOK.js'); +require('../../chunk-2CRB3JAQ.js'); +require('../../chunk-TIPR373R.js'); + + +exports.FetchInterceptor = _chunkWBHIW62Pjs.FetchInterceptor; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/interceptors/fetch/index.js.map b/node_modules/@mswjs/interceptors/lib/browser/interceptors/fetch/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a464c6732ec9fa9ef5cf78917d42f90f2200eb58 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/interceptors/fetch/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/interceptors/fetch/index.mjs b/node_modules/@mswjs/interceptors/lib/browser/interceptors/fetch/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..effaaf425bc901ee8886260d69fa55860cfdfef3 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/interceptors/fetch/index.mjs @@ -0,0 +1,10 @@ +import { + FetchInterceptor +} from "../../chunk-MAEPOYB6.mjs"; +import "../../chunk-OUWBQF3Z.mjs"; +import "../../chunk-OMISYKWR.mjs"; +import "../../chunk-QED3Q6Z2.mjs"; +export { + FetchInterceptor +}; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/interceptors/fetch/index.mjs.map b/node_modules/@mswjs/interceptors/lib/browser/interceptors/fetch/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..84c51b288c478ac0d18748007ccfb8cddc797f3a --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/interceptors/fetch/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/presets/browser.d.ts b/node_modules/@mswjs/interceptors/lib/browser/presets/browser.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..773709bc49e5c14e8b37b4df5d50a713d40ea258 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/presets/browser.d.ts @@ -0,0 +1,15 @@ +import { FetchInterceptor } from '../interceptors/fetch/index.js'; +import { XMLHttpRequestInterceptor } from '../interceptors/XMLHttpRequest/index.js'; +import '../glossary-1c204f45.js'; +import '@open-draft/deferred-promise'; +import '../Interceptor-af98b768.js'; +import '@open-draft/logger'; +import 'strict-event-emitter'; + +/** + * The default preset provisions the interception of requests + * regardless of their type (fetch/XMLHttpRequest). + */ +declare const _default: readonly [FetchInterceptor, XMLHttpRequestInterceptor]; + +export { _default as default }; diff --git a/node_modules/@mswjs/interceptors/lib/browser/presets/browser.js b/node_modules/@mswjs/interceptors/lib/browser/presets/browser.js new file mode 100644 index 0000000000000000000000000000000000000000..b9fb84fcd2a8773e250d356b3338a9cf532f6c50 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/presets/browser.js @@ -0,0 +1,20 @@ +"use strict";Object.defineProperty(exports, "__esModule", {value: true}); + +var _chunkPSX5J3RFjs = require('../chunk-PSX5J3RF.js'); +require('../chunk-LK6DILFK.js'); + + +var _chunkWBHIW62Pjs = require('../chunk-WBHIW62P.js'); +require('../chunk-MQJ3JOOK.js'); +require('../chunk-2CRB3JAQ.js'); +require('../chunk-TIPR373R.js'); + +// src/presets/browser.ts +var browser_default = [ + new (0, _chunkWBHIW62Pjs.FetchInterceptor)(), + new (0, _chunkPSX5J3RFjs.XMLHttpRequestInterceptor)() +]; + + +exports.default = browser_default; +//# sourceMappingURL=browser.js.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/presets/browser.js.map b/node_modules/@mswjs/interceptors/lib/browser/presets/browser.js.map new file mode 100644 index 0000000000000000000000000000000000000000..8af23e493a3423a149603dc8c487ffb0c48e4280 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/presets/browser.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/presets/browser.ts"],"names":[],"mappings":";;;;;;;;;;;;AAOA,IAAO,kBAAQ;AAAA,EACb,IAAI,iBAAiB;AAAA,EACrB,IAAI,0BAA0B;AAChC","sourcesContent":["import { FetchInterceptor } from '../interceptors/fetch'\nimport { XMLHttpRequestInterceptor } from '../interceptors/XMLHttpRequest'\n\n/**\n * The default preset provisions the interception of requests\n * regardless of their type (fetch/XMLHttpRequest).\n */\nexport default [\n new FetchInterceptor(),\n new XMLHttpRequestInterceptor(),\n] as const\n"]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/presets/browser.mjs b/node_modules/@mswjs/interceptors/lib/browser/presets/browser.mjs new file mode 100644 index 0000000000000000000000000000000000000000..097998f0f3c9385541f58a644fe74655555917b4 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/presets/browser.mjs @@ -0,0 +1,20 @@ +import { + XMLHttpRequestInterceptor +} from "../chunk-732REFPX.mjs"; +import "../chunk-6HYIRFX2.mjs"; +import { + FetchInterceptor +} from "../chunk-MAEPOYB6.mjs"; +import "../chunk-OUWBQF3Z.mjs"; +import "../chunk-OMISYKWR.mjs"; +import "../chunk-QED3Q6Z2.mjs"; + +// src/presets/browser.ts +var browser_default = [ + new FetchInterceptor(), + new XMLHttpRequestInterceptor() +]; +export { + browser_default as default +}; +//# sourceMappingURL=browser.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/presets/browser.mjs.map b/node_modules/@mswjs/interceptors/lib/browser/presets/browser.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..8fd34d436f85e381472b63f10cfe0bee1e65465a --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/presets/browser.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/presets/browser.ts"],"sourcesContent":["import { FetchInterceptor } from '../interceptors/fetch'\nimport { XMLHttpRequestInterceptor } from '../interceptors/XMLHttpRequest'\n\n/**\n * The default preset provisions the interception of requests\n * regardless of their type (fetch/XMLHttpRequest).\n */\nexport default [\n new FetchInterceptor(),\n new XMLHttpRequestInterceptor(),\n] as const\n"],"mappings":";;;;;;;;;;;;AAOA,IAAO,kBAAQ;AAAA,EACb,IAAI,iBAAiB;AAAA,EACrB,IAAI,0BAA0B;AAChC;","names":[]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/BatchInterceptor-2badedde.d.ts b/node_modules/@mswjs/interceptors/lib/node/BatchInterceptor-2badedde.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..212fa61c2d29d3bb5d90a28c4edcc3152e48284a --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/BatchInterceptor-2badedde.d.ts @@ -0,0 +1,24 @@ +import { EventMap, Listener } from 'strict-event-emitter'; +import { f as Interceptor, E as ExtractEventNames } from './Interceptor-88ee47c0.js'; + +interface BatchInterceptorOptions>> { + name: string; + interceptors: InterceptorList; +} +type ExtractEventMapType>> = InterceptorList extends ReadonlyArray ? InterceptorType extends Interceptor ? EventMap : never : never; +/** + * A batch interceptor that exposes a single interface + * to apply and operate with multiple interceptors at once. + */ +declare class BatchInterceptor>, Events extends EventMap = ExtractEventMapType> extends Interceptor { + static symbol: symbol; + private interceptors; + constructor(options: BatchInterceptorOptions); + protected setup(): void; + on>(event: EventName, listener: Listener): this; + once>(event: EventName, listener: Listener): this; + off>(event: EventName, listener: Listener): this; + removeAllListeners>(event?: EventName | undefined): this; +} + +export { BatchInterceptorOptions as B, ExtractEventMapType as E, BatchInterceptor as a }; diff --git a/node_modules/@mswjs/interceptors/lib/node/Interceptor-88ee47c0.d.ts b/node_modules/@mswjs/interceptors/lib/node/Interceptor-88ee47c0.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3f7bb080bf0e341b2c2842202c914c0a508b3949 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/Interceptor-88ee47c0.d.ts @@ -0,0 +1,105 @@ +import { DeferredPromise } from '@open-draft/deferred-promise'; +import { Logger } from '@open-draft/logger'; +import { Emitter, Listener } from 'strict-event-emitter'; + +declare class RequestController { + protected request: Request; + responsePromise: DeferredPromise; + constructor(request: Request); + respondWith(response?: Response): void; +} + +type InteractiveRequest = globalThis.Request & { + respondWith: RequestController['respondWith']; +}; + +declare const IS_PATCHED_MODULE: unique symbol; +type RequestCredentials = 'omit' | 'include' | 'same-origin'; +type HttpRequestEventMap = { + request: [ + args: { + request: InteractiveRequest; + requestId: string; + } + ]; + response: [ + args: { + response: Response; + isMockedResponse: boolean; + request: Request; + requestId: string; + } + ]; + unhandledException: [ + args: { + error: unknown; + request: Request; + requestId: string; + controller: { + respondWith(response: Response): void; + errorWith(error?: Error): void; + }; + } + ]; +}; + +type InterceptorEventMap = Record; +type InterceptorSubscription = () => void; +/** + * Request header name to detect when a single request + * is being handled by nested interceptors (XHR -> ClientRequest). + * Obscure by design to prevent collisions with user-defined headers. + * Ideally, come up with the Interceptor-level mechanism for this. + * @see https://github.com/mswjs/interceptors/issues/378 + */ +declare const INTERNAL_REQUEST_ID_HEADER_NAME = "x-interceptors-internal-request-id"; +declare function getGlobalSymbol(symbol: Symbol): V | undefined; +declare function deleteGlobalSymbol(symbol: Symbol): void; +declare enum InterceptorReadyState { + INACTIVE = "INACTIVE", + APPLYING = "APPLYING", + APPLIED = "APPLIED", + DISPOSING = "DISPOSING", + DISPOSED = "DISPOSED" +} +type ExtractEventNames> = Events extends Record ? EventName : never; +declare class Interceptor { + private readonly symbol; + protected emitter: Emitter; + protected subscriptions: Array; + protected logger: Logger; + readyState: InterceptorReadyState; + constructor(symbol: symbol); + /** + * Determine if this interceptor can be applied + * in the current environment. + */ + protected checkEnvironment(): boolean; + /** + * Apply this interceptor to the current process. + * Returns an already running interceptor instance if it's present. + */ + apply(): void; + /** + * Setup the module augments and stubs necessary for this interceptor. + * This method is not run if there's a running interceptor instance + * to prevent instantiating an interceptor multiple times. + */ + protected setup(): void; + /** + * Listen to the interceptor's public events. + */ + on>(event: EventName, listener: Listener): this; + once>(event: EventName, listener: Listener): this; + off>(event: EventName, listener: Listener): this; + removeAllListeners>(event?: EventName): this; + /** + * Disposes of any side-effects this interceptor has introduced. + */ + dispose(): void; + private getInstance; + private setInstance; + private clearInstance; +} + +export { ExtractEventNames as E, HttpRequestEventMap as H, IS_PATCHED_MODULE as I, RequestCredentials as R, InterceptorEventMap as a, InterceptorSubscription as b, INTERNAL_REQUEST_ID_HEADER_NAME as c, deleteGlobalSymbol as d, InterceptorReadyState as e, Interceptor as f, getGlobalSymbol as g, InteractiveRequest as h }; diff --git a/node_modules/@mswjs/interceptors/lib/node/RemoteHttpInterceptor.d.ts b/node_modules/@mswjs/interceptors/lib/node/RemoteHttpInterceptor.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0c3d1e3044664605d2e78a4a8038b27a2e68e91c --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/RemoteHttpInterceptor.d.ts @@ -0,0 +1,44 @@ +import { ChildProcess } from 'child_process'; +import { f as Interceptor, H as HttpRequestEventMap } from './Interceptor-88ee47c0.js'; +import { a as BatchInterceptor } from './BatchInterceptor-2badedde.js'; +import { ClientRequestInterceptor } from './interceptors/ClientRequest/index.js'; +import { XMLHttpRequestInterceptor } from './interceptors/XMLHttpRequest/index.js'; +import '@open-draft/deferred-promise'; +import '@open-draft/logger'; +import 'strict-event-emitter'; +import 'http'; +import 'https'; + +interface SerializedRequest { + id: string; + url: string; + method: string; + headers: Array<[string, string]>; + credentials: RequestCredentials; + body: string; +} +interface SerializedResponse { + status: number; + statusText: string; + headers: Array<[string, string]>; + body: string; +} +declare class RemoteHttpInterceptor extends BatchInterceptor<[ + ClientRequestInterceptor, + XMLHttpRequestInterceptor +]> { + constructor(); + protected setup(): void; +} +declare function requestReviver(key: string, value: any): any; +interface RemoveResolverOptions { + process: ChildProcess; +} +declare class RemoteHttpResolver extends Interceptor { + static symbol: symbol; + private process; + constructor(options: RemoveResolverOptions); + protected setup(): void; +} + +export { RemoteHttpInterceptor, RemoteHttpResolver, RemoveResolverOptions, SerializedRequest, SerializedResponse, requestReviver }; diff --git a/node_modules/@mswjs/interceptors/lib/node/RemoteHttpInterceptor.js b/node_modules/@mswjs/interceptors/lib/node/RemoteHttpInterceptor.js new file mode 100644 index 0000000000000000000000000000000000000000..72e70d231b5d72bdb2ba3e07e0d7ea7bb1cafa62 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/RemoteHttpInterceptor.js @@ -0,0 +1,181 @@ +"use strict";Object.defineProperty(exports, "__esModule", {value: true}); + +var _chunkLTEXDYJ6js = require('./chunk-LTEXDYJ6.js'); + + +var _chunkSXGRMPXPjs = require('./chunk-SXGRMPXP.js'); + + +var _chunkAPT7KA3Bjs = require('./chunk-APT7KA3B.js'); +require('./chunk-LK6DILFK.js'); +require('./chunk-EIBTX65O.js'); + + + +var _chunkMQJ3JOOKjs = require('./chunk-MQJ3JOOK.js'); + + +var _chunkE4AC7YACjs = require('./chunk-E4AC7YAC.js'); + +// src/RemoteHttpInterceptor.ts +var RemoteHttpInterceptor = class extends _chunkLTEXDYJ6js.BatchInterceptor { + constructor() { + super({ + name: "remote-interceptor", + interceptors: [ + new (0, _chunkSXGRMPXPjs.ClientRequestInterceptor)(), + new (0, _chunkAPT7KA3Bjs.XMLHttpRequestInterceptor)() + ] + }); + } + setup() { + super.setup(); + let handleParentMessage; + this.on("request", async ({ request, requestId }) => { + var _a; + const serializedRequest = JSON.stringify({ + id: requestId, + method: request.method, + url: request.url, + headers: Array.from(request.headers.entries()), + credentials: request.credentials, + body: ["GET", "HEAD"].includes(request.method) ? null : await request.text() + }); + this.logger.info( + "sent serialized request to the child:", + serializedRequest + ); + (_a = process.send) == null ? void 0 : _a.call(process, `request:${serializedRequest}`); + const responsePromise = new Promise((resolve) => { + handleParentMessage = (message) => { + if (typeof message !== "string") { + return resolve(); + } + if (message.startsWith(`response:${requestId}`)) { + const [, serializedResponse] = message.match(/^response:.+?:(.+)$/) || []; + if (!serializedResponse) { + return resolve(); + } + const responseInit = JSON.parse( + serializedResponse + ); + const mockedResponse = new Response(responseInit.body, { + status: responseInit.status, + statusText: responseInit.statusText, + headers: responseInit.headers + }); + request.respondWith(mockedResponse); + return resolve(); + } + }; + }); + this.logger.info( + 'add "message" listener to the parent process', + handleParentMessage + ); + process.addListener("message", handleParentMessage); + return responsePromise; + }); + this.subscriptions.push(() => { + process.removeListener("message", handleParentMessage); + }); + } +}; +function requestReviver(key, value) { + switch (key) { + case "url": + return new URL(value); + case "headers": + return new Headers(value); + default: + return value; + } +} +var _RemoteHttpResolver = class extends _chunkE4AC7YACjs.Interceptor { + constructor(options) { + super(_RemoteHttpResolver.symbol); + this.process = options.process; + } + setup() { + const logger = this.logger.extend("setup"); + const handleChildMessage = async (message) => { + logger.info("received message from child!", message); + if (typeof message !== "string" || !message.startsWith("request:")) { + logger.info("unknown message, ignoring..."); + return; + } + const [, serializedRequest] = message.match(/^request:(.+)$/) || []; + if (!serializedRequest) { + return; + } + const requestJson = JSON.parse( + serializedRequest, + requestReviver + ); + logger.info("parsed intercepted request", requestJson); + const capturedRequest = new Request(requestJson.url, { + method: requestJson.method, + headers: new Headers(requestJson.headers), + credentials: requestJson.credentials, + body: requestJson.body + }); + const { interactiveRequest, requestController } = _chunkMQJ3JOOKjs.toInteractiveRequest.call(void 0, capturedRequest); + this.emitter.once("request", () => { + if (requestController.responsePromise.state === "pending") { + requestController.respondWith(void 0); + } + }); + await _chunkMQJ3JOOKjs.emitAsync.call(void 0, this.emitter, "request", { + request: interactiveRequest, + requestId: requestJson.id + }); + const mockedResponse = await requestController.responsePromise; + if (!mockedResponse) { + return; + } + logger.info("event.respondWith called with:", mockedResponse); + const responseClone = mockedResponse.clone(); + const responseText = await mockedResponse.text(); + const serializedResponse = JSON.stringify({ + status: mockedResponse.status, + statusText: mockedResponse.statusText, + headers: Array.from(mockedResponse.headers.entries()), + body: responseText + }); + this.process.send( + `response:${requestJson.id}:${serializedResponse}`, + (error) => { + if (error) { + return; + } + this.emitter.emit("response", { + response: responseClone, + isMockedResponse: true, + request: capturedRequest, + requestId: requestJson.id + }); + } + ); + logger.info( + "sent serialized mocked response to the parent:", + serializedResponse + ); + }; + this.subscriptions.push(() => { + this.process.removeListener("message", handleChildMessage); + logger.info('removed the "message" listener from the child process!'); + }); + logger.info('adding a "message" listener to the child process'); + this.process.addListener("message", handleChildMessage); + this.process.once("error", () => this.dispose()); + this.process.once("exit", () => this.dispose()); + } +}; +var RemoteHttpResolver = _RemoteHttpResolver; +RemoteHttpResolver.symbol = Symbol("remote-resolver"); + + + + +exports.RemoteHttpInterceptor = RemoteHttpInterceptor; exports.RemoteHttpResolver = RemoteHttpResolver; exports.requestReviver = requestReviver; +//# sourceMappingURL=RemoteHttpInterceptor.js.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/RemoteHttpInterceptor.js.map b/node_modules/@mswjs/interceptors/lib/node/RemoteHttpInterceptor.js.map new file mode 100644 index 0000000000000000000000000000000000000000..85a4f887a42e8ced3eb9ac91c6a8667435571946 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/RemoteHttpInterceptor.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/RemoteHttpInterceptor.ts"],"names":[],"mappings":"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","sourcesContent":["import { ChildProcess } from 'child_process'\nimport { HttpRequestEventMap } from './glossary'\nimport { Interceptor } from './Interceptor'\nimport { BatchInterceptor } from './BatchInterceptor'\nimport { ClientRequestInterceptor } from './interceptors/ClientRequest'\nimport { XMLHttpRequestInterceptor } from './interceptors/XMLHttpRequest'\nimport { toInteractiveRequest } from './utils/toInteractiveRequest'\nimport { emitAsync } from './utils/emitAsync'\n\nexport interface SerializedRequest {\n id: string\n url: string\n method: string\n headers: Array<[string, string]>\n credentials: RequestCredentials\n body: string\n}\n\ninterface RevivedRequest extends Omit {\n url: URL\n headers: Headers\n}\n\nexport interface SerializedResponse {\n status: number\n statusText: string\n headers: Array<[string, string]>\n body: string\n}\n\nexport class RemoteHttpInterceptor extends BatchInterceptor<\n [ClientRequestInterceptor, XMLHttpRequestInterceptor]\n> {\n constructor() {\n super({\n name: 'remote-interceptor',\n interceptors: [\n new ClientRequestInterceptor(),\n new XMLHttpRequestInterceptor(),\n ],\n })\n }\n\n protected setup() {\n super.setup()\n\n let handleParentMessage: NodeJS.MessageListener\n\n this.on('request', async ({ request, requestId }) => {\n // Send the stringified intercepted request to\n // the parent process where the remote resolver is established.\n const serializedRequest = JSON.stringify({\n id: requestId,\n method: request.method,\n url: request.url,\n headers: Array.from(request.headers.entries()),\n credentials: request.credentials,\n body: ['GET', 'HEAD'].includes(request.method)\n ? null\n : await request.text(),\n } as SerializedRequest)\n\n this.logger.info(\n 'sent serialized request to the child:',\n serializedRequest\n )\n process.send?.(`request:${serializedRequest}`)\n\n const responsePromise = new Promise((resolve) => {\n handleParentMessage = (message) => {\n if (typeof message !== 'string') {\n return resolve()\n }\n\n if (message.startsWith(`response:${requestId}`)) {\n const [, serializedResponse] =\n message.match(/^response:.+?:(.+)$/) || []\n\n if (!serializedResponse) {\n return resolve()\n }\n\n const responseInit = JSON.parse(\n serializedResponse\n ) as SerializedResponse\n\n const mockedResponse = new Response(responseInit.body, {\n status: responseInit.status,\n statusText: responseInit.statusText,\n headers: responseInit.headers,\n })\n\n request.respondWith(mockedResponse)\n return resolve()\n }\n }\n })\n\n // Listen for the mocked response message from the parent.\n this.logger.info(\n 'add \"message\" listener to the parent process',\n handleParentMessage\n )\n process.addListener('message', handleParentMessage)\n\n return responsePromise\n })\n\n this.subscriptions.push(() => {\n process.removeListener('message', handleParentMessage)\n })\n }\n}\n\nexport function requestReviver(key: string, value: any) {\n switch (key) {\n case 'url':\n return new URL(value)\n\n case 'headers':\n return new Headers(value)\n\n default:\n return value\n }\n}\n\nexport interface RemoveResolverOptions {\n process: ChildProcess\n}\n\nexport class RemoteHttpResolver extends Interceptor {\n static symbol = Symbol('remote-resolver')\n private process: ChildProcess\n\n constructor(options: RemoveResolverOptions) {\n super(RemoteHttpResolver.symbol)\n this.process = options.process\n }\n\n protected setup() {\n const logger = this.logger.extend('setup')\n\n const handleChildMessage: NodeJS.MessageListener = async (message) => {\n logger.info('received message from child!', message)\n\n if (typeof message !== 'string' || !message.startsWith('request:')) {\n logger.info('unknown message, ignoring...')\n return\n }\n\n const [, serializedRequest] = message.match(/^request:(.+)$/) || []\n if (!serializedRequest) {\n return\n }\n\n const requestJson = JSON.parse(\n serializedRequest,\n requestReviver\n ) as RevivedRequest\n logger.info('parsed intercepted request', requestJson)\n\n const capturedRequest = new Request(requestJson.url, {\n method: requestJson.method,\n headers: new Headers(requestJson.headers),\n credentials: requestJson.credentials,\n body: requestJson.body,\n })\n\n const { interactiveRequest, requestController } =\n toInteractiveRequest(capturedRequest)\n\n this.emitter.once('request', () => {\n if (requestController.responsePromise.state === 'pending') {\n requestController.respondWith(undefined)\n }\n })\n\n await emitAsync(this.emitter, 'request', {\n request: interactiveRequest,\n requestId: requestJson.id,\n })\n\n const mockedResponse = await requestController.responsePromise\n\n if (!mockedResponse) {\n return\n }\n\n logger.info('event.respondWith called with:', mockedResponse)\n const responseClone = mockedResponse.clone()\n const responseText = await mockedResponse.text()\n\n // Send the mocked response to the child process.\n const serializedResponse = JSON.stringify({\n status: mockedResponse.status,\n statusText: mockedResponse.statusText,\n headers: Array.from(mockedResponse.headers.entries()),\n body: responseText,\n } as SerializedResponse)\n\n this.process.send(\n `response:${requestJson.id}:${serializedResponse}`,\n (error) => {\n if (error) {\n return\n }\n\n // Emit an optimistic \"response\" event at this point,\n // not to rely on the back-and-forth signaling for the sake of the event.\n this.emitter.emit('response', {\n response: responseClone,\n isMockedResponse: true,\n request: capturedRequest,\n requestId: requestJson.id,\n })\n }\n )\n\n logger.info(\n 'sent serialized mocked response to the parent:',\n serializedResponse\n )\n }\n\n this.subscriptions.push(() => {\n this.process.removeListener('message', handleChildMessage)\n logger.info('removed the \"message\" listener from the child process!')\n })\n\n logger.info('adding a \"message\" listener to the child process')\n this.process.addListener('message', handleChildMessage)\n\n this.process.once('error', () => this.dispose())\n this.process.once('exit', () => this.dispose())\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/RemoteHttpInterceptor.mjs b/node_modules/@mswjs/interceptors/lib/node/RemoteHttpInterceptor.mjs new file mode 100644 index 0000000000000000000000000000000000000000..097640d14a55d23d37c77ebe69074583a59a1bea --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/RemoteHttpInterceptor.mjs @@ -0,0 +1,181 @@ +import { + BatchInterceptor +} from "./chunk-6FRASLM3.mjs"; +import { + ClientRequestInterceptor +} from "./chunk-CVV3L375.mjs"; +import { + XMLHttpRequestInterceptor +} from "./chunk-KSHIDGUL.mjs"; +import "./chunk-6HYIRFX2.mjs"; +import "./chunk-OJ6O4LSC.mjs"; +import { + emitAsync, + toInteractiveRequest +} from "./chunk-OUWBQF3Z.mjs"; +import { + Interceptor +} from "./chunk-Q7POAM5N.mjs"; + +// src/RemoteHttpInterceptor.ts +var RemoteHttpInterceptor = class extends BatchInterceptor { + constructor() { + super({ + name: "remote-interceptor", + interceptors: [ + new ClientRequestInterceptor(), + new XMLHttpRequestInterceptor() + ] + }); + } + setup() { + super.setup(); + let handleParentMessage; + this.on("request", async ({ request, requestId }) => { + var _a; + const serializedRequest = JSON.stringify({ + id: requestId, + method: request.method, + url: request.url, + headers: Array.from(request.headers.entries()), + credentials: request.credentials, + body: ["GET", "HEAD"].includes(request.method) ? null : await request.text() + }); + this.logger.info( + "sent serialized request to the child:", + serializedRequest + ); + (_a = process.send) == null ? void 0 : _a.call(process, `request:${serializedRequest}`); + const responsePromise = new Promise((resolve) => { + handleParentMessage = (message) => { + if (typeof message !== "string") { + return resolve(); + } + if (message.startsWith(`response:${requestId}`)) { + const [, serializedResponse] = message.match(/^response:.+?:(.+)$/) || []; + if (!serializedResponse) { + return resolve(); + } + const responseInit = JSON.parse( + serializedResponse + ); + const mockedResponse = new Response(responseInit.body, { + status: responseInit.status, + statusText: responseInit.statusText, + headers: responseInit.headers + }); + request.respondWith(mockedResponse); + return resolve(); + } + }; + }); + this.logger.info( + 'add "message" listener to the parent process', + handleParentMessage + ); + process.addListener("message", handleParentMessage); + return responsePromise; + }); + this.subscriptions.push(() => { + process.removeListener("message", handleParentMessage); + }); + } +}; +function requestReviver(key, value) { + switch (key) { + case "url": + return new URL(value); + case "headers": + return new Headers(value); + default: + return value; + } +} +var _RemoteHttpResolver = class extends Interceptor { + constructor(options) { + super(_RemoteHttpResolver.symbol); + this.process = options.process; + } + setup() { + const logger = this.logger.extend("setup"); + const handleChildMessage = async (message) => { + logger.info("received message from child!", message); + if (typeof message !== "string" || !message.startsWith("request:")) { + logger.info("unknown message, ignoring..."); + return; + } + const [, serializedRequest] = message.match(/^request:(.+)$/) || []; + if (!serializedRequest) { + return; + } + const requestJson = JSON.parse( + serializedRequest, + requestReviver + ); + logger.info("parsed intercepted request", requestJson); + const capturedRequest = new Request(requestJson.url, { + method: requestJson.method, + headers: new Headers(requestJson.headers), + credentials: requestJson.credentials, + body: requestJson.body + }); + const { interactiveRequest, requestController } = toInteractiveRequest(capturedRequest); + this.emitter.once("request", () => { + if (requestController.responsePromise.state === "pending") { + requestController.respondWith(void 0); + } + }); + await emitAsync(this.emitter, "request", { + request: interactiveRequest, + requestId: requestJson.id + }); + const mockedResponse = await requestController.responsePromise; + if (!mockedResponse) { + return; + } + logger.info("event.respondWith called with:", mockedResponse); + const responseClone = mockedResponse.clone(); + const responseText = await mockedResponse.text(); + const serializedResponse = JSON.stringify({ + status: mockedResponse.status, + statusText: mockedResponse.statusText, + headers: Array.from(mockedResponse.headers.entries()), + body: responseText + }); + this.process.send( + `response:${requestJson.id}:${serializedResponse}`, + (error) => { + if (error) { + return; + } + this.emitter.emit("response", { + response: responseClone, + isMockedResponse: true, + request: capturedRequest, + requestId: requestJson.id + }); + } + ); + logger.info( + "sent serialized mocked response to the parent:", + serializedResponse + ); + }; + this.subscriptions.push(() => { + this.process.removeListener("message", handleChildMessage); + logger.info('removed the "message" listener from the child process!'); + }); + logger.info('adding a "message" listener to the child process'); + this.process.addListener("message", handleChildMessage); + this.process.once("error", () => this.dispose()); + this.process.once("exit", () => this.dispose()); + } +}; +var RemoteHttpResolver = _RemoteHttpResolver; +RemoteHttpResolver.symbol = Symbol("remote-resolver"); +export { + RemoteHttpInterceptor, + RemoteHttpResolver, + requestReviver +}; +//# sourceMappingURL=RemoteHttpInterceptor.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/RemoteHttpInterceptor.mjs.map b/node_modules/@mswjs/interceptors/lib/node/RemoteHttpInterceptor.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..273728705107904d8fbfd6790a03894d731a17f9 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/RemoteHttpInterceptor.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/RemoteHttpInterceptor.ts"],"sourcesContent":["import { ChildProcess } from 'child_process'\nimport { HttpRequestEventMap } from './glossary'\nimport { Interceptor } from './Interceptor'\nimport { BatchInterceptor } from './BatchInterceptor'\nimport { ClientRequestInterceptor } from './interceptors/ClientRequest'\nimport { XMLHttpRequestInterceptor } from './interceptors/XMLHttpRequest'\nimport { toInteractiveRequest } from './utils/toInteractiveRequest'\nimport { emitAsync } from './utils/emitAsync'\n\nexport interface SerializedRequest {\n id: string\n url: string\n method: string\n headers: Array<[string, string]>\n credentials: RequestCredentials\n body: string\n}\n\ninterface RevivedRequest extends Omit {\n url: URL\n headers: Headers\n}\n\nexport interface SerializedResponse {\n status: number\n statusText: string\n headers: Array<[string, string]>\n body: string\n}\n\nexport class RemoteHttpInterceptor extends BatchInterceptor<\n [ClientRequestInterceptor, XMLHttpRequestInterceptor]\n> {\n constructor() {\n super({\n name: 'remote-interceptor',\n interceptors: [\n new ClientRequestInterceptor(),\n new XMLHttpRequestInterceptor(),\n ],\n })\n }\n\n protected setup() {\n super.setup()\n\n let handleParentMessage: NodeJS.MessageListener\n\n this.on('request', async ({ request, requestId }) => {\n // Send the stringified intercepted request to\n // the parent process where the remote resolver is established.\n const serializedRequest = JSON.stringify({\n id: requestId,\n method: request.method,\n url: request.url,\n headers: Array.from(request.headers.entries()),\n credentials: request.credentials,\n body: ['GET', 'HEAD'].includes(request.method)\n ? null\n : await request.text(),\n } as SerializedRequest)\n\n this.logger.info(\n 'sent serialized request to the child:',\n serializedRequest\n )\n process.send?.(`request:${serializedRequest}`)\n\n const responsePromise = new Promise((resolve) => {\n handleParentMessage = (message) => {\n if (typeof message !== 'string') {\n return resolve()\n }\n\n if (message.startsWith(`response:${requestId}`)) {\n const [, serializedResponse] =\n message.match(/^response:.+?:(.+)$/) || []\n\n if (!serializedResponse) {\n return resolve()\n }\n\n const responseInit = JSON.parse(\n serializedResponse\n ) as SerializedResponse\n\n const mockedResponse = new Response(responseInit.body, {\n status: responseInit.status,\n statusText: responseInit.statusText,\n headers: responseInit.headers,\n })\n\n request.respondWith(mockedResponse)\n return resolve()\n }\n }\n })\n\n // Listen for the mocked response message from the parent.\n this.logger.info(\n 'add \"message\" listener to the parent process',\n handleParentMessage\n )\n process.addListener('message', handleParentMessage)\n\n return responsePromise\n })\n\n this.subscriptions.push(() => {\n process.removeListener('message', handleParentMessage)\n })\n }\n}\n\nexport function requestReviver(key: string, value: any) {\n switch (key) {\n case 'url':\n return new URL(value)\n\n case 'headers':\n return new Headers(value)\n\n default:\n return value\n }\n}\n\nexport interface RemoveResolverOptions {\n process: ChildProcess\n}\n\nexport class RemoteHttpResolver extends Interceptor {\n static symbol = Symbol('remote-resolver')\n private process: ChildProcess\n\n constructor(options: RemoveResolverOptions) {\n super(RemoteHttpResolver.symbol)\n this.process = options.process\n }\n\n protected setup() {\n const logger = this.logger.extend('setup')\n\n const handleChildMessage: NodeJS.MessageListener = async (message) => {\n logger.info('received message from child!', message)\n\n if (typeof message !== 'string' || !message.startsWith('request:')) {\n logger.info('unknown message, ignoring...')\n return\n }\n\n const [, serializedRequest] = message.match(/^request:(.+)$/) || []\n if (!serializedRequest) {\n return\n }\n\n const requestJson = JSON.parse(\n serializedRequest,\n requestReviver\n ) as RevivedRequest\n logger.info('parsed intercepted request', requestJson)\n\n const capturedRequest = new Request(requestJson.url, {\n method: requestJson.method,\n headers: new Headers(requestJson.headers),\n credentials: requestJson.credentials,\n body: requestJson.body,\n })\n\n const { interactiveRequest, requestController } =\n toInteractiveRequest(capturedRequest)\n\n this.emitter.once('request', () => {\n if (requestController.responsePromise.state === 'pending') {\n requestController.respondWith(undefined)\n }\n })\n\n await emitAsync(this.emitter, 'request', {\n request: interactiveRequest,\n requestId: requestJson.id,\n })\n\n const mockedResponse = await requestController.responsePromise\n\n if (!mockedResponse) {\n return\n }\n\n logger.info('event.respondWith called with:', mockedResponse)\n const responseClone = mockedResponse.clone()\n const responseText = await mockedResponse.text()\n\n // Send the mocked response to the child process.\n const serializedResponse = JSON.stringify({\n status: mockedResponse.status,\n statusText: mockedResponse.statusText,\n headers: Array.from(mockedResponse.headers.entries()),\n body: responseText,\n } as SerializedResponse)\n\n this.process.send(\n `response:${requestJson.id}:${serializedResponse}`,\n (error) => {\n if (error) {\n return\n }\n\n // Emit an optimistic \"response\" event at this point,\n // not to rely on the back-and-forth signaling for the sake of the event.\n this.emitter.emit('response', {\n response: responseClone,\n isMockedResponse: true,\n request: capturedRequest,\n requestId: requestJson.id,\n })\n }\n )\n\n logger.info(\n 'sent serialized mocked response to the parent:',\n serializedResponse\n )\n }\n\n this.subscriptions.push(() => {\n this.process.removeListener('message', handleChildMessage)\n logger.info('removed the \"message\" listener from the child process!')\n })\n\n logger.info('adding a \"message\" listener to the child process')\n this.process.addListener('message', handleChildMessage)\n\n this.process.once('error', () => this.dispose())\n this.process.once('exit', () => this.dispose())\n }\n}\n"],"mappings":"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","names":[]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/chunk-6FRASLM3.mjs b/node_modules/@mswjs/interceptors/lib/node/chunk-6FRASLM3.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5462740fd0853f85360679c62074d2518b060e18 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/chunk-6FRASLM3.mjs @@ -0,0 +1,51 @@ +import { + Interceptor +} from "./chunk-Q7POAM5N.mjs"; + +// src/BatchInterceptor.ts +var BatchInterceptor = class extends Interceptor { + constructor(options) { + BatchInterceptor.symbol = Symbol(options.name); + super(BatchInterceptor.symbol); + this.interceptors = options.interceptors; + } + setup() { + const logger = this.logger.extend("setup"); + logger.info("applying all %d interceptors...", this.interceptors.length); + for (const interceptor of this.interceptors) { + logger.info('applying "%s" interceptor...', interceptor.constructor.name); + interceptor.apply(); + logger.info("adding interceptor dispose subscription"); + this.subscriptions.push(() => interceptor.dispose()); + } + } + on(event, listener) { + for (const interceptor of this.interceptors) { + interceptor.on(event, listener); + } + return this; + } + once(event, listener) { + for (const interceptor of this.interceptors) { + interceptor.once(event, listener); + } + return this; + } + off(event, listener) { + for (const interceptor of this.interceptors) { + interceptor.off(event, listener); + } + return this; + } + removeAllListeners(event) { + for (const interceptors of this.interceptors) { + interceptors.removeAllListeners(event); + } + return this; + } +}; + +export { + BatchInterceptor +}; +//# sourceMappingURL=chunk-6FRASLM3.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/chunk-6FRASLM3.mjs.map b/node_modules/@mswjs/interceptors/lib/node/chunk-6FRASLM3.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..9569e4edae42e44acab6716f4c0a4ba4a8933c3a --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/chunk-6FRASLM3.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/BatchInterceptor.ts"],"sourcesContent":["import { EventMap, Listener } from 'strict-event-emitter'\nimport { Interceptor, ExtractEventNames } from './Interceptor'\n\nexport interface BatchInterceptorOptions<\n InterceptorList extends ReadonlyArray>\n> {\n name: string\n interceptors: InterceptorList\n}\n\nexport type ExtractEventMapType<\n InterceptorList extends ReadonlyArray>\n> = InterceptorList extends ReadonlyArray\n ? InterceptorType extends Interceptor\n ? EventMap\n : never\n : never\n\n/**\n * A batch interceptor that exposes a single interface\n * to apply and operate with multiple interceptors at once.\n */\nexport class BatchInterceptor<\n InterceptorList extends ReadonlyArray>,\n Events extends EventMap = ExtractEventMapType\n> extends Interceptor {\n static symbol: symbol\n\n private interceptors: InterceptorList\n\n constructor(options: BatchInterceptorOptions) {\n BatchInterceptor.symbol = Symbol(options.name)\n super(BatchInterceptor.symbol)\n this.interceptors = options.interceptors\n }\n\n protected setup() {\n const logger = this.logger.extend('setup')\n\n logger.info('applying all %d interceptors...', this.interceptors.length)\n\n for (const interceptor of this.interceptors) {\n logger.info('applying \"%s\" interceptor...', interceptor.constructor.name)\n interceptor.apply()\n\n logger.info('adding interceptor dispose subscription')\n this.subscriptions.push(() => interceptor.dispose())\n }\n }\n\n public on>(\n event: EventName,\n listener: Listener\n ): this {\n // Instead of adding a listener to the batch interceptor,\n // propagate the listener to each of the individual interceptors.\n for (const interceptor of this.interceptors) {\n interceptor.on(event, listener)\n }\n\n return this\n }\n\n public once>(\n event: EventName,\n listener: Listener\n ): this {\n for (const interceptor of this.interceptors) {\n interceptor.once(event, listener)\n }\n\n return this\n }\n\n public off>(\n event: EventName,\n listener: Listener\n ): this {\n for (const interceptor of this.interceptors) {\n interceptor.off(event, listener)\n }\n\n return this\n }\n\n public removeAllListeners>(\n event?: EventName | undefined\n ): this {\n for (const interceptors of this.interceptors) {\n interceptors.removeAllListeners(event)\n }\n\n return this\n }\n}\n"],"mappings":";;;;;AAsBO,IAAM,mBAAN,cAGG,YAAoB;AAAA,EAK5B,YAAY,SAAmD;AAC7D,qBAAiB,SAAS,OAAO,QAAQ,IAAI;AAC7C,UAAM,iBAAiB,MAAM;AAC7B,SAAK,eAAe,QAAQ;AAAA,EAC9B;AAAA,EAEU,QAAQ;AAChB,UAAM,SAAS,KAAK,OAAO,OAAO,OAAO;AAEzC,WAAO,KAAK,mCAAmC,KAAK,aAAa,MAAM;AAEvE,eAAW,eAAe,KAAK,cAAc;AAC3C,aAAO,KAAK,gCAAgC,YAAY,YAAY,IAAI;AACxE,kBAAY,MAAM;AAElB,aAAO,KAAK,yCAAyC;AACrD,WAAK,cAAc,KAAK,MAAM,YAAY,QAAQ,CAAC;AAAA,IACrD;AAAA,EACF;AAAA,EAEO,GACL,OACA,UACM;AAGN,eAAW,eAAe,KAAK,cAAc;AAC3C,kBAAY,GAAG,OAAO,QAAQ;AAAA,IAChC;AAEA,WAAO;AAAA,EACT;AAAA,EAEO,KACL,OACA,UACM;AACN,eAAW,eAAe,KAAK,cAAc;AAC3C,kBAAY,KAAK,OAAO,QAAQ;AAAA,IAClC;AAEA,WAAO;AAAA,EACT;AAAA,EAEO,IACL,OACA,UACM;AACN,eAAW,eAAe,KAAK,cAAc;AAC3C,kBAAY,IAAI,OAAO,QAAQ;AAAA,IACjC;AAEA,WAAO;AAAA,EACT;AAAA,EAEO,mBACL,OACM;AACN,eAAW,gBAAgB,KAAK,cAAc;AAC5C,mBAAa,mBAAmB,KAAK;AAAA,IACvC;AAEA,WAAO;AAAA,EACT;AACF;","names":[]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/chunk-6HYIRFX2.mjs b/node_modules/@mswjs/interceptors/lib/node/chunk-6HYIRFX2.mjs new file mode 100644 index 0000000000000000000000000000000000000000..05b6c33cb2dec03c23115c9c1de440c0a0a10277 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/chunk-6HYIRFX2.mjs @@ -0,0 +1,22 @@ +// src/utils/bufferUtils.ts +var encoder = new TextEncoder(); +function encodeBuffer(text) { + return encoder.encode(text); +} +function decodeBuffer(buffer, encoding) { + const decoder = new TextDecoder(encoding); + return decoder.decode(buffer); +} +function toArrayBuffer(array) { + return array.buffer.slice( + array.byteOffset, + array.byteOffset + array.byteLength + ); +} + +export { + encodeBuffer, + decodeBuffer, + toArrayBuffer +}; +//# sourceMappingURL=chunk-6HYIRFX2.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/chunk-6HYIRFX2.mjs.map b/node_modules/@mswjs/interceptors/lib/node/chunk-6HYIRFX2.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..6f27915c41e396fe4b28381b580d8fc7fdffbb3b --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/chunk-6HYIRFX2.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/utils/bufferUtils.ts"],"sourcesContent":["const encoder = new TextEncoder()\n\nexport function encodeBuffer(text: string): Uint8Array {\n return encoder.encode(text)\n}\n\nexport function decodeBuffer(buffer: ArrayBuffer, encoding?: string): string {\n const decoder = new TextDecoder(encoding)\n return decoder.decode(buffer)\n}\n\n/**\n * Create an `ArrayBuffer` from the given `Uint8Array`.\n * Takes the byte offset into account to produce the right buffer\n * in the case when the buffer is bigger than the data view.\n */\nexport function toArrayBuffer(array: Uint8Array): ArrayBuffer {\n return array.buffer.slice(\n array.byteOffset,\n array.byteOffset + array.byteLength\n )\n}\n"],"mappings":";AAAA,IAAM,UAAU,IAAI,YAAY;AAEzB,SAAS,aAAa,MAA0B;AACrD,SAAO,QAAQ,OAAO,IAAI;AAC5B;AAEO,SAAS,aAAa,QAAqB,UAA2B;AAC3E,QAAM,UAAU,IAAI,YAAY,QAAQ;AACxC,SAAO,QAAQ,OAAO,MAAM;AAC9B;AAOO,SAAS,cAAc,OAAgC;AAC5D,SAAO,MAAM,OAAO;AAAA,IAClB,MAAM;AAAA,IACN,MAAM,aAAa,MAAM;AAAA,EAC3B;AACF;","names":[]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/chunk-APT7KA3B.js b/node_modules/@mswjs/interceptors/lib/node/chunk-APT7KA3B.js new file mode 100644 index 0000000000000000000000000000000000000000..a1c5800590ab6a3360ba2f467bd71189deae22e3 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/chunk-APT7KA3B.js @@ -0,0 +1,820 @@ +"use strict";Object.defineProperty(exports, "__esModule", {value: true}); + + + +var _chunkLK6DILFKjs = require('./chunk-LK6DILFK.js'); + + +var _chunkEIBTX65Ojs = require('./chunk-EIBTX65O.js'); + + + +var _chunkMQJ3JOOKjs = require('./chunk-MQJ3JOOK.js'); + + + + + + + +var _chunkE4AC7YACjs = require('./chunk-E4AC7YAC.js'); + +// src/interceptors/XMLHttpRequest/index.ts +var _outvariant = require('outvariant'); + +// src/interceptors/XMLHttpRequest/XMLHttpRequestProxy.ts +var _until = require('@open-draft/until'); + +// src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts + +var _isnodeprocess = require('is-node-process'); + +// src/interceptors/XMLHttpRequest/utils/concatArrayBuffer.ts +function concatArrayBuffer(left, right) { + const result = new Uint8Array(left.byteLength + right.byteLength); + result.set(left, 0); + result.set(right, left.byteLength); + return result; +} + +// src/interceptors/XMLHttpRequest/polyfills/EventPolyfill.ts +var EventPolyfill = class { + constructor(type, options) { + this.AT_TARGET = 0; + this.BUBBLING_PHASE = 0; + this.CAPTURING_PHASE = 0; + this.NONE = 0; + this.type = ""; + this.srcElement = null; + this.currentTarget = null; + this.eventPhase = 0; + this.isTrusted = true; + this.composed = false; + this.cancelable = true; + this.defaultPrevented = false; + this.bubbles = true; + this.lengthComputable = true; + this.loaded = 0; + this.total = 0; + this.cancelBubble = false; + this.returnValue = true; + this.type = type; + this.target = (options == null ? void 0 : options.target) || null; + this.currentTarget = (options == null ? void 0 : options.currentTarget) || null; + this.timeStamp = Date.now(); + } + composedPath() { + return []; + } + initEvent(type, bubbles, cancelable) { + this.type = type; + this.bubbles = !!bubbles; + this.cancelable = !!cancelable; + } + preventDefault() { + this.defaultPrevented = true; + } + stopPropagation() { + } + stopImmediatePropagation() { + } +}; + +// src/interceptors/XMLHttpRequest/polyfills/ProgressEventPolyfill.ts +var ProgressEventPolyfill = class extends EventPolyfill { + constructor(type, init) { + super(type); + this.lengthComputable = (init == null ? void 0 : init.lengthComputable) || false; + this.composed = (init == null ? void 0 : init.composed) || false; + this.loaded = (init == null ? void 0 : init.loaded) || 0; + this.total = (init == null ? void 0 : init.total) || 0; + } +}; + +// src/interceptors/XMLHttpRequest/utils/createEvent.ts +var SUPPORTS_PROGRESS_EVENT = typeof ProgressEvent !== "undefined"; +function createEvent(target, type, init) { + const progressEvents = [ + "error", + "progress", + "loadstart", + "loadend", + "load", + "timeout", + "abort" + ]; + const ProgressEventClass = SUPPORTS_PROGRESS_EVENT ? ProgressEvent : ProgressEventPolyfill; + const event = progressEvents.includes(type) ? new ProgressEventClass(type, { + lengthComputable: true, + loaded: (init == null ? void 0 : init.loaded) || 0, + total: (init == null ? void 0 : init.total) || 0 + }) : new EventPolyfill(type, { + target, + currentTarget: target + }); + return event; +} + +// src/utils/findPropertySource.ts +function findPropertySource(target, propertyName) { + if (!(propertyName in target)) { + return null; + } + const hasProperty = Object.prototype.hasOwnProperty.call(target, propertyName); + if (hasProperty) { + return target; + } + const prototype = Reflect.getPrototypeOf(target); + return prototype ? findPropertySource(prototype, propertyName) : null; +} + +// src/utils/createProxy.ts +function createProxy(target, options) { + const proxy = new Proxy(target, optionsToProxyHandler(options)); + return proxy; +} +function optionsToProxyHandler(options) { + const { constructorCall, methodCall, getProperty, setProperty } = options; + const handler = {}; + if (typeof constructorCall !== "undefined") { + handler.construct = function(target, args, newTarget) { + const next = Reflect.construct.bind(null, target, args, newTarget); + return constructorCall.call(newTarget, args, next); + }; + } + handler.set = function(target, propertyName, nextValue) { + const next = () => { + const propertySource = findPropertySource(target, propertyName) || target; + const ownDescriptors = Reflect.getOwnPropertyDescriptor( + propertySource, + propertyName + ); + if (typeof (ownDescriptors == null ? void 0 : ownDescriptors.set) !== "undefined") { + ownDescriptors.set.apply(target, [nextValue]); + return true; + } + return Reflect.defineProperty(propertySource, propertyName, { + writable: true, + enumerable: true, + configurable: true, + value: nextValue + }); + }; + if (typeof setProperty !== "undefined") { + return setProperty.call(target, [propertyName, nextValue], next); + } + return next(); + }; + handler.get = function(target, propertyName, receiver) { + const next = () => target[propertyName]; + const value = typeof getProperty !== "undefined" ? getProperty.call(target, [propertyName, receiver], next) : next(); + if (typeof value === "function") { + return (...args) => { + const next2 = value.bind(target, ...args); + if (typeof methodCall !== "undefined") { + return methodCall.call(target, [propertyName, args], next2); + } + return next2(); + }; + } + return value; + }; + return handler; +} + +// src/interceptors/XMLHttpRequest/utils/isDomParserSupportedType.ts +function isDomParserSupportedType(type) { + const supportedTypes = [ + "application/xhtml+xml", + "application/xml", + "image/svg+xml", + "text/html", + "text/xml" + ]; + return supportedTypes.some((supportedType) => { + return type.startsWith(supportedType); + }); +} + +// src/utils/parseJson.ts +function parseJson(data) { + try { + const json = JSON.parse(data); + return json; + } catch (_) { + return null; + } +} + +// src/interceptors/XMLHttpRequest/utils/createResponse.ts +function createResponse(request, body) { + const responseBodyOrNull = _chunkE4AC7YACjs.isResponseWithoutBody.call(void 0, request.status) ? null : body; + return new Response(responseBodyOrNull, { + status: request.status, + statusText: request.statusText, + headers: createHeadersFromXMLHttpReqestHeaders( + request.getAllResponseHeaders() + ) + }); +} +function createHeadersFromXMLHttpReqestHeaders(headersString) { + const headers = new Headers(); + const lines = headersString.split(/[\r\n]+/); + for (const line of lines) { + if (line.trim() === "") { + continue; + } + const [name, ...parts] = line.split(": "); + const value = parts.join(": "); + headers.append(name, value); + } + return headers; +} + +// src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts +var IS_MOCKED_RESPONSE = Symbol("isMockedResponse"); +var IS_NODE = _isnodeprocess.isNodeProcess.call(void 0, ); +var XMLHttpRequestController = class { + constructor(initialRequest, logger) { + this.initialRequest = initialRequest; + this.logger = logger; + this.method = "GET"; + this.url = null; + this.events = /* @__PURE__ */ new Map(); + this.requestId = _chunkE4AC7YACjs.createRequestId.call(void 0, ); + this.requestHeaders = new Headers(); + this.responseBuffer = new Uint8Array(); + this.request = createProxy(initialRequest, { + setProperty: ([propertyName, nextValue], invoke) => { + switch (propertyName) { + case "ontimeout": { + const eventName = propertyName.slice( + 2 + ); + this.request.addEventListener(eventName, nextValue); + return invoke(); + } + default: { + return invoke(); + } + } + }, + methodCall: ([methodName, args], invoke) => { + var _a; + switch (methodName) { + case "open": { + const [method, url] = args; + if (typeof url === "undefined") { + this.method = "GET"; + this.url = toAbsoluteUrl(method); + } else { + this.method = method; + this.url = toAbsoluteUrl(url); + } + this.logger = this.logger.extend(`${this.method} ${this.url.href}`); + this.logger.info("open", this.method, this.url.href); + return invoke(); + } + case "addEventListener": { + const [eventName, listener] = args; + this.registerEvent(eventName, listener); + this.logger.info("addEventListener", eventName, listener); + return invoke(); + } + case "setRequestHeader": { + const [name, value] = args; + this.requestHeaders.set(name, value); + this.logger.info("setRequestHeader", name, value); + return invoke(); + } + case "send": { + const [body] = args; + if (body != null) { + this.requestBody = typeof body === "string" ? _chunkLK6DILFKjs.encodeBuffer.call(void 0, body) : body; + } + this.request.addEventListener("load", () => { + if (typeof this.onResponse !== "undefined") { + const fetchResponse = createResponse( + this.request, + /** + * The `response` property is the right way to read + * the ambiguous response body, as the request's "responseType" may differ. + * @see https://xhr.spec.whatwg.org/#the-response-attribute + */ + this.request.response + ); + this.onResponse.call(this, { + response: fetchResponse, + isMockedResponse: IS_MOCKED_RESPONSE in this.request, + request: fetchRequest, + requestId: this.requestId + }); + } + }); + const fetchRequest = this.toFetchApiRequest(); + const onceRequestSettled = ((_a = this.onRequest) == null ? void 0 : _a.call(this, { + request: fetchRequest, + requestId: this.requestId + })) || Promise.resolve(); + onceRequestSettled.finally(() => { + if (this.request.readyState < this.request.LOADING) { + this.logger.info( + "request callback settled but request has not been handled (readystate %d), performing as-is...", + this.request.readyState + ); + if (IS_NODE) { + this.request.setRequestHeader( + _chunkE4AC7YACjs.INTERNAL_REQUEST_ID_HEADER_NAME, + this.requestId + ); + } + return invoke(); + } + }); + break; + } + default: { + return invoke(); + } + } + } + }); + } + registerEvent(eventName, listener) { + const prevEvents = this.events.get(eventName) || []; + const nextEvents = prevEvents.concat(listener); + this.events.set(eventName, nextEvents); + this.logger.info('registered event "%s"', eventName, listener); + } + /** + * Responds to the current request with the given + * Fetch API `Response` instance. + */ + respondWith(response) { + this.logger.info( + "responding with a mocked response: %d %s", + response.status, + response.statusText + ); + define(this.request, IS_MOCKED_RESPONSE, true); + define(this.request, "status", response.status); + define(this.request, "statusText", response.statusText); + define(this.request, "responseURL", this.url.href); + this.request.getResponseHeader = new Proxy(this.request.getResponseHeader, { + apply: (_, __, args) => { + this.logger.info("getResponseHeader", args[0]); + if (this.request.readyState < this.request.HEADERS_RECEIVED) { + this.logger.info("headers not received yet, returning null"); + return null; + } + const headerValue = response.headers.get(args[0]); + this.logger.info( + 'resolved response header "%s" to', + args[0], + headerValue + ); + return headerValue; + } + }); + this.request.getAllResponseHeaders = new Proxy( + this.request.getAllResponseHeaders, + { + apply: () => { + this.logger.info("getAllResponseHeaders"); + if (this.request.readyState < this.request.HEADERS_RECEIVED) { + this.logger.info("headers not received yet, returning empty string"); + return ""; + } + const headersList = Array.from(response.headers.entries()); + const allHeaders = headersList.map(([headerName, headerValue]) => { + return `${headerName}: ${headerValue}`; + }).join("\r\n"); + this.logger.info("resolved all response headers to", allHeaders); + return allHeaders; + } + } + ); + Object.defineProperties(this.request, { + response: { + enumerable: true, + configurable: false, + get: () => this.response + }, + responseText: { + enumerable: true, + configurable: false, + get: () => this.responseText + }, + responseXML: { + enumerable: true, + configurable: false, + get: () => this.responseXML + } + }); + const totalResponseBodyLength = response.headers.has("Content-Length") ? Number(response.headers.get("Content-Length")) : ( + /** + * @todo Infer the response body length from the response body. + */ + void 0 + ); + this.logger.info("calculated response body length", totalResponseBodyLength); + this.trigger("loadstart", { + loaded: 0, + total: totalResponseBodyLength + }); + this.setReadyState(this.request.HEADERS_RECEIVED); + this.setReadyState(this.request.LOADING); + const finalizeResponse = () => { + this.logger.info("finalizing the mocked response..."); + this.setReadyState(this.request.DONE); + this.trigger("load", { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength + }); + this.trigger("loadend", { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength + }); + }; + if (response.body) { + this.logger.info("mocked response has body, streaming..."); + const reader = response.body.getReader(); + const readNextResponseBodyChunk = async () => { + const { value, done } = await reader.read(); + if (done) { + this.logger.info("response body stream done!"); + finalizeResponse(); + return; + } + if (value) { + this.logger.info("read response body chunk:", value); + this.responseBuffer = concatArrayBuffer(this.responseBuffer, value); + this.trigger("progress", { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength + }); + } + readNextResponseBodyChunk(); + }; + readNextResponseBodyChunk(); + } else { + finalizeResponse(); + } + } + responseBufferToText() { + return _chunkLK6DILFKjs.decodeBuffer.call(void 0, this.responseBuffer); + } + get response() { + this.logger.info( + "getResponse (responseType: %s)", + this.request.responseType + ); + if (this.request.readyState !== this.request.DONE) { + return null; + } + switch (this.request.responseType) { + case "json": { + const responseJson = parseJson(this.responseBufferToText()); + this.logger.info("resolved response JSON", responseJson); + return responseJson; + } + case "arraybuffer": { + const arrayBuffer = _chunkLK6DILFKjs.toArrayBuffer.call(void 0, this.responseBuffer); + this.logger.info("resolved response ArrayBuffer", arrayBuffer); + return arrayBuffer; + } + case "blob": { + const mimeType = this.request.getResponseHeader("Content-Type") || "text/plain"; + const responseBlob = new Blob([this.responseBufferToText()], { + type: mimeType + }); + this.logger.info( + "resolved response Blob (mime type: %s)", + responseBlob, + mimeType + ); + return responseBlob; + } + default: { + const responseText = this.responseBufferToText(); + this.logger.info( + 'resolving "%s" response type as text', + this.request.responseType, + responseText + ); + return responseText; + } + } + } + get responseText() { + _outvariant.invariant.call(void 0, + this.request.responseType === "" || this.request.responseType === "text", + "InvalidStateError: The object is in invalid state." + ); + if (this.request.readyState !== this.request.LOADING && this.request.readyState !== this.request.DONE) { + return ""; + } + const responseText = this.responseBufferToText(); + this.logger.info('getResponseText: "%s"', responseText); + return responseText; + } + get responseXML() { + _outvariant.invariant.call(void 0, + this.request.responseType === "" || this.request.responseType === "document", + "InvalidStateError: The object is in invalid state." + ); + if (this.request.readyState !== this.request.DONE) { + return null; + } + const contentType = this.request.getResponseHeader("Content-Type") || ""; + if (typeof DOMParser === "undefined") { + console.warn( + "Cannot retrieve XMLHttpRequest response body as XML: DOMParser is not defined. You are likely using an environment that is not browser or does not polyfill browser globals correctly." + ); + return null; + } + if (isDomParserSupportedType(contentType)) { + return new DOMParser().parseFromString( + this.responseBufferToText(), + contentType + ); + } + return null; + } + errorWith(error) { + this.logger.info("responding with an error"); + this.setReadyState(this.request.DONE); + this.trigger("error"); + this.trigger("loadend"); + } + /** + * Transitions this request's `readyState` to the given one. + */ + setReadyState(nextReadyState) { + this.logger.info( + "setReadyState: %d -> %d", + this.request.readyState, + nextReadyState + ); + if (this.request.readyState === nextReadyState) { + this.logger.info("ready state identical, skipping transition..."); + return; + } + define(this.request, "readyState", nextReadyState); + this.logger.info("set readyState to: %d", nextReadyState); + if (nextReadyState !== this.request.UNSENT) { + this.logger.info('triggerring "readystatechange" event...'); + this.trigger("readystatechange"); + } + } + /** + * Triggers given event on the `XMLHttpRequest` instance. + */ + trigger(eventName, options) { + const callback = this.request[`on${eventName}`]; + const event = createEvent(this.request, eventName, options); + this.logger.info('trigger "%s"', eventName, options || ""); + if (typeof callback === "function") { + this.logger.info('found a direct "%s" callback, calling...', eventName); + callback.call(this.request, event); + } + for (const [registeredEventName, listeners] of this.events) { + if (registeredEventName === eventName) { + this.logger.info( + 'found %d listener(s) for "%s" event, calling...', + listeners.length, + eventName + ); + listeners.forEach((listener) => listener.call(this.request, event)); + } + } + } + /** + * Converts this `XMLHttpRequest` instance into a Fetch API `Request` instance. + */ + toFetchApiRequest() { + this.logger.info("converting request to a Fetch API Request..."); + const fetchRequest = new Request(this.url.href, { + method: this.method, + headers: this.requestHeaders, + /** + * @see https://xhr.spec.whatwg.org/#cross-origin-credentials + */ + credentials: this.request.withCredentials ? "include" : "same-origin", + body: ["GET", "HEAD"].includes(this.method) ? null : this.requestBody + }); + const proxyHeaders = createProxy(fetchRequest.headers, { + methodCall: ([methodName, args], invoke) => { + switch (methodName) { + case "append": + case "set": { + const [headerName, headerValue] = args; + this.request.setRequestHeader(headerName, headerValue); + break; + } + case "delete": { + const [headerName] = args; + console.warn( + `XMLHttpRequest: Cannot remove a "${headerName}" header from the Fetch API representation of the "${fetchRequest.method} ${fetchRequest.url}" request. XMLHttpRequest headers cannot be removed.` + ); + break; + } + } + return invoke(); + } + }); + define(fetchRequest, "headers", proxyHeaders); + this.logger.info("converted request to a Fetch API Request!", fetchRequest); + return fetchRequest; + } +}; +function toAbsoluteUrl(url) { + if (typeof location === "undefined") { + return new URL(url); + } + return new URL(url.toString(), location.href); +} +function define(target, property, value) { + Reflect.defineProperty(target, property, { + // Ensure writable properties to allow redefining readonly properties. + writable: true, + enumerable: true, + value + }); +} + +// src/interceptors/XMLHttpRequest/XMLHttpRequestProxy.ts +function createXMLHttpRequestProxy({ + emitter, + logger +}) { + const XMLHttpRequestProxy = new Proxy(globalThis.XMLHttpRequest, { + construct(target, args, newTarget) { + logger.info("constructed new XMLHttpRequest"); + const originalRequest = Reflect.construct( + target, + args, + newTarget + ); + const prototypeDescriptors = Object.getOwnPropertyDescriptors( + target.prototype + ); + for (const propertyName in prototypeDescriptors) { + Reflect.defineProperty( + originalRequest, + propertyName, + prototypeDescriptors[propertyName] + ); + } + const xhrRequestController = new XMLHttpRequestController( + originalRequest, + logger + ); + xhrRequestController.onRequest = async function({ request, requestId }) { + const { interactiveRequest, requestController } = _chunkMQJ3JOOKjs.toInteractiveRequest.call(void 0, request); + this.logger.info("awaiting mocked response..."); + emitter.once("request", ({ requestId: pendingRequestId }) => { + if (pendingRequestId !== requestId) { + return; + } + if (requestController.responsePromise.state === "pending") { + requestController.respondWith(void 0); + } + }); + const resolverResult = await _until.until.call(void 0, async () => { + this.logger.info( + 'emitting the "request" event for %s listener(s)...', + emitter.listenerCount("request") + ); + await _chunkMQJ3JOOKjs.emitAsync.call(void 0, emitter, "request", { + request: interactiveRequest, + requestId + }); + this.logger.info('all "request" listeners settled!'); + const mockedResponse2 = await requestController.responsePromise; + this.logger.info("event.respondWith called with:", mockedResponse2); + return mockedResponse2; + }); + if (resolverResult.error) { + this.logger.info( + "request listener threw an exception, aborting request...", + resolverResult.error + ); + if (resolverResult.error instanceof Response) { + if (_chunkE4AC7YACjs.isResponseError.call(void 0, resolverResult.error)) { + xhrRequestController.errorWith(new TypeError("Network error")); + } else { + this.respondWith(resolverResult.error); + } + return; + } + if (emitter.listenerCount("unhandledException") > 0) { + await _chunkMQJ3JOOKjs.emitAsync.call(void 0, emitter, "unhandledException", { + error: resolverResult.error, + request, + requestId, + controller: { + respondWith: xhrRequestController.respondWith.bind(xhrRequestController), + errorWith: xhrRequestController.errorWith.bind(xhrRequestController) + } + }); + if (originalRequest.readyState > XMLHttpRequest.OPENED) { + return; + } + } + xhrRequestController.respondWith( + _chunkE4AC7YACjs.createServerErrorResponse.call(void 0, resolverResult.error) + ); + return; + } + const mockedResponse = resolverResult.data; + if (typeof mockedResponse !== "undefined") { + this.logger.info( + "received mocked response: %d %s", + mockedResponse.status, + mockedResponse.statusText + ); + if (_chunkE4AC7YACjs.isResponseError.call(void 0, mockedResponse)) { + this.logger.info( + "received a network error response, rejecting the request promise..." + ); + xhrRequestController.errorWith(new TypeError("Network error")); + return; + } + return xhrRequestController.respondWith(mockedResponse); + } + this.logger.info( + "no mocked response received, performing request as-is..." + ); + }; + xhrRequestController.onResponse = async function({ + response, + isMockedResponse, + request, + requestId + }) { + this.logger.info( + 'emitting the "response" event for %s listener(s)...', + emitter.listenerCount("response") + ); + emitter.emit("response", { + response, + isMockedResponse, + request, + requestId + }); + }; + return xhrRequestController.request; + } + }); + return XMLHttpRequestProxy; +} + +// src/interceptors/XMLHttpRequest/index.ts +var _XMLHttpRequestInterceptor = class extends _chunkE4AC7YACjs.Interceptor { + constructor() { + super(_XMLHttpRequestInterceptor.interceptorSymbol); + } + checkEnvironment() { + return typeof globalThis.XMLHttpRequest !== "undefined"; + } + setup() { + const logger = this.logger.extend("setup"); + logger.info('patching "XMLHttpRequest" module...'); + const PureXMLHttpRequest = globalThis.XMLHttpRequest; + _outvariant.invariant.call(void 0, + !PureXMLHttpRequest[_chunkEIBTX65Ojs.IS_PATCHED_MODULE], + 'Failed to patch the "XMLHttpRequest" module: already patched.' + ); + globalThis.XMLHttpRequest = createXMLHttpRequestProxy({ + emitter: this.emitter, + logger: this.logger + }); + logger.info( + 'native "XMLHttpRequest" module patched!', + globalThis.XMLHttpRequest.name + ); + Object.defineProperty(globalThis.XMLHttpRequest, _chunkEIBTX65Ojs.IS_PATCHED_MODULE, { + enumerable: true, + configurable: true, + value: true + }); + this.subscriptions.push(() => { + Object.defineProperty(globalThis.XMLHttpRequest, _chunkEIBTX65Ojs.IS_PATCHED_MODULE, { + value: void 0 + }); + globalThis.XMLHttpRequest = PureXMLHttpRequest; + logger.info( + 'native "XMLHttpRequest" module restored!', + globalThis.XMLHttpRequest.name + ); + }); + } +}; +var XMLHttpRequestInterceptor = _XMLHttpRequestInterceptor; +XMLHttpRequestInterceptor.interceptorSymbol = Symbol("xhr"); + + + +exports.XMLHttpRequestInterceptor = XMLHttpRequestInterceptor; +//# sourceMappingURL=chunk-APT7KA3B.js.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/chunk-APT7KA3B.js.map b/node_modules/@mswjs/interceptors/lib/node/chunk-APT7KA3B.js.map new file mode 100644 index 0000000000000000000000000000000000000000..0fcaaa0af08cc15102cf71985418d4fb53478044 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/chunk-APT7KA3B.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/interceptors/XMLHttpRequest/index.ts","../../src/interceptors/XMLHttpRequest/XMLHttpRequestProxy.ts","../../src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts","../../src/interceptors/XMLHttpRequest/utils/concatArrayBuffer.ts","../../src/interceptors/XMLHttpRequest/polyfills/EventPolyfill.ts","../../src/interceptors/XMLHttpRequest/polyfills/ProgressEventPolyfill.ts","../../src/interceptors/XMLHttpRequest/utils/createEvent.ts","../../src/utils/findPropertySource.ts","../../src/utils/createProxy.ts","../../src/interceptors/XMLHttpRequest/utils/isDomParserSupportedType.ts","../../src/utils/parseJson.ts","../../src/interceptors/XMLHttpRequest/utils/createResponse.ts"],"names":["invariant","next","mockedResponse"],"mappings":"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","sourcesContent":["import { invariant } from 'outvariant'\nimport { Emitter } from 'strict-event-emitter'\nimport { HttpRequestEventMap, IS_PATCHED_MODULE } from '../../glossary'\nimport { InteractiveRequest } from '../../utils/toInteractiveRequest'\nimport { Interceptor } from '../../Interceptor'\nimport { createXMLHttpRequestProxy } from './XMLHttpRequestProxy'\n\nexport type XMLHttpRequestEventListener = (args: {\n request: InteractiveRequest\n requestId: string\n}) => Promise | void\n\nexport type XMLHttpRequestEmitter = Emitter\n\nexport class XMLHttpRequestInterceptor extends Interceptor {\n static interceptorSymbol = Symbol('xhr')\n\n constructor() {\n super(XMLHttpRequestInterceptor.interceptorSymbol)\n }\n\n protected checkEnvironment() {\n return typeof globalThis.XMLHttpRequest !== 'undefined'\n }\n\n protected setup() {\n const logger = this.logger.extend('setup')\n\n logger.info('patching \"XMLHttpRequest\" module...')\n\n const PureXMLHttpRequest = globalThis.XMLHttpRequest\n\n invariant(\n !(PureXMLHttpRequest as any)[IS_PATCHED_MODULE],\n 'Failed to patch the \"XMLHttpRequest\" module: already patched.'\n )\n\n globalThis.XMLHttpRequest = createXMLHttpRequestProxy({\n emitter: this.emitter,\n logger: this.logger,\n })\n\n logger.info(\n 'native \"XMLHttpRequest\" module patched!',\n globalThis.XMLHttpRequest.name\n )\n\n Object.defineProperty(globalThis.XMLHttpRequest, IS_PATCHED_MODULE, {\n enumerable: true,\n configurable: true,\n value: true,\n })\n\n this.subscriptions.push(() => {\n Object.defineProperty(globalThis.XMLHttpRequest, IS_PATCHED_MODULE, {\n value: undefined,\n })\n\n globalThis.XMLHttpRequest = PureXMLHttpRequest\n logger.info(\n 'native \"XMLHttpRequest\" module restored!',\n globalThis.XMLHttpRequest.name\n )\n })\n }\n}\n","import { until } from '@open-draft/until'\nimport type { Logger } from '@open-draft/logger'\nimport { XMLHttpRequestEmitter } from '.'\nimport { toInteractiveRequest } from '../../utils/toInteractiveRequest'\nimport { emitAsync } from '../../utils/emitAsync'\nimport { XMLHttpRequestController } from './XMLHttpRequestController'\nimport {\n createServerErrorResponse,\n isResponseError,\n} from '../../utils/responseUtils'\n\nexport interface XMLHttpRequestProxyOptions {\n emitter: XMLHttpRequestEmitter\n logger: Logger\n}\n\n/**\n * Create a proxied `XMLHttpRequest` class.\n * The proxied class establishes spies on certain methods,\n * allowing us to intercept requests and respond to them.\n */\nexport function createXMLHttpRequestProxy({\n emitter,\n logger,\n}: XMLHttpRequestProxyOptions) {\n const XMLHttpRequestProxy = new Proxy(globalThis.XMLHttpRequest, {\n construct(target, args, newTarget) {\n logger.info('constructed new XMLHttpRequest')\n\n const originalRequest = Reflect.construct(\n target,\n args,\n newTarget\n ) as XMLHttpRequest\n\n /**\n * @note Forward prototype descriptors onto the proxied object.\n * XMLHttpRequest is implemented in JSDOM in a way that assigns\n * a bunch of descriptors, like \"set responseType()\" on the prototype.\n * With this propagation, we make sure that those descriptors trigger\n * when the user operates with the proxied request instance.\n */\n const prototypeDescriptors = Object.getOwnPropertyDescriptors(\n target.prototype\n )\n for (const propertyName in prototypeDescriptors) {\n Reflect.defineProperty(\n originalRequest,\n propertyName,\n prototypeDescriptors[propertyName]\n )\n }\n\n const xhrRequestController = new XMLHttpRequestController(\n originalRequest,\n logger\n )\n\n xhrRequestController.onRequest = async function ({ request, requestId }) {\n const { interactiveRequest, requestController } =\n toInteractiveRequest(request)\n\n this.logger.info('awaiting mocked response...')\n\n emitter.once('request', ({ requestId: pendingRequestId }) => {\n if (pendingRequestId !== requestId) {\n return\n }\n\n if (requestController.responsePromise.state === 'pending') {\n requestController.respondWith(undefined)\n }\n })\n\n const resolverResult = await until(async () => {\n this.logger.info(\n 'emitting the \"request\" event for %s listener(s)...',\n emitter.listenerCount('request')\n )\n\n await emitAsync(emitter, 'request', {\n request: interactiveRequest,\n requestId,\n })\n\n this.logger.info('all \"request\" listeners settled!')\n\n const mockedResponse = await requestController.responsePromise\n\n this.logger.info('event.respondWith called with:', mockedResponse)\n\n return mockedResponse\n })\n\n if (resolverResult.error) {\n this.logger.info(\n 'request listener threw an exception, aborting request...',\n resolverResult.error\n )\n\n // Treat thrown Responses as mocked responses.\n if (resolverResult.error instanceof Response) {\n if (isResponseError(resolverResult.error)) {\n xhrRequestController.errorWith(new TypeError('Network error'))\n } else {\n this.respondWith(resolverResult.error)\n }\n\n return\n }\n\n if (emitter.listenerCount('unhandledException') > 0) {\n // Emit the \"unhandledException\" event so the client can opt-out\n // from the default exception handling (producing 500 error responses).\n await emitAsync(emitter, 'unhandledException', {\n error: resolverResult.error,\n request,\n requestId,\n controller: {\n respondWith:\n xhrRequestController.respondWith.bind(xhrRequestController),\n errorWith:\n xhrRequestController.errorWith.bind(xhrRequestController),\n },\n })\n\n // If any of the \"unhandledException\" listeners handled the request,\n // do nothing. Note that mocked responses will dispatch\n // HEADERS_RECEIVED (2), then LOADING (3), and DONE (4) can take\n // time as the mocked response body finishes streaming.\n if (originalRequest.readyState > XMLHttpRequest.OPENED) {\n return\n }\n }\n\n // Unhandled exceptions in the request listeners are\n // synonymous to unhandled exceptions on the server.\n // Those are represented as 500 error responses.\n xhrRequestController.respondWith(\n createServerErrorResponse(resolverResult.error)\n )\n\n return\n }\n\n const mockedResponse = resolverResult.data\n\n if (typeof mockedResponse !== 'undefined') {\n this.logger.info(\n 'received mocked response: %d %s',\n mockedResponse.status,\n mockedResponse.statusText\n )\n\n if (isResponseError(mockedResponse)) {\n this.logger.info(\n 'received a network error response, rejecting the request promise...'\n )\n\n xhrRequestController.errorWith(new TypeError('Network error'))\n return\n }\n\n return xhrRequestController.respondWith(mockedResponse)\n }\n\n this.logger.info(\n 'no mocked response received, performing request as-is...'\n )\n }\n\n xhrRequestController.onResponse = async function ({\n response,\n isMockedResponse,\n request,\n requestId,\n }) {\n this.logger.info(\n 'emitting the \"response\" event for %s listener(s)...',\n emitter.listenerCount('response')\n )\n\n emitter.emit('response', {\n response,\n isMockedResponse,\n request,\n requestId,\n })\n }\n\n // Return the proxied request from the controller\n // so that the controller can react to the consumer's interactions\n // with this request (opening/sending/etc).\n return xhrRequestController.request\n },\n })\n\n return XMLHttpRequestProxy\n}\n","import { invariant } from 'outvariant'\nimport { isNodeProcess } from 'is-node-process'\nimport type { Logger } from '@open-draft/logger'\nimport { concatArrayBuffer } from './utils/concatArrayBuffer'\nimport { createEvent } from './utils/createEvent'\nimport {\n decodeBuffer,\n encodeBuffer,\n toArrayBuffer,\n} from '../../utils/bufferUtils'\nimport { createProxy } from '../../utils/createProxy'\nimport { isDomParserSupportedType } from './utils/isDomParserSupportedType'\nimport { parseJson } from '../../utils/parseJson'\nimport { createResponse } from './utils/createResponse'\nimport { INTERNAL_REQUEST_ID_HEADER_NAME } from '../../Interceptor'\nimport { createRequestId } from '../../createRequestId'\n\nconst IS_MOCKED_RESPONSE = Symbol('isMockedResponse')\nconst IS_NODE = isNodeProcess()\n\n/**\n * An `XMLHttpRequest` instance controller that allows us\n * to handle any given request instance (e.g. responding to it).\n */\nexport class XMLHttpRequestController {\n public request: XMLHttpRequest\n public requestId: string\n public onRequest?: (\n this: XMLHttpRequestController,\n args: {\n request: Request\n requestId: string\n }\n ) => Promise\n public onResponse?: (\n this: XMLHttpRequestController,\n args: {\n response: Response\n isMockedResponse: boolean\n request: Request\n requestId: string\n }\n ) => void\n\n private method: string = 'GET'\n private url: URL = null as any\n private requestHeaders: Headers\n private requestBody?: XMLHttpRequestBodyInit | Document | null\n private responseBuffer: Uint8Array\n private events: Map>\n\n constructor(readonly initialRequest: XMLHttpRequest, public logger: Logger) {\n this.events = new Map()\n this.requestId = createRequestId()\n this.requestHeaders = new Headers()\n this.responseBuffer = new Uint8Array()\n\n this.request = createProxy(initialRequest, {\n setProperty: ([propertyName, nextValue], invoke) => {\n switch (propertyName) {\n case 'ontimeout': {\n const eventName = propertyName.slice(\n 2\n ) as keyof XMLHttpRequestEventTargetEventMap\n\n /**\n * @note Proxy callbacks to event listeners because JSDOM has trouble\n * translating these properties to callbacks. It seemed to be operating\n * on events exclusively.\n */\n this.request.addEventListener(eventName, nextValue as any)\n\n return invoke()\n }\n\n default: {\n return invoke()\n }\n }\n },\n methodCall: ([methodName, args], invoke) => {\n switch (methodName) {\n case 'open': {\n const [method, url] = args as [string, string | undefined]\n\n if (typeof url === 'undefined') {\n this.method = 'GET'\n this.url = toAbsoluteUrl(method)\n } else {\n this.method = method\n this.url = toAbsoluteUrl(url)\n }\n\n this.logger = this.logger.extend(`${this.method} ${this.url.href}`)\n this.logger.info('open', this.method, this.url.href)\n\n return invoke()\n }\n\n case 'addEventListener': {\n const [eventName, listener] = args as [\n keyof XMLHttpRequestEventTargetEventMap,\n Function\n ]\n\n this.registerEvent(eventName, listener)\n this.logger.info('addEventListener', eventName, listener)\n\n return invoke()\n }\n\n case 'setRequestHeader': {\n const [name, value] = args as [string, string]\n this.requestHeaders.set(name, value)\n\n this.logger.info('setRequestHeader', name, value)\n\n return invoke()\n }\n\n case 'send': {\n const [body] = args as [\n body?: XMLHttpRequestBodyInit | Document | null\n ]\n\n if (body != null) {\n this.requestBody =\n typeof body === 'string' ? encodeBuffer(body) : body\n }\n\n this.request.addEventListener('load', () => {\n if (typeof this.onResponse !== 'undefined') {\n // Create a Fetch API Response representation of whichever\n // response this XMLHttpRequest received. Note those may\n // be either a mocked and the original response.\n const fetchResponse = createResponse(\n this.request,\n /**\n * The `response` property is the right way to read\n * the ambiguous response body, as the request's \"responseType\" may differ.\n * @see https://xhr.spec.whatwg.org/#the-response-attribute\n */\n this.request.response\n )\n\n // Notify the consumer about the response.\n this.onResponse.call(this, {\n response: fetchResponse,\n isMockedResponse: IS_MOCKED_RESPONSE in this.request,\n request: fetchRequest,\n requestId: this.requestId!,\n })\n }\n })\n\n // Delegate request handling to the consumer.\n const fetchRequest = this.toFetchApiRequest()\n const onceRequestSettled =\n this.onRequest?.call(this, {\n request: fetchRequest,\n requestId: this.requestId!,\n }) || Promise.resolve()\n\n onceRequestSettled.finally(() => {\n // If the consumer didn't handle the request perform it as-is.\n // Note that the request may not yet be DONE and may, in fact,\n // be LOADING while the \"respondWith\" method does its magic.\n if (this.request.readyState < this.request.LOADING) {\n this.logger.info(\n 'request callback settled but request has not been handled (readystate %d), performing as-is...',\n this.request.readyState\n )\n\n /**\n * @note Set the intercepted request ID on the original request in Node.js\n * so that if it triggers any other interceptors, they don't attempt\n * to process it once again.\n *\n * For instance, XMLHttpRequest is often implemented via \"http.ClientRequest\"\n * and we don't want for both XHR and ClientRequest interceptors to\n * handle the same request at the same time (e.g. emit the \"response\" event twice).\n */\n if (IS_NODE) {\n this.request.setRequestHeader(\n INTERNAL_REQUEST_ID_HEADER_NAME,\n this.requestId!\n )\n }\n\n return invoke()\n }\n })\n\n break\n }\n\n default: {\n return invoke()\n }\n }\n },\n })\n }\n\n private registerEvent(\n eventName: keyof XMLHttpRequestEventTargetEventMap,\n listener: Function\n ): void {\n const prevEvents = this.events.get(eventName) || []\n const nextEvents = prevEvents.concat(listener)\n this.events.set(eventName, nextEvents)\n\n this.logger.info('registered event \"%s\"', eventName, listener)\n }\n\n /**\n * Responds to the current request with the given\n * Fetch API `Response` instance.\n */\n public respondWith(response: Response): void {\n this.logger.info(\n 'responding with a mocked response: %d %s',\n response.status,\n response.statusText\n )\n\n /**\n * @note Since `XMLHttpRequestController` delegates the handling of the responses\n * to the \"load\" event listener that doesn't distinguish between the mocked and original\n * responses, mark the request that had a mocked response with a corresponding symbol.\n */\n define(this.request, IS_MOCKED_RESPONSE, true)\n\n define(this.request, 'status', response.status)\n define(this.request, 'statusText', response.statusText)\n define(this.request, 'responseURL', this.url.href)\n\n this.request.getResponseHeader = new Proxy(this.request.getResponseHeader, {\n apply: (_, __, args: [name: string]) => {\n this.logger.info('getResponseHeader', args[0])\n\n if (this.request.readyState < this.request.HEADERS_RECEIVED) {\n this.logger.info('headers not received yet, returning null')\n\n // Headers not received yet, nothing to return.\n return null\n }\n\n const headerValue = response.headers.get(args[0])\n this.logger.info(\n 'resolved response header \"%s\" to',\n args[0],\n headerValue\n )\n\n return headerValue\n },\n })\n\n this.request.getAllResponseHeaders = new Proxy(\n this.request.getAllResponseHeaders,\n {\n apply: () => {\n this.logger.info('getAllResponseHeaders')\n\n if (this.request.readyState < this.request.HEADERS_RECEIVED) {\n this.logger.info('headers not received yet, returning empty string')\n\n // Headers not received yet, nothing to return.\n return ''\n }\n\n const headersList = Array.from(response.headers.entries())\n const allHeaders = headersList\n .map(([headerName, headerValue]) => {\n return `${headerName}: ${headerValue}`\n })\n .join('\\r\\n')\n\n this.logger.info('resolved all response headers to', allHeaders)\n\n return allHeaders\n },\n }\n )\n\n // Update the response getters to resolve against the mocked response.\n Object.defineProperties(this.request, {\n response: {\n enumerable: true,\n configurable: false,\n get: () => this.response,\n },\n responseText: {\n enumerable: true,\n configurable: false,\n get: () => this.responseText,\n },\n responseXML: {\n enumerable: true,\n configurable: false,\n get: () => this.responseXML,\n },\n })\n\n const totalResponseBodyLength = response.headers.has('Content-Length')\n ? Number(response.headers.get('Content-Length'))\n : /**\n * @todo Infer the response body length from the response body.\n */\n undefined\n\n this.logger.info('calculated response body length', totalResponseBodyLength)\n\n this.trigger('loadstart', {\n loaded: 0,\n total: totalResponseBodyLength,\n })\n\n this.setReadyState(this.request.HEADERS_RECEIVED)\n this.setReadyState(this.request.LOADING)\n\n const finalizeResponse = () => {\n this.logger.info('finalizing the mocked response...')\n\n this.setReadyState(this.request.DONE)\n\n this.trigger('load', {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n\n this.trigger('loadend', {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n }\n\n if (response.body) {\n this.logger.info('mocked response has body, streaming...')\n\n const reader = response.body.getReader()\n\n const readNextResponseBodyChunk = async () => {\n const { value, done } = await reader.read()\n\n if (done) {\n this.logger.info('response body stream done!')\n finalizeResponse()\n return\n }\n\n if (value) {\n this.logger.info('read response body chunk:', value)\n this.responseBuffer = concatArrayBuffer(this.responseBuffer, value)\n\n this.trigger('progress', {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n }\n\n readNextResponseBodyChunk()\n }\n\n readNextResponseBodyChunk()\n } else {\n finalizeResponse()\n }\n }\n\n private responseBufferToText(): string {\n return decodeBuffer(this.responseBuffer)\n }\n\n get response(): unknown {\n this.logger.info(\n 'getResponse (responseType: %s)',\n this.request.responseType\n )\n\n if (this.request.readyState !== this.request.DONE) {\n return null\n }\n\n switch (this.request.responseType) {\n case 'json': {\n const responseJson = parseJson(this.responseBufferToText())\n this.logger.info('resolved response JSON', responseJson)\n\n return responseJson\n }\n\n case 'arraybuffer': {\n const arrayBuffer = toArrayBuffer(this.responseBuffer)\n this.logger.info('resolved response ArrayBuffer', arrayBuffer)\n\n return arrayBuffer\n }\n\n case 'blob': {\n const mimeType =\n this.request.getResponseHeader('Content-Type') || 'text/plain'\n const responseBlob = new Blob([this.responseBufferToText()], {\n type: mimeType,\n })\n\n this.logger.info(\n 'resolved response Blob (mime type: %s)',\n responseBlob,\n mimeType\n )\n\n return responseBlob\n }\n\n default: {\n const responseText = this.responseBufferToText()\n this.logger.info(\n 'resolving \"%s\" response type as text',\n this.request.responseType,\n responseText\n )\n\n return responseText\n }\n }\n }\n\n get responseText(): string {\n /**\n * Throw when trying to read the response body as text when the\n * \"responseType\" doesn't expect text. This just respects the spec better.\n * @see https://xhr.spec.whatwg.org/#the-responsetext-attribute\n */\n invariant(\n this.request.responseType === '' || this.request.responseType === 'text',\n 'InvalidStateError: The object is in invalid state.'\n )\n\n if (\n this.request.readyState !== this.request.LOADING &&\n this.request.readyState !== this.request.DONE\n ) {\n return ''\n }\n\n const responseText = this.responseBufferToText()\n this.logger.info('getResponseText: \"%s\"', responseText)\n\n return responseText\n }\n\n get responseXML(): Document | null {\n invariant(\n this.request.responseType === '' ||\n this.request.responseType === 'document',\n 'InvalidStateError: The object is in invalid state.'\n )\n\n if (this.request.readyState !== this.request.DONE) {\n return null\n }\n\n const contentType = this.request.getResponseHeader('Content-Type') || ''\n\n if (typeof DOMParser === 'undefined') {\n console.warn(\n 'Cannot retrieve XMLHttpRequest response body as XML: DOMParser is not defined. You are likely using an environment that is not browser or does not polyfill browser globals correctly.'\n )\n return null\n }\n\n if (isDomParserSupportedType(contentType)) {\n return new DOMParser().parseFromString(\n this.responseBufferToText(),\n contentType\n )\n }\n\n return null\n }\n\n public errorWith(error: Error): void {\n this.logger.info('responding with an error')\n\n this.setReadyState(this.request.DONE)\n this.trigger('error')\n this.trigger('loadend')\n }\n\n /**\n * Transitions this request's `readyState` to the given one.\n */\n private setReadyState(nextReadyState: number): void {\n this.logger.info(\n 'setReadyState: %d -> %d',\n this.request.readyState,\n nextReadyState\n )\n\n if (this.request.readyState === nextReadyState) {\n this.logger.info('ready state identical, skipping transition...')\n return\n }\n\n define(this.request, 'readyState', nextReadyState)\n\n this.logger.info('set readyState to: %d', nextReadyState)\n\n if (nextReadyState !== this.request.UNSENT) {\n this.logger.info('triggerring \"readystatechange\" event...')\n\n this.trigger('readystatechange')\n }\n }\n\n /**\n * Triggers given event on the `XMLHttpRequest` instance.\n */\n private trigger<\n EventName extends keyof (XMLHttpRequestEventTargetEventMap & {\n readystatechange: ProgressEvent\n })\n >(eventName: EventName, options?: ProgressEventInit): void {\n const callback = this.request[`on${eventName}`]\n const event = createEvent(this.request, eventName, options)\n\n this.logger.info('trigger \"%s\"', eventName, options || '')\n\n // Invoke direct callbacks.\n if (typeof callback === 'function') {\n this.logger.info('found a direct \"%s\" callback, calling...', eventName)\n callback.call(this.request, event)\n }\n\n // Invoke event listeners.\n for (const [registeredEventName, listeners] of this.events) {\n if (registeredEventName === eventName) {\n this.logger.info(\n 'found %d listener(s) for \"%s\" event, calling...',\n listeners.length,\n eventName\n )\n\n listeners.forEach((listener) => listener.call(this.request, event))\n }\n }\n }\n\n /**\n * Converts this `XMLHttpRequest` instance into a Fetch API `Request` instance.\n */\n public toFetchApiRequest(): Request {\n this.logger.info('converting request to a Fetch API Request...')\n\n const fetchRequest = new Request(this.url.href, {\n method: this.method,\n headers: this.requestHeaders,\n /**\n * @see https://xhr.spec.whatwg.org/#cross-origin-credentials\n */\n credentials: this.request.withCredentials ? 'include' : 'same-origin',\n body: ['GET', 'HEAD'].includes(this.method)\n ? null\n : (this.requestBody as BodyInit),\n })\n\n const proxyHeaders = createProxy(fetchRequest.headers, {\n methodCall: ([methodName, args], invoke) => {\n // Forward the latest state of the internal request headers\n // because the interceptor might have modified them\n // without responding to the request.\n switch (methodName) {\n case 'append':\n case 'set': {\n const [headerName, headerValue] = args as [string, string]\n this.request.setRequestHeader(headerName, headerValue)\n break\n }\n\n case 'delete': {\n const [headerName] = args as [string]\n console.warn(\n `XMLHttpRequest: Cannot remove a \"${headerName}\" header from the Fetch API representation of the \"${fetchRequest.method} ${fetchRequest.url}\" request. XMLHttpRequest headers cannot be removed.`\n )\n break\n }\n }\n\n return invoke()\n },\n })\n define(fetchRequest, 'headers', proxyHeaders)\n\n this.logger.info('converted request to a Fetch API Request!', fetchRequest)\n\n return fetchRequest\n }\n}\n\nfunction toAbsoluteUrl(url: string | URL): URL {\n /**\n * @note XMLHttpRequest interceptor may run in environments\n * that implement XMLHttpRequest but don't implement \"location\"\n * (for example, React Native). If that's the case, return the\n * input URL as-is (nothing to be relative to).\n * @see https://github.com/mswjs/msw/issues/1777\n */\n if (typeof location === 'undefined') {\n return new URL(url)\n }\n\n return new URL(url.toString(), location.href)\n}\n\nfunction define(\n target: object,\n property: string | symbol,\n value: unknown\n): void {\n Reflect.defineProperty(target, property, {\n // Ensure writable properties to allow redefining readonly properties.\n writable: true,\n enumerable: true,\n value,\n })\n}\n","/**\n * Concatenate two `Uint8Array` buffers.\n */\nexport function concatArrayBuffer(\n left: Uint8Array,\n right: Uint8Array\n): Uint8Array {\n const result = new Uint8Array(left.byteLength + right.byteLength)\n result.set(left, 0)\n result.set(right, left.byteLength)\n return result\n}\n","export class EventPolyfill implements Event {\n readonly AT_TARGET: number = 0\n readonly BUBBLING_PHASE: number = 0\n readonly CAPTURING_PHASE: number = 0\n readonly NONE: number = 0\n\n public type: string = ''\n public srcElement: EventTarget | null = null\n public target: EventTarget | null\n public currentTarget: EventTarget | null = null\n public eventPhase: number = 0\n public timeStamp: number\n public isTrusted: boolean = true\n public composed: boolean = false\n public cancelable: boolean = true\n public defaultPrevented: boolean = false\n public bubbles: boolean = true\n public lengthComputable: boolean = true\n public loaded: number = 0\n public total: number = 0\n\n cancelBubble: boolean = false\n returnValue: boolean = true\n\n constructor(\n type: string,\n options?: { target: EventTarget; currentTarget: EventTarget }\n ) {\n this.type = type\n this.target = options?.target || null\n this.currentTarget = options?.currentTarget || null\n this.timeStamp = Date.now()\n }\n\n public composedPath(): EventTarget[] {\n return []\n }\n\n public initEvent(type: string, bubbles?: boolean, cancelable?: boolean) {\n this.type = type\n this.bubbles = !!bubbles\n this.cancelable = !!cancelable\n }\n\n public preventDefault() {\n this.defaultPrevented = true\n }\n\n public stopPropagation() {}\n public stopImmediatePropagation() {}\n}\n","import { EventPolyfill } from './EventPolyfill'\n\nexport class ProgressEventPolyfill extends EventPolyfill {\n readonly lengthComputable: boolean\n readonly composed: boolean\n readonly loaded: number\n readonly total: number\n\n constructor(type: string, init?: ProgressEventInit) {\n super(type)\n\n this.lengthComputable = init?.lengthComputable || false\n this.composed = init?.composed || false\n this.loaded = init?.loaded || 0\n this.total = init?.total || 0\n }\n}\n","import { EventPolyfill } from '../polyfills/EventPolyfill'\nimport { ProgressEventPolyfill } from '../polyfills/ProgressEventPolyfill'\n\nconst SUPPORTS_PROGRESS_EVENT = typeof ProgressEvent !== 'undefined'\n\nexport function createEvent(\n target: XMLHttpRequest,\n type: string,\n init?: ProgressEventInit\n): EventPolyfill {\n const progressEvents = [\n 'error',\n 'progress',\n 'loadstart',\n 'loadend',\n 'load',\n 'timeout',\n 'abort',\n ]\n\n /**\n * `ProgressEvent` is not supported in React Native.\n * @see https://github.com/mswjs/interceptors/issues/40\n */\n const ProgressEventClass = SUPPORTS_PROGRESS_EVENT\n ? ProgressEvent\n : ProgressEventPolyfill\n\n const event = progressEvents.includes(type)\n ? new ProgressEventClass(type, {\n lengthComputable: true,\n loaded: init?.loaded || 0,\n total: init?.total || 0,\n })\n : new EventPolyfill(type, {\n target,\n currentTarget: target,\n })\n\n return event\n}\n","/**\n * Returns the source object of the given property on the target object\n * (the target itself, any parent in its prototype, or null).\n */\nexport function findPropertySource(\n target: object,\n propertyName: string | symbol\n): object | null {\n if (!(propertyName in target)) {\n return null\n }\n\n const hasProperty = Object.prototype.hasOwnProperty.call(target, propertyName)\n if (hasProperty) {\n return target\n }\n\n const prototype = Reflect.getPrototypeOf(target)\n return prototype ? findPropertySource(prototype, propertyName) : null\n}\n","import { findPropertySource } from './findPropertySource'\n\nexport interface ProxyOptions> {\n constructorCall?(args: Array, next: NextFunction): Target\n\n methodCall?(\n this: Target,\n data: [methodName: F, args: Array],\n next: NextFunction\n ): void\n\n setProperty?(\n data: [propertyName: string | symbol, nextValue: unknown],\n next: NextFunction\n ): boolean\n\n getProperty?(\n data: [propertyName: string | symbol, receiver: Target],\n next: NextFunction\n ): void\n}\n\nexport type NextFunction = () => ReturnType\n\nexport function createProxy(\n target: Target,\n options: ProxyOptions\n): Target {\n const proxy = new Proxy(target, optionsToProxyHandler(options))\n\n return proxy\n}\n\nfunction optionsToProxyHandler>(\n options: ProxyOptions\n): ProxyHandler {\n const { constructorCall, methodCall, getProperty, setProperty } = options\n const handler: ProxyHandler = {}\n\n if (typeof constructorCall !== 'undefined') {\n handler.construct = function (target, args, newTarget) {\n const next = Reflect.construct.bind(null, target as any, args, newTarget)\n return constructorCall.call(newTarget, args, next)\n }\n }\n\n handler.set = function (target, propertyName, nextValue) {\n const next = () => {\n const propertySource = findPropertySource(target, propertyName) || target\n const ownDescriptors = Reflect.getOwnPropertyDescriptor(\n propertySource,\n propertyName\n )\n\n // Respect any custom setters present for this property.\n if (typeof ownDescriptors?.set !== 'undefined') {\n ownDescriptors.set.apply(target, [nextValue])\n return true\n }\n\n // Otherwise, set the property on the source.\n return Reflect.defineProperty(propertySource, propertyName, {\n writable: true,\n enumerable: true,\n configurable: true,\n value: nextValue,\n })\n }\n\n if (typeof setProperty !== 'undefined') {\n return setProperty.call(target, [propertyName, nextValue], next)\n }\n\n return next()\n }\n\n handler.get = function (target, propertyName, receiver) {\n /**\n * @note Using `Reflect.get()` here causes \"TypeError: Illegal invocation\".\n */\n const next = () => target[propertyName as any]\n\n const value =\n typeof getProperty !== 'undefined'\n ? getProperty.call(target, [propertyName, receiver], next)\n : next()\n\n if (typeof value === 'function') {\n return (...args: Array) => {\n const next = value.bind(target, ...args)\n\n if (typeof methodCall !== 'undefined') {\n return methodCall.call(target, [propertyName as any, args], next)\n }\n\n return next()\n }\n }\n\n return value\n }\n\n return handler\n}\n","export function isDomParserSupportedType(\n type: string\n): type is DOMParserSupportedType {\n const supportedTypes: Array = [\n 'application/xhtml+xml',\n 'application/xml',\n 'image/svg+xml',\n 'text/html',\n 'text/xml',\n ]\n return supportedTypes.some((supportedType) => {\n return type.startsWith(supportedType)\n })\n}\n","/**\n * Parses a given string into JSON.\n * Gracefully handles invalid JSON by returning `null`.\n */\nexport function parseJson(data: string): Record | null {\n try {\n const json = JSON.parse(data)\n return json\n } catch (_) {\n return null\n }\n}\n","import { isResponseWithoutBody } from '../../../utils/responseUtils'\n\n/**\n * Creates a Fetch API `Response` instance from the given\n * `XMLHttpRequest` instance and a response body.\n */\nexport function createResponse(\n request: XMLHttpRequest,\n body: BodyInit | null\n): Response {\n /**\n * Handle XMLHttpRequest responses that must have null as the\n * response body when represented using Fetch API Response.\n * XMLHttpRequest response will always have an empty string\n * as the \"request.response\" in those cases, resulting in an error\n * when constructing a Response instance.\n * @see https://github.com/mswjs/interceptors/issues/379\n */\n const responseBodyOrNull = isResponseWithoutBody(request.status) ? null : body\n\n return new Response(responseBodyOrNull, {\n status: request.status,\n statusText: request.statusText,\n headers: createHeadersFromXMLHttpReqestHeaders(\n request.getAllResponseHeaders()\n ),\n })\n}\n\nfunction createHeadersFromXMLHttpReqestHeaders(headersString: string): Headers {\n const headers = new Headers()\n\n const lines = headersString.split(/[\\r\\n]+/)\n for (const line of lines) {\n if (line.trim() === '') {\n continue\n }\n\n const [name, ...parts] = line.split(': ')\n const value = parts.join(': ')\n\n headers.append(name, value)\n }\n\n return headers\n}\n"]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/chunk-CVV3L375.mjs b/node_modules/@mswjs/interceptors/lib/node/chunk-CVV3L375.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c37d61d709235efebe4ea19703a901bfbc05c9e3 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/chunk-CVV3L375.mjs @@ -0,0 +1,889 @@ +import { + emitAsync, + toInteractiveRequest +} from "./chunk-OUWBQF3Z.mjs"; +import { + INTERNAL_REQUEST_ID_HEADER_NAME, + Interceptor, + createRequestId, + createServerErrorResponse, + isResponseError, + isResponseWithoutBody +} from "./chunk-Q7POAM5N.mjs"; + +// src/interceptors/ClientRequest/index.ts +import http from "http"; +import https from "https"; + +// src/interceptors/ClientRequest/NodeClientRequest.ts +import { ClientRequest, IncomingMessage as IncomingMessage2, STATUS_CODES } from "http"; +import { until } from "@open-draft/until"; +import { DeferredPromise } from "@open-draft/deferred-promise"; + +// src/interceptors/ClientRequest/utils/normalizeClientRequestEndArgs.ts +import { Logger } from "@open-draft/logger"; +var logger = new Logger("utils getUrlByRequestOptions"); +function normalizeClientRequestEndArgs(...args) { + logger.info("arguments", args); + const normalizedArgs = new Array(3).fill(null).map((value, index) => args[index] || value); + normalizedArgs.sort((a, b) => { + if (typeof a === "function") { + return 1; + } + if (typeof b === "function") { + return -1; + } + if (typeof a === "string" && typeof b === "string") { + return normalizedArgs.indexOf(a) - normalizedArgs.indexOf(b); + } + return 0; + }); + logger.info("normalized args", normalizedArgs); + return normalizedArgs; +} + +// src/interceptors/ClientRequest/utils/normalizeClientRequestWriteArgs.ts +import { Logger as Logger2 } from "@open-draft/logger"; +var logger2 = new Logger2("http normalizeWriteArgs"); +function normalizeClientRequestWriteArgs(args) { + logger2.info("normalizing ClientRequest.write arguments...", args); + const chunk = args[0]; + const encoding = typeof args[1] === "string" ? args[1] : void 0; + const callback = typeof args[1] === "function" ? args[1] : args[2]; + const writeArgs = [ + chunk, + encoding, + callback + ]; + logger2.info( + "successfully normalized ClientRequest.write arguments:", + writeArgs + ); + return writeArgs; +} + +// src/interceptors/ClientRequest/utils/cloneIncomingMessage.ts +import { IncomingMessage } from "http"; +import { PassThrough } from "stream"; +var IS_CLONE = Symbol("isClone"); +function cloneIncomingMessage(message) { + const clone = message.pipe(new PassThrough()); + inheritProperties(message, clone); + const clonedPrototype = Object.create(IncomingMessage.prototype); + getPrototypes(clone).forEach((prototype) => { + inheritProperties(prototype, clonedPrototype); + }); + Object.setPrototypeOf(clone, clonedPrototype); + Object.defineProperty(clone, IS_CLONE, { + enumerable: true, + value: true + }); + return clone; +} +function getPrototypes(source) { + const prototypes = []; + let current = source; + while (current = Object.getPrototypeOf(current)) { + prototypes.push(current); + } + return prototypes; +} +function inheritProperties(source, target) { + const properties = [ + ...Object.getOwnPropertyNames(source), + ...Object.getOwnPropertySymbols(source) + ]; + for (const property of properties) { + if (target.hasOwnProperty(property)) { + continue; + } + const descriptor = Object.getOwnPropertyDescriptor(source, property); + if (!descriptor) { + continue; + } + Object.defineProperty(target, property, descriptor); + } +} + +// src/interceptors/ClientRequest/utils/createResponse.ts +function createResponse(message) { + const responseBodyOrNull = isResponseWithoutBody(message.statusCode || 200) ? null : new ReadableStream({ + start(controller) { + message.on("data", (chunk) => controller.enqueue(chunk)); + message.on("end", () => controller.close()); + } + }); + return new Response(responseBodyOrNull, { + status: message.statusCode, + statusText: message.statusMessage, + headers: createHeadersFromIncomingHttpHeaders(message.headers) + }); +} +function createHeadersFromIncomingHttpHeaders(httpHeaders) { + const headers = new Headers(); + for (const headerName in httpHeaders) { + const headerValues = httpHeaders[headerName]; + if (typeof headerValues === "undefined") { + continue; + } + if (Array.isArray(headerValues)) { + headerValues.forEach((headerValue) => { + headers.append(headerName, headerValue); + }); + continue; + } + headers.set(headerName, headerValues); + } + return headers; +} + +// src/interceptors/ClientRequest/utils/createRequest.ts +function createRequest(clientRequest) { + const headers = new Headers(); + const outgoingHeaders = clientRequest.getHeaders(); + for (const headerName in outgoingHeaders) { + const headerValue = outgoingHeaders[headerName]; + if (typeof headerValue === "undefined") { + continue; + } + const valuesList = Array.prototype.concat([], headerValue); + for (const value of valuesList) { + headers.append(headerName, value.toString()); + } + } + if (clientRequest.url.username || clientRequest.url.password) { + const username = decodeURIComponent(clientRequest.url.username || ""); + const password = decodeURIComponent(clientRequest.url.password || ""); + const auth = `${username}:${password}`; + headers.set("Authorization", `Basic ${btoa(auth)}`); + clientRequest.url.username = ""; + clientRequest.url.password = ""; + } + const method = clientRequest.method || "GET"; + return new Request(clientRequest.url, { + method, + headers, + credentials: "same-origin", + body: method === "HEAD" || method === "GET" ? null : clientRequest.requestBuffer + }); +} + +// src/utils/getValueBySymbol.ts +function getValueBySymbol(symbolName, source) { + const ownSymbols = Object.getOwnPropertySymbols(source); + const symbol = ownSymbols.find((symbol2) => { + return symbol2.description === symbolName; + }); + if (symbol) { + return Reflect.get(source, symbol); + } + return; +} + +// src/utils/isObject.ts +function isObject(value, loose = false) { + return loose ? Object.prototype.toString.call(value).startsWith("[object ") : Object.prototype.toString.call(value) === "[object Object]"; +} + +// src/utils/getRawFetchHeaders.ts +function getRawFetchHeaders(headers) { + const headersList = getValueBySymbol("headers list", headers); + if (!headersList) { + return; + } + const headersMap = getValueBySymbol("headers map", headersList); + if (!headersMap || !isHeadersMapWithRawHeaderNames(headersMap)) { + return; + } + const rawHeaders = /* @__PURE__ */ new Map(); + headersMap.forEach(({ name, value }) => { + rawHeaders.set(name, value); + }); + return rawHeaders; +} +function isHeadersMapWithRawHeaderNames(headersMap) { + return Array.from( + headersMap.values() + ).every((value) => { + return isObject(value) && "name" in value; + }); +} + +// src/utils/isNodeLikeError.ts +function isNodeLikeError(error) { + if (error == null) { + return false; + } + if (!(error instanceof Error)) { + return false; + } + return "code" in error && "errno" in error; +} + +// src/interceptors/ClientRequest/NodeClientRequest.ts +var _NodeClientRequest = class extends ClientRequest { + constructor([url, requestOptions, callback], options) { + super(requestOptions, callback); + this.chunks = []; + this.logger = options.logger.extend( + `request ${requestOptions.method} ${url.href}` + ); + this.logger.info("constructing ClientRequest using options:", { + url, + requestOptions, + callback + }); + this.state = 0 /* Idle */; + this.url = url; + this.emitter = options.emitter; + this.requestBuffer = null; + this.response = new IncomingMessage2(this.socket); + } + writeRequestBodyChunk(chunk, encoding) { + if (chunk == null) { + return; + } + if (this.requestBuffer == null) { + this.requestBuffer = Buffer.from([]); + } + const resolvedChunk = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding); + this.requestBuffer = Buffer.concat([this.requestBuffer, resolvedChunk]); + } + write(...args) { + var _a; + const [chunk, encoding, callback] = normalizeClientRequestWriteArgs(args); + this.logger.info("write:", { chunk, encoding, callback }); + this.chunks.push({ chunk, encoding }); + this.writeRequestBodyChunk(chunk, encoding); + this.logger.info( + "chunk successfully stored!", + (_a = this.requestBuffer) == null ? void 0 : _a.byteLength + ); + if (!chunk || chunk.length === 0) { + this.logger.info("written chunk is empty, skipping callback..."); + } else { + callback == null ? void 0 : callback(); + } + return true; + } + end(...args) { + this.logger.info("end", args); + const requestId = createRequestId(); + const [chunk, encoding, callback] = normalizeClientRequestEndArgs(...args); + this.logger.info("normalized arguments:", { chunk, encoding, callback }); + this.writeRequestBodyChunk(chunk, encoding || void 0); + this.state = 2 /* Sent */; + const capturedRequest = createRequest(this); + const { interactiveRequest, requestController } = toInteractiveRequest(capturedRequest); + Object.defineProperty(capturedRequest, "respondWith", { + value: requestController.respondWith.bind(requestController) + }); + if (this.hasHeader(INTERNAL_REQUEST_ID_HEADER_NAME)) { + this.removeHeader(INTERNAL_REQUEST_ID_HEADER_NAME); + return this.passthrough(chunk, encoding, callback); + } + this.emitter.once("request", ({ requestId: pendingRequestId }) => { + if (pendingRequestId !== requestId) { + return; + } + if (requestController.responsePromise.state === "pending") { + this.logger.info( + "request has not been handled in listeners, executing fail-safe listener..." + ); + requestController.responsePromise.resolve(void 0); + } + }); + until(async () => { + this.logger.info( + 'emitting the "request" event for %d listener(s)...', + this.emitter.listenerCount("request") + ); + this.state = 3 /* MockLookupStart */; + await emitAsync(this.emitter, "request", { + request: interactiveRequest, + requestId + }); + this.logger.info('all "request" listeners done!'); + const mockedResponse = await requestController.responsePromise; + this.logger.info("event.respondWith called with:", mockedResponse); + return mockedResponse; + }).then((resolverResult) => { + this.logger.info("the listeners promise awaited!"); + this.state = 4 /* MockLookupEnd */; + if (!this.headersSent) { + for (const [headerName, headerValue] of capturedRequest.headers) { + this.setHeader(headerName, headerValue); + } + } + if (resolverResult.error) { + this.logger.info( + "unhandled resolver exception, coercing to an error response...", + resolverResult.error + ); + if (resolverResult.error instanceof Response) { + if (isResponseError(resolverResult.error)) { + this.logger.info( + "received network error response, erroring request..." + ); + this.errorWith(new TypeError("Network error")); + } else { + this.respondWith(resolverResult.error); + } + return; + } + if (isNodeLikeError(resolverResult.error)) { + this.errorWith(resolverResult.error); + return this; + } + until(async () => { + if (this.emitter.listenerCount("unhandledException") > 0) { + await emitAsync(this.emitter, "unhandledException", { + error: resolverResult.error, + request: capturedRequest, + requestId, + controller: { + respondWith: this.respondWith.bind(this), + errorWith: this.errorWith.bind(this) + } + }); + if (this.writableEnded || this.destroyed) { + return; + } + } + this.respondWith(createServerErrorResponse(resolverResult.error)); + }); + return this; + } + const mockedResponse = resolverResult.data; + if (mockedResponse) { + this.logger.info( + "received mocked response:", + mockedResponse.status, + mockedResponse.statusText + ); + this.destroyed = false; + if (isResponseError(mockedResponse)) { + this.logger.info( + "received network error response, erroring request..." + ); + this.errorWith(new TypeError("Network error")); + return this; + } + const responseClone = mockedResponse.clone(); + this.respondWith(mockedResponse); + this.logger.info( + mockedResponse.status, + mockedResponse.statusText, + "(MOCKED)" + ); + callback == null ? void 0 : callback(); + this.logger.info('emitting the custom "response" event...'); + this.emitter.emit("response", { + response: responseClone, + isMockedResponse: true, + request: capturedRequest, + requestId + }); + this.logger.info("request (mock) is completed"); + return this; + } + this.logger.info("no mocked response received!"); + this.once("response-internal", (message) => { + this.logger.info(message.statusCode, message.statusMessage); + this.logger.info("original response headers:", message.headers); + this.logger.info('emitting the custom "response" event...'); + this.emitter.emit("response", { + response: createResponse(message), + isMockedResponse: false, + request: capturedRequest, + requestId + }); + }); + return this.passthrough(chunk, encoding, callback); + }); + return this; + } + emit(event, ...data) { + this.logger.info("emit: %s", event); + if (event === "response") { + this.logger.info('found "response" event, cloning the response...'); + try { + const response = data[0]; + const firstClone = cloneIncomingMessage(response); + const secondClone = cloneIncomingMessage(response); + this.emit("response-internal", secondClone); + this.logger.info( + 'response successfully cloned, emitting "response" event...' + ); + return super.emit(event, firstClone, ...data.slice(1)); + } catch (error) { + this.logger.info("error when cloning response:", error); + return super.emit(event, ...data); + } + } + if (event === "error") { + const error = data[0]; + const errorCode = error.code || ""; + this.logger.info("error:\n", error); + if (_NodeClientRequest.suppressErrorCodes.includes(errorCode)) { + if (this.state < 4 /* MockLookupEnd */) { + if (!this.capturedError) { + this.capturedError = error; + this.logger.info("captured the first error:", this.capturedError); + } + return false; + } + if (this.state === 5 /* ResponseReceived */ && this.responseType === "mock") { + return false; + } + } + } + return super.emit(event, ...data); + } + /** + * Performs the intercepted request as-is. + * Replays the captured request body chunks, + * still emits the internal events, and wraps + * up the request with `super.end()`. + */ + passthrough(chunk, encoding, callback) { + this.state = 5 /* ResponseReceived */; + this.responseType = "passthrough"; + if (this.capturedError) { + this.emit("error", this.capturedError); + return this; + } + this.logger.info("writing request chunks...", this.chunks); + for (const { chunk: chunk2, encoding: encoding2 } of this.chunks) { + if (encoding2) { + super.write(chunk2, encoding2); + } else { + super.write(chunk2); + } + } + this.once("error", (error) => { + this.logger.info("original request error:", error); + }); + this.once("abort", () => { + this.logger.info("original request aborted!"); + }); + this.once("response-internal", (message) => { + this.logger.info(message.statusCode, message.statusMessage); + this.logger.info("original response headers:", message.headers); + }); + this.logger.info("performing original request..."); + return super.end(...[chunk, encoding, callback].filter(Boolean)); + } + /** + * Responds to this request instance using a mocked response. + */ + respondWith(mockedResponse) { + this.logger.info("responding with a mocked response...", mockedResponse); + this.state = 5 /* ResponseReceived */; + this.responseType = "mock"; + Object.defineProperties(this, { + writableFinished: { value: true }, + writableEnded: { value: true } + }); + this.emit("finish"); + const { status, statusText, headers, body } = mockedResponse; + this.response.statusCode = status; + this.response.statusMessage = statusText || STATUS_CODES[status]; + const rawHeaders = getRawFetchHeaders(headers) || headers; + if (rawHeaders) { + this.response.headers = {}; + rawHeaders.forEach((headerValue, headerName) => { + this.response.rawHeaders.push(headerName, headerValue); + const insensitiveHeaderName = headerName.toLowerCase(); + const prevHeaders = this.response.headers[insensitiveHeaderName]; + this.response.headers[insensitiveHeaderName] = prevHeaders ? Array.prototype.concat([], prevHeaders, headerValue) : headerValue; + }); + } + this.logger.info("mocked response headers ready:", headers); + this.res = this.response; + this.emit("response", this.response); + const isResponseStreamFinished = new DeferredPromise(); + const finishResponseStream = () => { + this.logger.info("finished response stream!"); + this.response.push(null); + this.response.complete = true; + isResponseStreamFinished.resolve(); + }; + if (body) { + const bodyReader = body.getReader(); + const readNextChunk = async () => { + const { done, value } = await bodyReader.read(); + if (done) { + finishResponseStream(); + return; + } + this.response.emit("data", value); + return readNextChunk(); + }; + readNextChunk(); + } else { + finishResponseStream(); + } + isResponseStreamFinished.then(() => { + this.logger.info("finalizing response..."); + this.response.emit("end"); + this.terminate(); + this.logger.info("request complete!"); + }); + } + errorWith(error) { + this.destroyed = true; + this.emit("error", error); + this.terminate(); + } + /** + * Terminates a pending request. + */ + terminate() { + var _a; + (_a = this.agent) == null ? void 0 : _a.destroy(); + } +}; +var NodeClientRequest = _NodeClientRequest; +/** + * The list of internal Node.js errors to suppress while + * using the "mock" response source. + */ +NodeClientRequest.suppressErrorCodes = [ + "ENOTFOUND", + "ECONNREFUSED", + "ECONNRESET", + "EAI_AGAIN", + "ENETUNREACH", + "EHOSTUNREACH" +]; + +// src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.ts +import { + Agent as HttpAgent, + globalAgent as httpGlobalAgent +} from "http"; +import { + Agent as HttpsAgent, + globalAgent as httpsGlobalAgent +} from "https"; +import { parse as parseUrl } from "url"; +import { Logger as Logger5 } from "@open-draft/logger"; + +// src/utils/getRequestOptionsByUrl.ts +function getRequestOptionsByUrl(url) { + const options = { + method: "GET", + protocol: url.protocol, + hostname: typeof url.hostname === "string" && url.hostname.startsWith("[") ? url.hostname.slice(1, -1) : url.hostname, + host: url.host, + path: `${url.pathname}${url.search || ""}` + }; + if (!!url.port) { + options.port = Number(url.port); + } + if (url.username || url.password) { + options.auth = `${url.username}:${url.password}`; + } + return options; +} + +// src/utils/getUrlByRequestOptions.ts +import { Agent } from "http"; +import { Logger as Logger3 } from "@open-draft/logger"; +var logger3 = new Logger3("utils getUrlByRequestOptions"); +var DEFAULT_PATH = "/"; +var DEFAULT_PROTOCOL = "http:"; +var DEFAULT_HOSTNAME = "localhost"; +var SSL_PORT = 443; +function getAgent(options) { + return options.agent instanceof Agent ? options.agent : void 0; +} +function getProtocolByRequestOptions(options) { + var _a; + if (options.protocol) { + return options.protocol; + } + const agent = getAgent(options); + const agentProtocol = agent == null ? void 0 : agent.protocol; + if (agentProtocol) { + return agentProtocol; + } + const port = getPortByRequestOptions(options); + const isSecureRequest = options.cert || port === SSL_PORT; + return isSecureRequest ? "https:" : ((_a = options.uri) == null ? void 0 : _a.protocol) || DEFAULT_PROTOCOL; +} +function getPortByRequestOptions(options) { + if (options.port) { + return Number(options.port); + } + const agent = getAgent(options); + if (agent == null ? void 0 : agent.options.port) { + return Number(agent.options.port); + } + if (agent == null ? void 0 : agent.defaultPort) { + return Number(agent.defaultPort); + } + return void 0; +} +function getAuthByRequestOptions(options) { + if (options.auth) { + const [username, password] = options.auth.split(":"); + return { username, password }; + } +} +function isRawIPv6Address(host) { + return host.includes(":") && !host.startsWith("[") && !host.endsWith("]"); +} +function getHostname(options) { + let host = options.hostname || options.host; + if (host) { + if (isRawIPv6Address(host)) { + host = `[${host}]`; + } + return new URL(`http://${host}`).hostname; + } + return DEFAULT_HOSTNAME; +} +function getUrlByRequestOptions(options) { + logger3.info("request options", options); + if (options.uri) { + logger3.info( + 'constructing url from explicitly provided "options.uri": %s', + options.uri + ); + return new URL(options.uri.href); + } + logger3.info("figuring out url from request options..."); + const protocol = getProtocolByRequestOptions(options); + logger3.info("protocol", protocol); + const port = getPortByRequestOptions(options); + logger3.info("port", port); + const hostname = getHostname(options); + logger3.info("hostname", hostname); + const path = options.path || DEFAULT_PATH; + logger3.info("path", path); + const credentials = getAuthByRequestOptions(options); + logger3.info("credentials", credentials); + const authString = credentials ? `${credentials.username}:${credentials.password}@` : ""; + logger3.info("auth string:", authString); + const portString = typeof port !== "undefined" ? `:${port}` : ""; + const url = new URL(`${protocol}//${hostname}${portString}${path}`); + url.username = (credentials == null ? void 0 : credentials.username) || ""; + url.password = (credentials == null ? void 0 : credentials.password) || ""; + logger3.info("created url:", url); + return url; +} + +// src/utils/cloneObject.ts +import { Logger as Logger4 } from "@open-draft/logger"; +var logger4 = new Logger4("cloneObject"); +function isPlainObject(obj) { + var _a; + logger4.info("is plain object?", obj); + if (obj == null || !((_a = obj.constructor) == null ? void 0 : _a.name)) { + logger4.info("given object is undefined, not a plain object..."); + return false; + } + logger4.info("checking the object constructor:", obj.constructor.name); + return obj.constructor.name === "Object"; +} +function cloneObject(obj) { + logger4.info("cloning object:", obj); + const enumerableProperties = Object.entries(obj).reduce( + (acc, [key, value]) => { + logger4.info("analyzing key-value pair:", key, value); + acc[key] = isPlainObject(value) ? cloneObject(value) : value; + return acc; + }, + {} + ); + return isPlainObject(obj) ? enumerableProperties : Object.assign(Object.getPrototypeOf(obj), enumerableProperties); +} + +// src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.ts +var logger5 = new Logger5("http normalizeClientRequestArgs"); +function resolveRequestOptions(args, url) { + if (typeof args[1] === "undefined" || typeof args[1] === "function") { + logger5.info("request options not provided, deriving from the url", url); + return getRequestOptionsByUrl(url); + } + if (args[1]) { + logger5.info("has custom RequestOptions!", args[1]); + const requestOptionsFromUrl = getRequestOptionsByUrl(url); + logger5.info("derived RequestOptions from the URL:", requestOptionsFromUrl); + logger5.info("cloning RequestOptions..."); + const clonedRequestOptions = cloneObject(args[1]); + logger5.info("successfully cloned RequestOptions!", clonedRequestOptions); + return { + ...requestOptionsFromUrl, + ...clonedRequestOptions + }; + } + logger5.info("using an empty object as request options"); + return {}; +} +function overrideUrlByRequestOptions(url, options) { + url.host = options.host || url.host; + url.hostname = options.hostname || url.hostname; + url.port = options.port ? options.port.toString() : url.port; + if (options.path) { + const parsedOptionsPath = parseUrl(options.path, false); + url.pathname = parsedOptionsPath.pathname || ""; + url.search = parsedOptionsPath.search || ""; + } + return url; +} +function resolveCallback(args) { + return typeof args[1] === "function" ? args[1] : args[2]; +} +function normalizeClientRequestArgs(defaultProtocol, ...args) { + let url; + let options; + let callback; + logger5.info("arguments", args); + logger5.info("using default protocol:", defaultProtocol); + if (args.length === 0) { + const url2 = new URL("http://localhost"); + const options2 = resolveRequestOptions(args, url2); + return [url2, options2]; + } + if (typeof args[0] === "string") { + logger5.info("first argument is a location string:", args[0]); + url = new URL(args[0]); + logger5.info("created a url:", url); + const requestOptionsFromUrl = getRequestOptionsByUrl(url); + logger5.info("request options from url:", requestOptionsFromUrl); + options = resolveRequestOptions(args, url); + logger5.info("resolved request options:", options); + callback = resolveCallback(args); + } else if (args[0] instanceof URL) { + url = args[0]; + logger5.info("first argument is a URL:", url); + if (typeof args[1] !== "undefined" && isObject(args[1])) { + url = overrideUrlByRequestOptions(url, args[1]); + } + options = resolveRequestOptions(args, url); + logger5.info("derived request options:", options); + callback = resolveCallback(args); + } else if ("hash" in args[0] && !("method" in args[0])) { + const [legacyUrl] = args; + logger5.info("first argument is a legacy URL:", legacyUrl); + if (legacyUrl.hostname === null) { + logger5.info("given legacy URL is relative (no hostname)"); + return isObject(args[1]) ? normalizeClientRequestArgs( + defaultProtocol, + { path: legacyUrl.path, ...args[1] }, + args[2] + ) : normalizeClientRequestArgs( + defaultProtocol, + { path: legacyUrl.path }, + args[1] + ); + } + logger5.info("given legacy url is absolute"); + const resolvedUrl = new URL(legacyUrl.href); + return args[1] === void 0 ? normalizeClientRequestArgs(defaultProtocol, resolvedUrl) : typeof args[1] === "function" ? normalizeClientRequestArgs(defaultProtocol, resolvedUrl, args[1]) : normalizeClientRequestArgs( + defaultProtocol, + resolvedUrl, + args[1], + args[2] + ); + } else if (isObject(args[0])) { + options = args[0]; + logger5.info("first argument is RequestOptions:", options); + options.protocol = options.protocol || defaultProtocol; + logger5.info("normalized request options:", options); + url = getUrlByRequestOptions(options); + logger5.info("created a URL from RequestOptions:", url.href); + callback = resolveCallback(args); + } else { + throw new Error( + `Failed to construct ClientRequest with these parameters: ${args}` + ); + } + options.protocol = options.protocol || url.protocol; + options.method = options.method || "GET"; + if (typeof options.agent === "undefined") { + const agent = options.protocol === "https:" ? new HttpsAgent({ + rejectUnauthorized: options.rejectUnauthorized + }) : new HttpAgent(); + options.agent = agent; + logger5.info("resolved fallback agent:", agent); + } + if (!options._defaultAgent) { + logger5.info( + 'has no default agent, setting the default agent for "%s"', + options.protocol + ); + options._defaultAgent = options.protocol === "https:" ? httpsGlobalAgent : httpGlobalAgent; + } + logger5.info("successfully resolved url:", url.href); + logger5.info("successfully resolved options:", options); + logger5.info("successfully resolved callback:", callback); + return [url, options, callback]; +} + +// src/interceptors/ClientRequest/http.get.ts +function get(protocol, options) { + return function interceptorsHttpGet(...args) { + const clientRequestArgs = normalizeClientRequestArgs( + `${protocol}:`, + ...args + ); + const request2 = new NodeClientRequest(clientRequestArgs, options); + request2.end(); + return request2; + }; +} + +// src/interceptors/ClientRequest/http.request.ts +import { Logger as Logger6 } from "@open-draft/logger"; +var logger6 = new Logger6("http request"); +function request(protocol, options) { + return function interceptorsHttpRequest(...args) { + logger6.info('request call (protocol "%s"):', protocol, args); + const clientRequestArgs = normalizeClientRequestArgs( + `${protocol}:`, + ...args + ); + return new NodeClientRequest(clientRequestArgs, options); + }; +} + +// src/interceptors/ClientRequest/index.ts +var _ClientRequestInterceptor = class extends Interceptor { + constructor() { + super(_ClientRequestInterceptor.interceptorSymbol); + this.modules = /* @__PURE__ */ new Map(); + this.modules.set("http", http); + this.modules.set("https", https); + } + setup() { + const logger7 = this.logger.extend("setup"); + for (const [protocol, requestModule] of this.modules) { + const { request: pureRequest, get: pureGet } = requestModule; + this.subscriptions.push(() => { + requestModule.request = pureRequest; + requestModule.get = pureGet; + logger7.info('native "%s" module restored!', protocol); + }); + const options = { + emitter: this.emitter, + logger: this.logger + }; + requestModule.request = // Force a line break. + request(protocol, options); + requestModule.get = // Force a line break. + get(protocol, options); + logger7.info('native "%s" module patched!', protocol); + } + } +}; +var ClientRequestInterceptor = _ClientRequestInterceptor; +ClientRequestInterceptor.interceptorSymbol = Symbol("http"); + +export { + ClientRequestInterceptor +}; +//# sourceMappingURL=chunk-CVV3L375.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/chunk-CVV3L375.mjs.map b/node_modules/@mswjs/interceptors/lib/node/chunk-CVV3L375.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..a8c32700ca3955591711aaffad9eef85d9b7d2d6 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/chunk-CVV3L375.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/interceptors/ClientRequest/index.ts","../../src/interceptors/ClientRequest/NodeClientRequest.ts","../../src/interceptors/ClientRequest/utils/normalizeClientRequestEndArgs.ts","../../src/interceptors/ClientRequest/utils/normalizeClientRequestWriteArgs.ts","../../src/interceptors/ClientRequest/utils/cloneIncomingMessage.ts","../../src/interceptors/ClientRequest/utils/createResponse.ts","../../src/interceptors/ClientRequest/utils/createRequest.ts","../../src/utils/getValueBySymbol.ts","../../src/utils/isObject.ts","../../src/utils/getRawFetchHeaders.ts","../../src/utils/isNodeLikeError.ts","../../src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.ts","../../src/utils/getRequestOptionsByUrl.ts","../../src/utils/getUrlByRequestOptions.ts","../../src/utils/cloneObject.ts","../../src/interceptors/ClientRequest/http.get.ts","../../src/interceptors/ClientRequest/http.request.ts"],"sourcesContent":["import http from 'http'\nimport https from 'https'\nimport type { Emitter } from 'strict-event-emitter'\nimport { HttpRequestEventMap } from '../../glossary'\nimport { Interceptor } from '../../Interceptor'\nimport { get } from './http.get'\nimport { request } from './http.request'\nimport { NodeClientOptions, Protocol } from './NodeClientRequest'\n\nexport type ClientRequestEmitter = Emitter\n\nexport type ClientRequestModules = Map\n\n/**\n * Intercept requests made via the `ClientRequest` class.\n * Such requests include `http.get`, `https.request`, etc.\n */\nexport class ClientRequestInterceptor extends Interceptor {\n static interceptorSymbol = Symbol('http')\n private modules: ClientRequestModules\n\n constructor() {\n super(ClientRequestInterceptor.interceptorSymbol)\n\n this.modules = new Map()\n this.modules.set('http', http)\n this.modules.set('https', https)\n }\n\n protected setup(): void {\n const logger = this.logger.extend('setup')\n\n for (const [protocol, requestModule] of this.modules) {\n const { request: pureRequest, get: pureGet } = requestModule\n\n this.subscriptions.push(() => {\n requestModule.request = pureRequest\n requestModule.get = pureGet\n\n logger.info('native \"%s\" module restored!', protocol)\n })\n\n const options: NodeClientOptions = {\n emitter: this.emitter,\n logger: this.logger,\n }\n\n // @ts-ignore\n requestModule.request =\n // Force a line break.\n request(protocol, options)\n\n // @ts-ignore\n requestModule.get =\n // Force a line break.\n get(protocol, options)\n\n logger.info('native \"%s\" module patched!', protocol)\n }\n }\n}\n","import { ClientRequest, IncomingMessage, STATUS_CODES } from 'node:http'\nimport type { Logger } from '@open-draft/logger'\nimport { until } from '@open-draft/until'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport type { ClientRequestEmitter } from '.'\nimport {\n ClientRequestEndCallback,\n ClientRequestEndChunk,\n normalizeClientRequestEndArgs,\n} from './utils/normalizeClientRequestEndArgs'\nimport { NormalizedClientRequestArgs } from './utils/normalizeClientRequestArgs'\nimport {\n ClientRequestWriteArgs,\n normalizeClientRequestWriteArgs,\n} from './utils/normalizeClientRequestWriteArgs'\nimport { cloneIncomingMessage } from './utils/cloneIncomingMessage'\nimport { createResponse } from './utils/createResponse'\nimport { createRequest } from './utils/createRequest'\nimport { toInteractiveRequest } from '../../utils/toInteractiveRequest'\nimport { emitAsync } from '../../utils/emitAsync'\nimport { getRawFetchHeaders } from '../../utils/getRawFetchHeaders'\nimport { isNodeLikeError } from '../../utils/isNodeLikeError'\nimport { INTERNAL_REQUEST_ID_HEADER_NAME } from '../../Interceptor'\nimport { createRequestId } from '../../createRequestId'\nimport {\n createServerErrorResponse,\n isResponseError,\n} from '../../utils/responseUtils'\n\nexport type Protocol = 'http' | 'https'\n\nenum HttpClientInternalState {\n // Have the concept of an idle request because different\n // request methods can kick off request sending\n // (e.g. \".end()\" or \".flushHeaders()\").\n Idle,\n Sending,\n Sent,\n MockLookupStart,\n MockLookupEnd,\n ResponseReceived,\n}\n\nexport interface NodeClientOptions {\n emitter: ClientRequestEmitter\n logger: Logger\n}\n\nexport class NodeClientRequest extends ClientRequest {\n /**\n * The list of internal Node.js errors to suppress while\n * using the \"mock\" response source.\n */\n static suppressErrorCodes = [\n 'ENOTFOUND',\n 'ECONNREFUSED',\n 'ECONNRESET',\n 'EAI_AGAIN',\n 'ENETUNREACH',\n 'EHOSTUNREACH',\n ]\n\n /**\n * Internal state of the request.\n */\n private state: HttpClientInternalState\n private responseType?: 'mock' | 'passthrough'\n private response: IncomingMessage\n private emitter: ClientRequestEmitter\n private logger: Logger\n private chunks: Array<{\n chunk?: string | Buffer\n encoding?: BufferEncoding\n }> = []\n private capturedError?: NodeJS.ErrnoException\n\n public url: URL\n public requestBuffer: Buffer | null\n\n constructor(\n [url, requestOptions, callback]: NormalizedClientRequestArgs,\n options: NodeClientOptions\n ) {\n super(requestOptions, callback)\n\n this.logger = options.logger.extend(\n `request ${requestOptions.method} ${url.href}`\n )\n\n this.logger.info('constructing ClientRequest using options:', {\n url,\n requestOptions,\n callback,\n })\n\n this.state = HttpClientInternalState.Idle\n this.url = url\n this.emitter = options.emitter\n\n // Set request buffer to null by default so that GET/HEAD requests\n // without a body wouldn't suddenly get one.\n this.requestBuffer = null\n\n // Construct a mocked response message.\n this.response = new IncomingMessage(this.socket!)\n }\n\n private writeRequestBodyChunk(\n chunk: string | Buffer | null,\n encoding?: BufferEncoding\n ): void {\n if (chunk == null) {\n return\n }\n\n if (this.requestBuffer == null) {\n this.requestBuffer = Buffer.from([])\n }\n\n const resolvedChunk = Buffer.isBuffer(chunk)\n ? chunk\n : Buffer.from(chunk, encoding)\n\n this.requestBuffer = Buffer.concat([this.requestBuffer, resolvedChunk])\n }\n\n write(...args: ClientRequestWriteArgs): boolean {\n const [chunk, encoding, callback] = normalizeClientRequestWriteArgs(args)\n this.logger.info('write:', { chunk, encoding, callback })\n this.chunks.push({ chunk, encoding })\n\n // Write each request body chunk to the internal buffer.\n this.writeRequestBodyChunk(chunk, encoding)\n\n this.logger.info(\n 'chunk successfully stored!',\n this.requestBuffer?.byteLength\n )\n\n /**\n * Prevent invoking the callback if the written chunk is empty.\n * @see https://nodejs.org/api/http.html#requestwritechunk-encoding-callback\n */\n if (!chunk || chunk.length === 0) {\n this.logger.info('written chunk is empty, skipping callback...')\n } else {\n callback?.()\n }\n\n // Do not write the request body chunks to prevent\n // the Socket from sending data to a potentially existing\n // server when there is a mocked response defined.\n return true\n }\n\n end(...args: any): this {\n this.logger.info('end', args)\n\n const requestId = createRequestId()\n\n const [chunk, encoding, callback] = normalizeClientRequestEndArgs(...args)\n this.logger.info('normalized arguments:', { chunk, encoding, callback })\n\n // Write the last request body chunk passed to the \"end()\" method.\n this.writeRequestBodyChunk(chunk, encoding || undefined)\n\n /**\n * @note Mark the request as sent immediately when invoking \".end()\".\n * In Node.js, calling \".end()\" will flush the remaining request body\n * and mark the request as \"finished\" immediately (\"end\" is synchronous)\n * but we delegate that property update to:\n *\n * - respondWith(), in the case of mocked responses;\n * - super.end(), in the case of bypassed responses.\n *\n * For that reason, we have to keep an internal flag for a finished request.\n */\n this.state = HttpClientInternalState.Sent\n\n const capturedRequest = createRequest(this)\n const { interactiveRequest, requestController } =\n toInteractiveRequest(capturedRequest)\n\n /**\n * @todo Remove this modification of the original request\n * and expose the controller alongside it in the \"request\"\n * listener argument.\n */\n Object.defineProperty(capturedRequest, 'respondWith', {\n value: requestController.respondWith.bind(requestController),\n })\n\n // Prevent handling this request if it has already been handled\n // in another (parent) interceptor (like XMLHttpRequest -> ClientRequest).\n // That means some interceptor up the chain has concluded that\n // this request must be performed as-is.\n if (this.hasHeader(INTERNAL_REQUEST_ID_HEADER_NAME)) {\n this.removeHeader(INTERNAL_REQUEST_ID_HEADER_NAME)\n return this.passthrough(chunk, encoding, callback)\n }\n\n // Add the last \"request\" listener that always resolves\n // the pending response Promise. This way if the consumer\n // hasn't handled the request themselves, we will prevent\n // the response Promise from pending indefinitely.\n this.emitter.once('request', ({ requestId: pendingRequestId }) => {\n /**\n * @note Ignore request events emitted by irrelevant\n * requests. This happens when response patching.\n */\n if (pendingRequestId !== requestId) {\n return\n }\n\n if (requestController.responsePromise.state === 'pending') {\n this.logger.info(\n 'request has not been handled in listeners, executing fail-safe listener...'\n )\n\n requestController.responsePromise.resolve(undefined)\n }\n })\n\n // Execute the resolver Promise like a side-effect.\n // Node.js 16 forces \"ClientRequest.end\" to be synchronous and return \"this\".\n until(async () => {\n // Notify the interceptor about the request.\n // This will call any \"request\" listeners the users have.\n this.logger.info(\n 'emitting the \"request\" event for %d listener(s)...',\n this.emitter.listenerCount('request')\n )\n\n this.state = HttpClientInternalState.MockLookupStart\n\n await emitAsync(this.emitter, 'request', {\n request: interactiveRequest,\n requestId,\n })\n\n this.logger.info('all \"request\" listeners done!')\n\n const mockedResponse = await requestController.responsePromise\n this.logger.info('event.respondWith called with:', mockedResponse)\n\n return mockedResponse\n }).then((resolverResult) => {\n this.logger.info('the listeners promise awaited!')\n\n this.state = HttpClientInternalState.MockLookupEnd\n\n /**\n * @fixme We are in the \"end()\" method that still executes in parallel\n * to our mocking logic here. This can be solved by migrating to the\n * Proxy-based approach and deferring the passthrough \"end()\" properly.\n * @see https://github.com/mswjs/interceptors/issues/346\n */\n if (!this.headersSent) {\n // Forward any request headers that the \"request\" listener\n // may have modified before proceeding with this request.\n for (const [headerName, headerValue] of capturedRequest.headers) {\n this.setHeader(headerName, headerValue)\n }\n }\n\n if (resolverResult.error) {\n this.logger.info(\n 'unhandled resolver exception, coercing to an error response...',\n resolverResult.error\n )\n\n // Handle thrown Response instances.\n if (resolverResult.error instanceof Response) {\n // Treat thrown Response.error() as a request error.\n if (isResponseError(resolverResult.error)) {\n this.logger.info(\n 'received network error response, erroring request...'\n )\n\n this.errorWith(new TypeError('Network error'))\n } else {\n // Handle a thrown Response as a mocked response.\n this.respondWith(resolverResult.error)\n }\n\n return\n }\n\n // Allow throwing Node.js-like errors, like connection rejection errors.\n // Treat them as request errors.\n if (isNodeLikeError(resolverResult.error)) {\n this.errorWith(resolverResult.error)\n return this\n }\n\n until(async () => {\n if (this.emitter.listenerCount('unhandledException') > 0) {\n // Emit the \"unhandledException\" event to allow the client\n // to opt-out from the default handling of exceptions\n // as 500 error responses.\n await emitAsync(this.emitter, 'unhandledException', {\n error: resolverResult.error,\n request: capturedRequest,\n requestId,\n controller: {\n respondWith: this.respondWith.bind(this),\n errorWith: this.errorWith.bind(this),\n },\n })\n\n // If after the \"unhandledException\" listeners are done,\n // the request is either not writable (was mocked) or\n // destroyed (has errored), do nothing.\n if (this.writableEnded || this.destroyed) {\n return\n }\n }\n\n // Unhandled exceptions in the request listeners are\n // synonymous to unhandled exceptions on the server.\n // Those are represented as 500 error responses.\n this.respondWith(createServerErrorResponse(resolverResult.error))\n })\n\n return this\n }\n\n const mockedResponse = resolverResult.data\n\n if (mockedResponse) {\n this.logger.info(\n 'received mocked response:',\n mockedResponse.status,\n mockedResponse.statusText\n )\n\n /**\n * @note Ignore this request being destroyed by TLS in Node.js\n * due to connection errors.\n */\n this.destroyed = false\n\n // Handle mocked \"Response.error\" network error responses.\n if (isResponseError(mockedResponse)) {\n this.logger.info(\n 'received network error response, erroring request...'\n )\n\n /**\n * There is no standardized error format for network errors\n * in Node.js. Instead, emit a generic TypeError.\n */\n this.errorWith(new TypeError('Network error'))\n\n return this\n }\n\n const responseClone = mockedResponse.clone()\n\n this.respondWith(mockedResponse)\n this.logger.info(\n mockedResponse.status,\n mockedResponse.statusText,\n '(MOCKED)'\n )\n\n callback?.()\n\n this.logger.info('emitting the custom \"response\" event...')\n this.emitter.emit('response', {\n response: responseClone,\n isMockedResponse: true,\n request: capturedRequest,\n requestId,\n })\n\n this.logger.info('request (mock) is completed')\n\n return this\n }\n\n this.logger.info('no mocked response received!')\n\n this.once('response-internal', (message: IncomingMessage) => {\n this.logger.info(message.statusCode, message.statusMessage)\n this.logger.info('original response headers:', message.headers)\n\n this.logger.info('emitting the custom \"response\" event...')\n this.emitter.emit('response', {\n response: createResponse(message),\n isMockedResponse: false,\n request: capturedRequest,\n requestId,\n })\n })\n\n return this.passthrough(chunk, encoding, callback)\n })\n\n return this\n }\n\n emit(event: string, ...data: any[]) {\n this.logger.info('emit: %s', event)\n\n if (event === 'response') {\n this.logger.info('found \"response\" event, cloning the response...')\n\n try {\n /**\n * Clone the response object when emitting the \"response\" event.\n * This prevents the response body stream from locking\n * and allows reading it twice:\n * 1. Internal \"response\" event from the observer.\n * 2. Any external response body listeners.\n * @see https://github.com/mswjs/interceptors/issues/161\n */\n const response = data[0] as IncomingMessage\n const firstClone = cloneIncomingMessage(response)\n const secondClone = cloneIncomingMessage(response)\n\n this.emit('response-internal', secondClone)\n\n this.logger.info(\n 'response successfully cloned, emitting \"response\" event...'\n )\n return super.emit(event, firstClone, ...data.slice(1))\n } catch (error) {\n this.logger.info('error when cloning response:', error)\n return super.emit(event, ...data)\n }\n }\n\n if (event === 'error') {\n const error = data[0] as NodeJS.ErrnoException\n const errorCode = error.code || ''\n\n this.logger.info('error:\\n', error)\n\n // Suppress only specific Node.js connection errors.\n if (NodeClientRequest.suppressErrorCodes.includes(errorCode)) {\n // Until we aren't sure whether the request will be\n // passthrough, capture the first emitted connection\n // error in case we have to replay it for this request.\n if (this.state < HttpClientInternalState.MockLookupEnd) {\n if (!this.capturedError) {\n this.capturedError = error\n this.logger.info('captured the first error:', this.capturedError)\n }\n return false\n }\n\n // Ignore any connection errors once we know the request\n // has been resolved with a mocked response. Don't capture\n // them as they won't ever be replayed.\n if (\n this.state === HttpClientInternalState.ResponseReceived &&\n this.responseType === 'mock'\n ) {\n return false\n }\n }\n }\n\n return super.emit(event, ...data)\n }\n\n /**\n * Performs the intercepted request as-is.\n * Replays the captured request body chunks,\n * still emits the internal events, and wraps\n * up the request with `super.end()`.\n */\n private passthrough(\n chunk: ClientRequestEndChunk | null,\n encoding?: BufferEncoding | null,\n callback?: ClientRequestEndCallback | null\n ): this {\n this.state = HttpClientInternalState.ResponseReceived\n this.responseType = 'passthrough'\n\n // Propagate previously captured errors.\n // For example, a ECONNREFUSED error when connecting to a non-existing host.\n if (this.capturedError) {\n this.emit('error', this.capturedError)\n return this\n }\n\n this.logger.info('writing request chunks...', this.chunks)\n\n // Write the request body chunks in the order of \".write()\" calls.\n // Note that no request body has been written prior to this point\n // in order to prevent the Socket to communicate with a potentially\n // existing server.\n for (const { chunk, encoding } of this.chunks) {\n if (encoding) {\n super.write(chunk, encoding)\n } else {\n super.write(chunk)\n }\n }\n\n this.once('error', (error) => {\n this.logger.info('original request error:', error)\n })\n\n this.once('abort', () => {\n this.logger.info('original request aborted!')\n })\n\n this.once('response-internal', (message: IncomingMessage) => {\n this.logger.info(message.statusCode, message.statusMessage)\n this.logger.info('original response headers:', message.headers)\n })\n\n this.logger.info('performing original request...')\n\n // This call signature is way too dynamic.\n return super.end(...[chunk, encoding as any, callback].filter(Boolean))\n }\n\n /**\n * Responds to this request instance using a mocked response.\n */\n private respondWith(mockedResponse: Response): void {\n this.logger.info('responding with a mocked response...', mockedResponse)\n\n this.state = HttpClientInternalState.ResponseReceived\n this.responseType = 'mock'\n\n /**\n * Mark the request as finished right before streaming back the response.\n * This is not entirely conventional but this will allow the consumer to\n * modify the outoging request in the interceptor.\n *\n * The request is finished when its headers and bodies have been sent.\n * @see https://nodejs.org/api/http.html#event-finish\n */\n Object.defineProperties(this, {\n writableFinished: { value: true },\n writableEnded: { value: true },\n })\n this.emit('finish')\n\n const { status, statusText, headers, body } = mockedResponse\n this.response.statusCode = status\n this.response.statusMessage = statusText || STATUS_CODES[status]\n\n // Try extracting the raw headers from the headers instance.\n // If not possible, fallback to the headers instance as-is.\n const rawHeaders = getRawFetchHeaders(headers) || headers\n\n if (rawHeaders) {\n this.response.headers = {}\n\n rawHeaders.forEach((headerValue, headerName) => {\n /**\n * @note Make sure that multi-value headers are appended correctly.\n */\n this.response.rawHeaders.push(headerName, headerValue)\n\n const insensitiveHeaderName = headerName.toLowerCase()\n const prevHeaders = this.response.headers[insensitiveHeaderName]\n this.response.headers[insensitiveHeaderName] = prevHeaders\n ? Array.prototype.concat([], prevHeaders, headerValue)\n : headerValue\n })\n }\n this.logger.info('mocked response headers ready:', headers)\n\n /**\n * Set the internal \"res\" property to the mocked \"OutgoingMessage\"\n * to make the \"ClientRequest\" instance think there's data received\n * from the socket.\n * @see https://github.com/nodejs/node/blob/9c405f2591f5833d0247ed0fafdcd68c5b14ce7a/lib/_http_client.js#L501\n *\n * Set the response immediately so the interceptor could stream data\n * chunks to the request client as they come in.\n */\n // @ts-ignore\n this.res = this.response\n this.emit('response', this.response)\n\n const isResponseStreamFinished = new DeferredPromise()\n\n const finishResponseStream = () => {\n this.logger.info('finished response stream!')\n\n // Push \"null\" to indicate that the response body is complete\n // and shouldn't be written to anymore.\n this.response.push(null)\n this.response.complete = true\n\n isResponseStreamFinished.resolve()\n }\n\n if (body) {\n const bodyReader = body.getReader()\n const readNextChunk = async (): Promise => {\n const { done, value } = await bodyReader.read()\n\n if (done) {\n finishResponseStream()\n return\n }\n\n this.response.emit('data', value)\n\n return readNextChunk()\n }\n\n readNextChunk()\n } else {\n finishResponseStream()\n }\n\n isResponseStreamFinished.then(() => {\n this.logger.info('finalizing response...')\n this.response.emit('end')\n this.terminate()\n\n this.logger.info('request complete!')\n })\n }\n\n private errorWith(error: Error): void {\n this.destroyed = true\n this.emit('error', error)\n this.terminate()\n }\n\n /**\n * Terminates a pending request.\n */\n private terminate(): void {\n /**\n * @note Some request clients (e.g. Octokit) create a ClientRequest\n * in a way that it has no Agent set. Now, whether that's correct is\n * debatable, but we should still handle this case gracefully.\n * @see https://github.com/mswjs/interceptors/issues/304\n */\n // @ts-ignore\n this.agent?.destroy()\n }\n}\n","import { Logger } from '@open-draft/logger'\n\nconst logger = new Logger('utils getUrlByRequestOptions')\n\nexport type ClientRequestEndChunk = string | Buffer\nexport type ClientRequestEndCallback = () => void\n\ntype HttpRequestEndArgs =\n | []\n | [ClientRequestEndCallback]\n | [ClientRequestEndChunk, ClientRequestEndCallback?]\n | [ClientRequestEndChunk, BufferEncoding, ClientRequestEndCallback?]\n\ntype NormalizedHttpRequestEndParams = [\n ClientRequestEndChunk | null,\n BufferEncoding | null,\n ClientRequestEndCallback | null\n]\n\n/**\n * Normalizes a list of arguments given to the `ClientRequest.end()`\n * method to always include `chunk`, `encoding`, and `callback`.\n */\nexport function normalizeClientRequestEndArgs(\n ...args: HttpRequestEndArgs\n): NormalizedHttpRequestEndParams {\n logger.info('arguments', args)\n const normalizedArgs = new Array(3)\n .fill(null)\n .map((value, index) => args[index] || value)\n\n normalizedArgs.sort((a, b) => {\n // If first element is a function, move it rightwards.\n if (typeof a === 'function') {\n return 1\n }\n\n // If second element is a function, move the first leftwards.\n if (typeof b === 'function') {\n return -1\n }\n\n // If both elements are strings, preserve their original index.\n if (typeof a === 'string' && typeof b === 'string') {\n return normalizedArgs.indexOf(a) - normalizedArgs.indexOf(b)\n }\n\n return 0\n })\n\n logger.info('normalized args', normalizedArgs)\n return normalizedArgs as NormalizedHttpRequestEndParams\n}\n","import { Logger } from '@open-draft/logger'\n\nconst logger = new Logger('http normalizeWriteArgs')\n\nexport type ClientRequestWriteCallback = (error?: Error | null) => void\nexport type ClientRequestWriteArgs = [\n chunk: string | Buffer,\n encoding?: BufferEncoding | ClientRequestWriteCallback,\n callback?: ClientRequestWriteCallback\n]\n\nexport type NormalizedClientRequestWriteArgs = [\n chunk: string | Buffer,\n encoding?: BufferEncoding,\n callback?: ClientRequestWriteCallback\n]\n\nexport function normalizeClientRequestWriteArgs(\n args: ClientRequestWriteArgs\n): NormalizedClientRequestWriteArgs {\n logger.info('normalizing ClientRequest.write arguments...', args)\n\n const chunk = args[0]\n const encoding =\n typeof args[1] === 'string' ? (args[1] as BufferEncoding) : undefined\n const callback = typeof args[1] === 'function' ? args[1] : args[2]\n\n const writeArgs: NormalizedClientRequestWriteArgs = [\n chunk,\n encoding,\n callback,\n ]\n logger.info(\n 'successfully normalized ClientRequest.write arguments:',\n writeArgs\n )\n\n return writeArgs\n}\n","import { IncomingMessage } from 'http'\nimport { PassThrough } from 'stream'\n\nexport const IS_CLONE = Symbol('isClone')\n\nexport interface ClonedIncomingMessage extends IncomingMessage {\n [IS_CLONE]: boolean\n}\n\n/**\n * Clones a given `http.IncomingMessage` instance.\n */\nexport function cloneIncomingMessage(\n message: IncomingMessage\n): ClonedIncomingMessage {\n const clone = message.pipe(new PassThrough())\n\n // Inherit all direct \"IncomingMessage\" properties.\n inheritProperties(message, clone)\n\n // Deeply inherit the message prototypes (Readable, Stream, EventEmitter, etc.).\n const clonedPrototype = Object.create(IncomingMessage.prototype)\n getPrototypes(clone).forEach((prototype) => {\n inheritProperties(prototype, clonedPrototype)\n })\n Object.setPrototypeOf(clone, clonedPrototype)\n\n Object.defineProperty(clone, IS_CLONE, {\n enumerable: true,\n value: true,\n })\n\n return clone as unknown as ClonedIncomingMessage\n}\n\n/**\n * Returns a list of all prototypes the given object extends.\n */\nfunction getPrototypes(source: object): object[] {\n const prototypes: object[] = []\n let current = source\n\n while ((current = Object.getPrototypeOf(current))) {\n prototypes.push(current)\n }\n\n return prototypes\n}\n\n/**\n * Inherits a given target object properties and symbols\n * onto the given source object.\n * @param source Object which should acquire properties.\n * @param target Object to inherit the properties from.\n */\nfunction inheritProperties(source: object, target: object): void {\n const properties = [\n ...Object.getOwnPropertyNames(source),\n ...Object.getOwnPropertySymbols(source),\n ]\n\n for (const property of properties) {\n if (target.hasOwnProperty(property)) {\n continue\n }\n\n const descriptor = Object.getOwnPropertyDescriptor(source, property)\n if (!descriptor) {\n continue\n }\n\n Object.defineProperty(target, property, descriptor)\n }\n}\n","import type { IncomingHttpHeaders, IncomingMessage } from 'http'\nimport { isResponseWithoutBody } from '../../../utils/responseUtils'\n\n/**\n * Creates a Fetch API `Response` instance from the given\n * `http.IncomingMessage` instance.\n */\nexport function createResponse(message: IncomingMessage): Response {\n const responseBodyOrNull = isResponseWithoutBody(message.statusCode || 200)\n ? null\n : new ReadableStream({\n start(controller) {\n message.on('data', (chunk) => controller.enqueue(chunk))\n message.on('end', () => controller.close())\n\n /**\n * @todo Should also listen to the \"error\" on the message\n * and forward it to the controller. Otherwise the stream\n * will pend indefinitely.\n */\n },\n })\n\n return new Response(responseBodyOrNull, {\n status: message.statusCode,\n statusText: message.statusMessage,\n headers: createHeadersFromIncomingHttpHeaders(message.headers),\n })\n}\n\nfunction createHeadersFromIncomingHttpHeaders(\n httpHeaders: IncomingHttpHeaders\n): Headers {\n const headers = new Headers()\n\n for (const headerName in httpHeaders) {\n const headerValues = httpHeaders[headerName]\n\n if (typeof headerValues === 'undefined') {\n continue\n }\n\n if (Array.isArray(headerValues)) {\n headerValues.forEach((headerValue) => {\n headers.append(headerName, headerValue)\n })\n\n continue\n }\n\n headers.set(headerName, headerValues)\n }\n\n return headers\n}\n","import type { NodeClientRequest } from '../NodeClientRequest'\n\n/**\n * Creates a Fetch API `Request` instance from the given `http.ClientRequest`.\n */\nexport function createRequest(clientRequest: NodeClientRequest): Request {\n const headers = new Headers()\n\n const outgoingHeaders = clientRequest.getHeaders()\n for (const headerName in outgoingHeaders) {\n const headerValue = outgoingHeaders[headerName]\n\n if (typeof headerValue === 'undefined') {\n continue\n }\n\n const valuesList = Array.prototype.concat([], headerValue)\n for (const value of valuesList) {\n headers.append(headerName, value.toString())\n }\n }\n\n /**\n * Translate the authentication from the request URL to\n * the request \"Authorization\" header.\n * @see https://github.com/mswjs/interceptors/issues/438\n */\n if (clientRequest.url.username || clientRequest.url.password) {\n const username = decodeURIComponent(clientRequest.url.username || '')\n const password = decodeURIComponent(clientRequest.url.password || '')\n const auth = `${username}:${password}`\n headers.set('Authorization', `Basic ${btoa(auth)}`)\n\n // Remove the credentials from the URL since you cannot\n // construct a Request instance with such a URL.\n clientRequest.url.username = ''\n clientRequest.url.password = ''\n }\n\n const method = clientRequest.method || 'GET'\n\n return new Request(clientRequest.url, {\n method,\n headers,\n credentials: 'same-origin',\n body:\n method === 'HEAD' || method === 'GET'\n ? null\n : clientRequest.requestBuffer,\n })\n}\n","/**\n * Returns the value behind the symbol with the given name.\n */\nexport function getValueBySymbol(\n symbolName: string,\n source: object\n): T | undefined {\n const ownSymbols = Object.getOwnPropertySymbols(source)\n\n const symbol = ownSymbols.find((symbol) => {\n return symbol.description === symbolName\n })\n\n if (symbol) {\n return Reflect.get(source, symbol)\n }\n\n return\n}\n","/**\n * Determines if a given value is an instance of object.\n */\nexport function isObject(value: any, loose = false): value is T {\n return loose\n ? Object.prototype.toString.call(value).startsWith('[object ')\n : Object.prototype.toString.call(value) === '[object Object]'\n}\n","import { getValueBySymbol } from './getValueBySymbol'\nimport { isObject } from './isObject'\n\ntype RawHeadersMap = Map\ntype HeadersMapHeader = { name: string; value: string }\n\n/**\n * Returns raw headers from the given `Headers` instance.\n * @example\n * const headers = new Headers([\n * ['X-HeadeR-NamE', 'Value']\n * ])\n * getRawFetchHeaders(headers)\n * // { 'X-HeadeR-NamE': 'Value' }\n */\nexport function getRawFetchHeaders(\n headers: Headers\n): RawHeadersMap | undefined {\n const headersList = getValueBySymbol('headers list', headers)\n\n if (!headersList) {\n return\n }\n\n const headersMap = getValueBySymbol<\n Map | Map\n >('headers map', headersList)\n\n /**\n * @note Older versions of Node.js (e.g. 18.8.0) keep headers map\n * as Map without any means to tap\n * into raw header values. Detect that and return undefined.\n */\n if (!headersMap || !isHeadersMapWithRawHeaderNames(headersMap)) {\n return\n }\n\n // Raw headers is a map of { rawHeaderName: rawHeaderValue }\n const rawHeaders: RawHeadersMap = new Map()\n\n headersMap.forEach(({ name, value }) => {\n rawHeaders.set(name, value)\n })\n\n return rawHeaders\n}\n\nfunction isHeadersMapWithRawHeaderNames(\n headersMap: Map | Map\n): headersMap is Map {\n return Array.from(\n headersMap.values() as Iterable\n ).every((value) => {\n return isObject(value) && 'name' in value\n })\n}\n","export function isNodeLikeError(\n error: unknown\n): error is NodeJS.ErrnoException {\n if (error == null) {\n return false\n }\n\n if (!(error instanceof Error)) {\n return false\n }\n\n return 'code' in error && 'errno' in error\n}\n","import {\n Agent as HttpAgent,\n globalAgent as httpGlobalAgent,\n IncomingMessage,\n} from 'http'\nimport {\n RequestOptions,\n Agent as HttpsAgent,\n globalAgent as httpsGlobalAgent,\n} from 'https'\nimport { Url as LegacyURL, parse as parseUrl } from 'url'\nimport { Logger } from '@open-draft/logger'\nimport { getRequestOptionsByUrl } from '../../../utils/getRequestOptionsByUrl'\nimport {\n ResolvedRequestOptions,\n getUrlByRequestOptions,\n} from '../../../utils/getUrlByRequestOptions'\nimport { cloneObject } from '../../../utils/cloneObject'\nimport { isObject } from '../../../utils/isObject'\n\nconst logger = new Logger('http normalizeClientRequestArgs')\n\nexport type HttpRequestCallback = (response: IncomingMessage) => void\n\nexport type ClientRequestArgs =\n // Request without any arguments is also possible.\n | []\n | [string | URL | LegacyURL, HttpRequestCallback?]\n | [string | URL | LegacyURL, RequestOptions, HttpRequestCallback?]\n | [RequestOptions, HttpRequestCallback?]\n\nfunction resolveRequestOptions(\n args: ClientRequestArgs,\n url: URL\n): RequestOptions {\n // Calling `fetch` provides only URL to `ClientRequest`\n // without any `RequestOptions` or callback.\n if (typeof args[1] === 'undefined' || typeof args[1] === 'function') {\n logger.info('request options not provided, deriving from the url', url)\n return getRequestOptionsByUrl(url)\n }\n\n if (args[1]) {\n logger.info('has custom RequestOptions!', args[1])\n const requestOptionsFromUrl = getRequestOptionsByUrl(url)\n\n logger.info('derived RequestOptions from the URL:', requestOptionsFromUrl)\n\n /**\n * Clone the request options to lock their state\n * at the moment they are provided to `ClientRequest`.\n * @see https://github.com/mswjs/interceptors/issues/86\n */\n logger.info('cloning RequestOptions...')\n const clonedRequestOptions = cloneObject(args[1])\n logger.info('successfully cloned RequestOptions!', clonedRequestOptions)\n\n return {\n ...requestOptionsFromUrl,\n ...clonedRequestOptions,\n }\n }\n\n logger.info('using an empty object as request options')\n return {} as RequestOptions\n}\n\n/**\n * Overrides the given `URL` instance with the explicit properties provided\n * on the `RequestOptions` object. The options object takes precedence,\n * and will replace URL properties like \"host\", \"path\", and \"port\", if specified.\n */\nfunction overrideUrlByRequestOptions(url: URL, options: RequestOptions): URL {\n url.host = options.host || url.host\n url.hostname = options.hostname || url.hostname\n url.port = options.port ? options.port.toString() : url.port\n\n if (options.path) {\n const parsedOptionsPath = parseUrl(options.path, false)\n url.pathname = parsedOptionsPath.pathname || ''\n url.search = parsedOptionsPath.search || ''\n }\n\n return url\n}\n\nfunction resolveCallback(\n args: ClientRequestArgs\n): HttpRequestCallback | undefined {\n return typeof args[1] === 'function' ? args[1] : args[2]\n}\n\nexport type NormalizedClientRequestArgs = [\n url: URL,\n options: ResolvedRequestOptions,\n callback?: HttpRequestCallback\n]\n\n/**\n * Normalizes parameters given to a `http.request` call\n * so it always has a `URL` and `RequestOptions`.\n */\nexport function normalizeClientRequestArgs(\n defaultProtocol: string,\n ...args: ClientRequestArgs\n): NormalizedClientRequestArgs {\n let url: URL\n let options: ResolvedRequestOptions\n let callback: HttpRequestCallback | undefined\n\n logger.info('arguments', args)\n logger.info('using default protocol:', defaultProtocol)\n\n // Support \"http.request()\" calls without any arguments.\n // That call results in a \"GET http://localhost\" request.\n if (args.length === 0) {\n const url = new URL('http://localhost')\n const options = resolveRequestOptions(args, url)\n return [url, options]\n }\n\n // Convert a url string into a URL instance\n // and derive request options from it.\n if (typeof args[0] === 'string') {\n logger.info('first argument is a location string:', args[0])\n\n url = new URL(args[0])\n logger.info('created a url:', url)\n\n const requestOptionsFromUrl = getRequestOptionsByUrl(url)\n logger.info('request options from url:', requestOptionsFromUrl)\n\n options = resolveRequestOptions(args, url)\n logger.info('resolved request options:', options)\n\n callback = resolveCallback(args)\n }\n // Handle a given URL instance as-is\n // and derive request options from it.\n else if (args[0] instanceof URL) {\n url = args[0]\n logger.info('first argument is a URL:', url)\n\n // Check if the second provided argument is RequestOptions.\n // If it is, check if \"options.path\" was set and rewrite it\n // on the input URL.\n // Do this before resolving options from the URL below\n // to prevent query string from being duplicated in the path.\n if (typeof args[1] !== 'undefined' && isObject(args[1])) {\n url = overrideUrlByRequestOptions(url, args[1])\n }\n\n options = resolveRequestOptions(args, url)\n logger.info('derived request options:', options)\n\n callback = resolveCallback(args)\n }\n // Handle a legacy URL instance and re-normalize from either a RequestOptions object\n // or a WHATWG URL.\n else if ('hash' in args[0] && !('method' in args[0])) {\n const [legacyUrl] = args\n logger.info('first argument is a legacy URL:', legacyUrl)\n\n if (legacyUrl.hostname === null) {\n /**\n * We are dealing with a relative url, so use the path as an \"option\" and\n * merge in any existing options, giving priority to exising options -- i.e. a path in any\n * existing options will take precedence over the one contained in the url. This is consistent\n * with the behaviour in ClientRequest.\n * @see https://github.com/nodejs/node/blob/d84f1312915fe45fe0febe888db692c74894c382/lib/_http_client.js#L122\n */\n logger.info('given legacy URL is relative (no hostname)')\n\n return isObject(args[1])\n ? normalizeClientRequestArgs(\n defaultProtocol,\n { path: legacyUrl.path, ...args[1] },\n args[2]\n )\n : normalizeClientRequestArgs(\n defaultProtocol,\n { path: legacyUrl.path },\n args[1] as HttpRequestCallback\n )\n }\n\n logger.info('given legacy url is absolute')\n\n // We are dealing with an absolute URL, so convert to WHATWG and try again.\n const resolvedUrl = new URL(legacyUrl.href)\n\n return args[1] === undefined\n ? normalizeClientRequestArgs(defaultProtocol, resolvedUrl)\n : typeof args[1] === 'function'\n ? normalizeClientRequestArgs(defaultProtocol, resolvedUrl, args[1])\n : normalizeClientRequestArgs(\n defaultProtocol,\n resolvedUrl,\n args[1],\n args[2]\n )\n }\n // Handle a given \"RequestOptions\" object as-is\n // and derive the URL instance from it.\n else if (isObject(args[0])) {\n options = args[0] as any\n logger.info('first argument is RequestOptions:', options)\n\n // When handling a \"RequestOptions\" object without an explicit \"protocol\",\n // infer the protocol from the request issuing module (http/https).\n options.protocol = options.protocol || defaultProtocol\n logger.info('normalized request options:', options)\n\n url = getUrlByRequestOptions(options)\n logger.info('created a URL from RequestOptions:', url.href)\n\n callback = resolveCallback(args)\n } else {\n throw new Error(\n `Failed to construct ClientRequest with these parameters: ${args}`\n )\n }\n\n options.protocol = options.protocol || url.protocol\n options.method = options.method || 'GET'\n\n /**\n * Infer a fallback agent from the URL protocol.\n * The interception is done on the \"ClientRequest\" level (\"NodeClientRequest\")\n * and it may miss the correct agent. Always align the agent\n * with the URL protocol, if not provided.\n *\n * @note Respect the \"agent: false\" value.\n */\n if (typeof options.agent === 'undefined') {\n const agent =\n options.protocol === 'https:'\n ? new HttpsAgent({\n rejectUnauthorized: options.rejectUnauthorized,\n })\n : new HttpAgent()\n\n options.agent = agent\n logger.info('resolved fallback agent:', agent)\n }\n\n /**\n * Ensure that the default Agent is always set.\n * This prevents the protocol mismatch for requests with { agent: false },\n * where the global Agent is inferred.\n * @see https://github.com/mswjs/msw/issues/1150\n * @see https://github.com/nodejs/node/blob/418ff70b810f0e7112d48baaa72932a56cfa213b/lib/_http_client.js#L130\n * @see https://github.com/nodejs/node/blob/418ff70b810f0e7112d48baaa72932a56cfa213b/lib/_http_client.js#L157-L159\n */\n if (!options._defaultAgent) {\n logger.info(\n 'has no default agent, setting the default agent for \"%s\"',\n options.protocol\n )\n\n options._defaultAgent =\n options.protocol === 'https:' ? httpsGlobalAgent : httpGlobalAgent\n }\n\n logger.info('successfully resolved url:', url.href)\n logger.info('successfully resolved options:', options)\n logger.info('successfully resolved callback:', callback)\n\n return [url, options, callback]\n}\n","import { RequestOptions } from 'http'\n\n/**\n * Converts a URL instance into the RequestOptions object expected by\n * the `ClientRequest` class.\n * @see https://github.com/nodejs/node/blob/908292cf1f551c614a733d858528ffb13fb3a524/lib/internal/url.js#L1257\n */\nexport function getRequestOptionsByUrl(url: URL): RequestOptions {\n const options: RequestOptions = {\n method: 'GET',\n protocol: url.protocol,\n hostname:\n typeof url.hostname === 'string' && url.hostname.startsWith('[')\n ? url.hostname.slice(1, -1)\n : url.hostname,\n host: url.host,\n path: `${url.pathname}${url.search || ''}`,\n }\n\n if (!!url.port) {\n options.port = Number(url.port)\n }\n\n if (url.username || url.password) {\n options.auth = `${url.username}:${url.password}`\n }\n\n return options\n}\n","import { Agent } from 'http'\nimport { RequestOptions, Agent as HttpsAgent } from 'https'\nimport { Logger } from '@open-draft/logger'\n\nconst logger = new Logger('utils getUrlByRequestOptions')\n\n// Request instance constructed by the \"request\" library\n// has a \"self\" property that has a \"uri\" field. This is\n// reproducible by performing a \"XMLHttpRequest\" request in JSDOM.\nexport interface RequestSelf {\n uri?: URL\n}\n\nexport type ResolvedRequestOptions = RequestOptions & RequestSelf\n\nexport const DEFAULT_PATH = '/'\nconst DEFAULT_PROTOCOL = 'http:'\nconst DEFAULT_HOSTNAME = 'localhost'\nconst SSL_PORT = 443\n\nfunction getAgent(\n options: ResolvedRequestOptions\n): Agent | HttpsAgent | undefined {\n return options.agent instanceof Agent ? options.agent : undefined\n}\n\nfunction getProtocolByRequestOptions(options: ResolvedRequestOptions): string {\n if (options.protocol) {\n return options.protocol\n }\n\n const agent = getAgent(options)\n const agentProtocol = (agent as RequestOptions)?.protocol\n\n if (agentProtocol) {\n return agentProtocol\n }\n\n const port = getPortByRequestOptions(options)\n const isSecureRequest = options.cert || port === SSL_PORT\n\n return isSecureRequest ? 'https:' : options.uri?.protocol || DEFAULT_PROTOCOL\n}\n\nfunction getPortByRequestOptions(\n options: ResolvedRequestOptions\n): number | undefined {\n // Use the explicitly provided port.\n if (options.port) {\n return Number(options.port)\n }\n\n // Otherwise, try to resolve port from the agent.\n const agent = getAgent(options)\n\n if ((agent as HttpsAgent)?.options.port) {\n return Number((agent as HttpsAgent).options.port)\n }\n\n if ((agent as RequestOptions)?.defaultPort) {\n return Number((agent as RequestOptions).defaultPort)\n }\n\n // Lastly, return undefined indicating that the port\n // must inferred from the protocol. Do not infer it here.\n return undefined\n}\n\ninterface RequestAuth {\n username: string\n password: string\n}\n\nfunction getAuthByRequestOptions(\n options: ResolvedRequestOptions\n): RequestAuth | undefined {\n if (options.auth) {\n const [username, password] = options.auth.split(':')\n return { username, password }\n }\n}\n\n/**\n * Returns true if host looks like an IPv6 address without surrounding brackets\n * It assumes any host containing `:` is definitely not IPv4 and probably IPv6,\n * but note that this could include invalid IPv6 addresses as well.\n */\nfunction isRawIPv6Address(host: string): boolean {\n return host.includes(':') && !host.startsWith('[') && !host.endsWith(']')\n}\n\nfunction getHostname(options: ResolvedRequestOptions): string | undefined {\n let host = options.hostname || options.host\n\n if (host) {\n if (isRawIPv6Address(host)) {\n host = `[${host}]`\n }\n\n // Check the presence of the port, and if it's present,\n // remove it from the host, returning a hostname.\n return new URL(`http://${host}`).hostname\n }\n\n return DEFAULT_HOSTNAME\n}\n\n/**\n * Creates a `URL` instance from a given `RequestOptions` object.\n */\nexport function getUrlByRequestOptions(options: ResolvedRequestOptions): URL {\n logger.info('request options', options)\n\n if (options.uri) {\n logger.info(\n 'constructing url from explicitly provided \"options.uri\": %s',\n options.uri\n )\n return new URL(options.uri.href)\n }\n\n logger.info('figuring out url from request options...')\n\n const protocol = getProtocolByRequestOptions(options)\n logger.info('protocol', protocol)\n\n const port = getPortByRequestOptions(options)\n logger.info('port', port)\n\n const hostname = getHostname(options)\n logger.info('hostname', hostname)\n\n const path = options.path || DEFAULT_PATH\n logger.info('path', path)\n\n const credentials = getAuthByRequestOptions(options)\n logger.info('credentials', credentials)\n\n const authString = credentials\n ? `${credentials.username}:${credentials.password}@`\n : ''\n logger.info('auth string:', authString)\n\n const portString = typeof port !== 'undefined' ? `:${port}` : ''\n const url = new URL(`${protocol}//${hostname}${portString}${path}`)\n url.username = credentials?.username || ''\n url.password = credentials?.password || ''\n\n logger.info('created url:', url)\n\n return url\n}\n","import { Logger } from '@open-draft/logger'\n\nconst logger = new Logger('cloneObject')\n\nfunction isPlainObject(obj?: Record): boolean {\n logger.info('is plain object?', obj)\n\n if (obj == null || !obj.constructor?.name) {\n logger.info('given object is undefined, not a plain object...')\n return false\n }\n\n logger.info('checking the object constructor:', obj.constructor.name)\n return obj.constructor.name === 'Object'\n}\n\nexport function cloneObject>(\n obj: ObjectType\n): ObjectType {\n logger.info('cloning object:', obj)\n\n const enumerableProperties = Object.entries(obj).reduce>(\n (acc, [key, value]) => {\n logger.info('analyzing key-value pair:', key, value)\n\n // Recursively clone only plain objects, omitting class instances.\n acc[key] = isPlainObject(value) ? cloneObject(value) : value\n return acc\n },\n {}\n )\n\n return isPlainObject(obj)\n ? enumerableProperties\n : Object.assign(Object.getPrototypeOf(obj), enumerableProperties)\n}\n","import { ClientRequest } from 'node:http'\nimport {\n NodeClientOptions,\n NodeClientRequest,\n Protocol,\n} from './NodeClientRequest'\nimport {\n ClientRequestArgs,\n normalizeClientRequestArgs,\n} from './utils/normalizeClientRequestArgs'\n\nexport function get(protocol: Protocol, options: NodeClientOptions) {\n return function interceptorsHttpGet(\n ...args: ClientRequestArgs\n ): ClientRequest {\n const clientRequestArgs = normalizeClientRequestArgs(\n `${protocol}:`,\n ...args\n )\n const request = new NodeClientRequest(clientRequestArgs, options)\n\n /**\n * @note https://nodejs.org/api/http.html#httpgetoptions-callback\n * \"http.get\" sets the method to \"GET\" and calls \"req.end()\" automatically.\n */\n request.end()\n\n return request\n }\n}\n","import { ClientRequest } from 'http'\nimport { Logger } from '@open-draft/logger'\nimport {\n NodeClientOptions,\n NodeClientRequest,\n Protocol,\n} from './NodeClientRequest'\nimport {\n normalizeClientRequestArgs,\n ClientRequestArgs,\n} from './utils/normalizeClientRequestArgs'\n\nconst logger = new Logger('http request')\n\nexport function request(protocol: Protocol, options: NodeClientOptions) {\n return function interceptorsHttpRequest(\n ...args: ClientRequestArgs\n ): ClientRequest {\n logger.info('request call (protocol \"%s\"):', protocol, args)\n\n const clientRequestArgs = normalizeClientRequestArgs(\n `${protocol}:`,\n ...args\n )\n return new NodeClientRequest(clientRequestArgs, options)\n }\n}\n"],"mappings":"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","names":["IncomingMessage","Logger","logger","symbol","IncomingMessage","chunk","encoding","Logger","Logger","logger","Logger","logger","logger","Logger","url","options","request","Logger","logger","Logger","logger"]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/chunk-E4AC7YAC.js b/node_modules/@mswjs/interceptors/lib/node/chunk-E4AC7YAC.js new file mode 100644 index 0000000000000000000000000000000000000000..87026474bec5ba86309b0270d0455d5cf7234357 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/chunk-E4AC7YAC.js @@ -0,0 +1,215 @@ +"use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/Interceptor.ts +var _logger = require('@open-draft/logger'); +var _stricteventemitter = require('strict-event-emitter'); +var INTERNAL_REQUEST_ID_HEADER_NAME = "x-interceptors-internal-request-id"; +function getGlobalSymbol(symbol) { + return ( + // @ts-ignore https://github.com/Microsoft/TypeScript/issues/24587 + globalThis[symbol] || void 0 + ); +} +function setGlobalSymbol(symbol, value) { + globalThis[symbol] = value; +} +function deleteGlobalSymbol(symbol) { + delete globalThis[symbol]; +} +var InterceptorReadyState = /* @__PURE__ */ ((InterceptorReadyState2) => { + InterceptorReadyState2["INACTIVE"] = "INACTIVE"; + InterceptorReadyState2["APPLYING"] = "APPLYING"; + InterceptorReadyState2["APPLIED"] = "APPLIED"; + InterceptorReadyState2["DISPOSING"] = "DISPOSING"; + InterceptorReadyState2["DISPOSED"] = "DISPOSED"; + return InterceptorReadyState2; +})(InterceptorReadyState || {}); +var Interceptor = class { + constructor(symbol) { + this.symbol = symbol; + this.readyState = "INACTIVE" /* INACTIVE */; + this.emitter = new (0, _stricteventemitter.Emitter)(); + this.subscriptions = []; + this.logger = new (0, _logger.Logger)(symbol.description); + this.emitter.setMaxListeners(0); + this.logger.info("constructing the interceptor..."); + } + /** + * Determine if this interceptor can be applied + * in the current environment. + */ + checkEnvironment() { + return true; + } + /** + * Apply this interceptor to the current process. + * Returns an already running interceptor instance if it's present. + */ + apply() { + const logger = this.logger.extend("apply"); + logger.info("applying the interceptor..."); + if (this.readyState === "APPLIED" /* APPLIED */) { + logger.info("intercepted already applied!"); + return; + } + const shouldApply = this.checkEnvironment(); + if (!shouldApply) { + logger.info("the interceptor cannot be applied in this environment!"); + return; + } + this.readyState = "APPLYING" /* APPLYING */; + const runningInstance = this.getInstance(); + if (runningInstance) { + logger.info("found a running instance, reusing..."); + this.on = (event, listener) => { + logger.info('proxying the "%s" listener', event); + runningInstance.emitter.addListener(event, listener); + this.subscriptions.push(() => { + runningInstance.emitter.removeListener(event, listener); + logger.info('removed proxied "%s" listener!', event); + }); + return this; + }; + this.readyState = "APPLIED" /* APPLIED */; + return; + } + logger.info("no running instance found, setting up a new instance..."); + this.setup(); + this.setInstance(); + this.readyState = "APPLIED" /* APPLIED */; + } + /** + * Setup the module augments and stubs necessary for this interceptor. + * This method is not run if there's a running interceptor instance + * to prevent instantiating an interceptor multiple times. + */ + setup() { + } + /** + * Listen to the interceptor's public events. + */ + on(event, listener) { + const logger = this.logger.extend("on"); + if (this.readyState === "DISPOSING" /* DISPOSING */ || this.readyState === "DISPOSED" /* DISPOSED */) { + logger.info("cannot listen to events, already disposed!"); + return this; + } + logger.info('adding "%s" event listener:', event, listener); + this.emitter.on(event, listener); + return this; + } + once(event, listener) { + this.emitter.once(event, listener); + return this; + } + off(event, listener) { + this.emitter.off(event, listener); + return this; + } + removeAllListeners(event) { + this.emitter.removeAllListeners(event); + return this; + } + /** + * Disposes of any side-effects this interceptor has introduced. + */ + dispose() { + const logger = this.logger.extend("dispose"); + if (this.readyState === "DISPOSED" /* DISPOSED */) { + logger.info("cannot dispose, already disposed!"); + return; + } + logger.info("disposing the interceptor..."); + this.readyState = "DISPOSING" /* DISPOSING */; + if (!this.getInstance()) { + logger.info("no interceptors running, skipping dispose..."); + return; + } + this.clearInstance(); + logger.info("global symbol deleted:", getGlobalSymbol(this.symbol)); + if (this.subscriptions.length > 0) { + logger.info("disposing of %d subscriptions...", this.subscriptions.length); + for (const dispose of this.subscriptions) { + dispose(); + } + this.subscriptions = []; + logger.info("disposed of all subscriptions!", this.subscriptions.length); + } + this.emitter.removeAllListeners(); + logger.info("destroyed the listener!"); + this.readyState = "DISPOSED" /* DISPOSED */; + } + getInstance() { + var _a; + const instance = getGlobalSymbol(this.symbol); + this.logger.info("retrieved global instance:", (_a = instance == null ? void 0 : instance.constructor) == null ? void 0 : _a.name); + return instance; + } + setInstance() { + setGlobalSymbol(this.symbol, this); + this.logger.info("set global instance!", this.symbol.description); + } + clearInstance() { + deleteGlobalSymbol(this.symbol); + this.logger.info("cleared global instance!", this.symbol.description); + } +}; + +// src/createRequestId.ts +function createRequestId() { + return Math.random().toString(16).slice(2); +} + +// src/utils/isPropertyAccessible.ts +function isPropertyAccessible(obj, key) { + try { + obj[key]; + return true; + } catch (e) { + return false; + } +} + +// src/utils/responseUtils.ts +var RESPONSE_STATUS_CODES_WITHOUT_BODY = /* @__PURE__ */ new Set([ + 101, + 103, + 204, + 205, + 304 +]); +function isResponseWithoutBody(status) { + return RESPONSE_STATUS_CODES_WITHOUT_BODY.has(status); +} +function createServerErrorResponse(body) { + return new Response( + JSON.stringify( + body instanceof Error ? { + name: body.name, + message: body.message, + stack: body.stack + } : body + ), + { + status: 500, + statusText: "Unhandled Exception", + headers: { + "Content-Type": "application/json" + } + } + ); +} +function isResponseError(response) { + return isPropertyAccessible(response, "type") && response.type === "error"; +} + + + + + + + + + + + +exports.INTERNAL_REQUEST_ID_HEADER_NAME = INTERNAL_REQUEST_ID_HEADER_NAME; exports.getGlobalSymbol = getGlobalSymbol; exports.deleteGlobalSymbol = deleteGlobalSymbol; exports.InterceptorReadyState = InterceptorReadyState; exports.Interceptor = Interceptor; exports.createRequestId = createRequestId; exports.isResponseWithoutBody = isResponseWithoutBody; exports.createServerErrorResponse = createServerErrorResponse; exports.isResponseError = isResponseError; +//# sourceMappingURL=chunk-E4AC7YAC.js.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/chunk-E4AC7YAC.js.map b/node_modules/@mswjs/interceptors/lib/node/chunk-E4AC7YAC.js.map new file mode 100644 index 0000000000000000000000000000000000000000..86659c668bfb26f0b4362e8972d4a7c4e9f10853 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/chunk-E4AC7YAC.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/Interceptor.ts","../../src/createRequestId.ts","../../src/utils/isPropertyAccessible.ts","../../src/utils/responseUtils.ts"],"names":["InterceptorReadyState"],"mappings":"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","sourcesContent":["import { Logger } from '@open-draft/logger'\nimport { Emitter, Listener } from 'strict-event-emitter'\n\nexport type InterceptorEventMap = Record\nexport type InterceptorSubscription = () => void\n\n/**\n * Request header name to detect when a single request\n * is being handled by nested interceptors (XHR -> ClientRequest).\n * Obscure by design to prevent collisions with user-defined headers.\n * Ideally, come up with the Interceptor-level mechanism for this.\n * @see https://github.com/mswjs/interceptors/issues/378\n */\nexport const INTERNAL_REQUEST_ID_HEADER_NAME =\n 'x-interceptors-internal-request-id'\n\nexport function getGlobalSymbol(symbol: Symbol): V | undefined {\n return (\n // @ts-ignore https://github.com/Microsoft/TypeScript/issues/24587\n globalThis[symbol] || undefined\n )\n}\n\nfunction setGlobalSymbol(symbol: Symbol, value: any): void {\n // @ts-ignore\n globalThis[symbol] = value\n}\n\nexport function deleteGlobalSymbol(symbol: Symbol): void {\n // @ts-ignore\n delete globalThis[symbol]\n}\n\nexport enum InterceptorReadyState {\n INACTIVE = 'INACTIVE',\n APPLYING = 'APPLYING',\n APPLIED = 'APPLIED',\n DISPOSING = 'DISPOSING',\n DISPOSED = 'DISPOSED',\n}\n\nexport type ExtractEventNames> =\n Events extends Record ? EventName : never\n\nexport class Interceptor {\n protected emitter: Emitter\n protected subscriptions: Array\n protected logger: Logger\n\n public readyState: InterceptorReadyState\n\n constructor(private readonly symbol: symbol) {\n this.readyState = InterceptorReadyState.INACTIVE\n\n this.emitter = new Emitter()\n this.subscriptions = []\n this.logger = new Logger(symbol.description!)\n\n // Do not limit the maximum number of listeners\n // so not to limit the maximum amount of parallel events emitted.\n this.emitter.setMaxListeners(0)\n\n this.logger.info('constructing the interceptor...')\n }\n\n /**\n * Determine if this interceptor can be applied\n * in the current environment.\n */\n protected checkEnvironment(): boolean {\n return true\n }\n\n /**\n * Apply this interceptor to the current process.\n * Returns an already running interceptor instance if it's present.\n */\n public apply(): void {\n const logger = this.logger.extend('apply')\n logger.info('applying the interceptor...')\n\n if (this.readyState === InterceptorReadyState.APPLIED) {\n logger.info('intercepted already applied!')\n return\n }\n\n const shouldApply = this.checkEnvironment()\n\n if (!shouldApply) {\n logger.info('the interceptor cannot be applied in this environment!')\n return\n }\n\n this.readyState = InterceptorReadyState.APPLYING\n\n // Whenever applying a new interceptor, check if it hasn't been applied already.\n // This enables to apply the same interceptor multiple times, for example from a different\n // interceptor, only proxying events but keeping the stubs in a single place.\n const runningInstance = this.getInstance()\n\n if (runningInstance) {\n logger.info('found a running instance, reusing...')\n\n // Proxy any listeners you set on this instance to the running instance.\n this.on = (event, listener) => {\n logger.info('proxying the \"%s\" listener', event)\n\n // Add listeners to the running instance so they appear\n // at the top of the event listeners list and are executed first.\n runningInstance.emitter.addListener(event, listener)\n\n // Ensure that once this interceptor instance is disposed,\n // it removes all listeners it has appended to the running interceptor instance.\n this.subscriptions.push(() => {\n runningInstance.emitter.removeListener(event, listener)\n logger.info('removed proxied \"%s\" listener!', event)\n })\n\n return this\n }\n\n this.readyState = InterceptorReadyState.APPLIED\n\n return\n }\n\n logger.info('no running instance found, setting up a new instance...')\n\n // Setup the interceptor.\n this.setup()\n\n // Store the newly applied interceptor instance globally.\n this.setInstance()\n\n this.readyState = InterceptorReadyState.APPLIED\n }\n\n /**\n * Setup the module augments and stubs necessary for this interceptor.\n * This method is not run if there's a running interceptor instance\n * to prevent instantiating an interceptor multiple times.\n */\n protected setup(): void {}\n\n /**\n * Listen to the interceptor's public events.\n */\n public on>(\n event: EventName,\n listener: Listener\n ): this {\n const logger = this.logger.extend('on')\n\n if (\n this.readyState === InterceptorReadyState.DISPOSING ||\n this.readyState === InterceptorReadyState.DISPOSED\n ) {\n logger.info('cannot listen to events, already disposed!')\n return this\n }\n\n logger.info('adding \"%s\" event listener:', event, listener)\n\n this.emitter.on(event, listener)\n return this\n }\n\n public once>(\n event: EventName,\n listener: Listener\n ): this {\n this.emitter.once(event, listener)\n return this\n }\n\n public off>(\n event: EventName,\n listener: Listener\n ): this {\n this.emitter.off(event, listener)\n return this\n }\n\n public removeAllListeners>(\n event?: EventName\n ): this {\n this.emitter.removeAllListeners(event)\n return this\n }\n\n /**\n * Disposes of any side-effects this interceptor has introduced.\n */\n public dispose(): void {\n const logger = this.logger.extend('dispose')\n\n if (this.readyState === InterceptorReadyState.DISPOSED) {\n logger.info('cannot dispose, already disposed!')\n return\n }\n\n logger.info('disposing the interceptor...')\n this.readyState = InterceptorReadyState.DISPOSING\n\n if (!this.getInstance()) {\n logger.info('no interceptors running, skipping dispose...')\n return\n }\n\n // Delete the global symbol as soon as possible,\n // indicating that the interceptor is no longer running.\n this.clearInstance()\n\n logger.info('global symbol deleted:', getGlobalSymbol(this.symbol))\n\n if (this.subscriptions.length > 0) {\n logger.info('disposing of %d subscriptions...', this.subscriptions.length)\n\n for (const dispose of this.subscriptions) {\n dispose()\n }\n\n this.subscriptions = []\n\n logger.info('disposed of all subscriptions!', this.subscriptions.length)\n }\n\n this.emitter.removeAllListeners()\n logger.info('destroyed the listener!')\n\n this.readyState = InterceptorReadyState.DISPOSED\n }\n\n private getInstance(): this | undefined {\n const instance = getGlobalSymbol(this.symbol)\n this.logger.info('retrieved global instance:', instance?.constructor?.name)\n return instance\n }\n\n private setInstance(): void {\n setGlobalSymbol(this.symbol, this)\n this.logger.info('set global instance!', this.symbol.description)\n }\n\n private clearInstance(): void {\n deleteGlobalSymbol(this.symbol)\n this.logger.info('cleared global instance!', this.symbol.description)\n }\n}\n","/**\n * Generate a random ID string to represent a request.\n * @example\n * createRequestId()\n * // \"f774b6c9c600f\"\n */\nexport function createRequestId(): string {\n return Math.random().toString(16).slice(2)\n}\n","/**\n * A function that validates if property access is possible on an object\n * without throwing. It returns `true` if the property access is possible\n * and `false` otherwise.\n *\n * Environments like miniflare will throw on property access on certain objects\n * like Request and Response, for unimplemented properties.\n */\nexport function isPropertyAccessible>(\n obj: Obj,\n key: keyof Obj\n) {\n try {\n obj[key]\n return true\n } catch {\n return false\n }\n}\n","import { isPropertyAccessible } from './isPropertyAccessible'\n\n/**\n * Response status codes for responses that cannot have body.\n * @see https://fetch.spec.whatwg.org/#statuses\n */\nexport const RESPONSE_STATUS_CODES_WITHOUT_BODY = new Set([\n 101, 103, 204, 205, 304,\n])\n\n/**\n * Returns a boolean indicating whether the given response status\n * code represents a response that cannot have a body.\n */\nexport function isResponseWithoutBody(status: number): boolean {\n return RESPONSE_STATUS_CODES_WITHOUT_BODY.has(status)\n}\n\n/**\n * Creates a generic 500 Unhandled Exception response.\n */\nexport function createServerErrorResponse(body: unknown): Response {\n return new Response(\n JSON.stringify(\n body instanceof Error\n ? {\n name: body.name,\n message: body.message,\n stack: body.stack,\n }\n : body\n ),\n {\n status: 500,\n statusText: 'Unhandled Exception',\n headers: {\n 'Content-Type': 'application/json',\n },\n }\n )\n}\n\n/**\n * Checks if the given response is a `Response.error()`.\n *\n * @note Some environments, like Miniflare (Cloudflare) do not\n * implement the \"Response.type\" property and throw on its access.\n * Safely check if we can access \"type\" on \"Response\" before continuing.\n * @see https://github.com/mswjs/msw/issues/1834\n */\nexport function isResponseError(\n response: Response\n): response is Response & { type: 'error' } {\n return isPropertyAccessible(response, 'type') && response.type === 'error'\n}\n"]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/chunk-EIBTX65O.js b/node_modules/@mswjs/interceptors/lib/node/chunk-EIBTX65O.js new file mode 100644 index 0000000000000000000000000000000000000000..ae0ccb9645c2ff80a62cacb064da5a025a47808c --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/chunk-EIBTX65O.js @@ -0,0 +1,7 @@ +"use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/glossary.ts +var IS_PATCHED_MODULE = Symbol("isPatchedModule"); + + + +exports.IS_PATCHED_MODULE = IS_PATCHED_MODULE; +//# sourceMappingURL=chunk-EIBTX65O.js.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/chunk-EIBTX65O.js.map b/node_modules/@mswjs/interceptors/lib/node/chunk-EIBTX65O.js.map new file mode 100644 index 0000000000000000000000000000000000000000..0473158b6dc59d37b24636f3f8f485f82bfe2ee2 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/chunk-EIBTX65O.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/glossary.ts"],"names":[],"mappings":";AAEO,IAAM,oBAAmC,OAAO,iBAAiB","sourcesContent":["import type { InteractiveRequest } from './utils/toInteractiveRequest'\n\nexport const IS_PATCHED_MODULE: unique symbol = Symbol('isPatchedModule')\n\nexport type RequestCredentials = 'omit' | 'include' | 'same-origin'\n\nexport type HttpRequestEventMap = {\n request: [\n args: {\n request: InteractiveRequest\n requestId: string\n }\n ]\n response: [\n args: {\n response: Response\n isMockedResponse: boolean\n request: Request\n requestId: string\n }\n ]\n unhandledException: [\n args: {\n error: unknown\n request: Request\n requestId: string\n controller: {\n respondWith(response: Response): void\n errorWith(error?: Error): void\n }\n }\n ]\n}\n"]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/chunk-KSHIDGUL.mjs b/node_modules/@mswjs/interceptors/lib/node/chunk-KSHIDGUL.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e2199a6d591c6e0478a5cbafcbd9ed546b79b72c --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/chunk-KSHIDGUL.mjs @@ -0,0 +1,820 @@ +import { + decodeBuffer, + encodeBuffer, + toArrayBuffer +} from "./chunk-6HYIRFX2.mjs"; +import { + IS_PATCHED_MODULE +} from "./chunk-OJ6O4LSC.mjs"; +import { + emitAsync, + toInteractiveRequest +} from "./chunk-OUWBQF3Z.mjs"; +import { + INTERNAL_REQUEST_ID_HEADER_NAME, + Interceptor, + createRequestId, + createServerErrorResponse, + isResponseError, + isResponseWithoutBody +} from "./chunk-Q7POAM5N.mjs"; + +// src/interceptors/XMLHttpRequest/index.ts +import { invariant as invariant2 } from "outvariant"; + +// src/interceptors/XMLHttpRequest/XMLHttpRequestProxy.ts +import { until } from "@open-draft/until"; + +// src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts +import { invariant } from "outvariant"; +import { isNodeProcess } from "is-node-process"; + +// src/interceptors/XMLHttpRequest/utils/concatArrayBuffer.ts +function concatArrayBuffer(left, right) { + const result = new Uint8Array(left.byteLength + right.byteLength); + result.set(left, 0); + result.set(right, left.byteLength); + return result; +} + +// src/interceptors/XMLHttpRequest/polyfills/EventPolyfill.ts +var EventPolyfill = class { + constructor(type, options) { + this.AT_TARGET = 0; + this.BUBBLING_PHASE = 0; + this.CAPTURING_PHASE = 0; + this.NONE = 0; + this.type = ""; + this.srcElement = null; + this.currentTarget = null; + this.eventPhase = 0; + this.isTrusted = true; + this.composed = false; + this.cancelable = true; + this.defaultPrevented = false; + this.bubbles = true; + this.lengthComputable = true; + this.loaded = 0; + this.total = 0; + this.cancelBubble = false; + this.returnValue = true; + this.type = type; + this.target = (options == null ? void 0 : options.target) || null; + this.currentTarget = (options == null ? void 0 : options.currentTarget) || null; + this.timeStamp = Date.now(); + } + composedPath() { + return []; + } + initEvent(type, bubbles, cancelable) { + this.type = type; + this.bubbles = !!bubbles; + this.cancelable = !!cancelable; + } + preventDefault() { + this.defaultPrevented = true; + } + stopPropagation() { + } + stopImmediatePropagation() { + } +}; + +// src/interceptors/XMLHttpRequest/polyfills/ProgressEventPolyfill.ts +var ProgressEventPolyfill = class extends EventPolyfill { + constructor(type, init) { + super(type); + this.lengthComputable = (init == null ? void 0 : init.lengthComputable) || false; + this.composed = (init == null ? void 0 : init.composed) || false; + this.loaded = (init == null ? void 0 : init.loaded) || 0; + this.total = (init == null ? void 0 : init.total) || 0; + } +}; + +// src/interceptors/XMLHttpRequest/utils/createEvent.ts +var SUPPORTS_PROGRESS_EVENT = typeof ProgressEvent !== "undefined"; +function createEvent(target, type, init) { + const progressEvents = [ + "error", + "progress", + "loadstart", + "loadend", + "load", + "timeout", + "abort" + ]; + const ProgressEventClass = SUPPORTS_PROGRESS_EVENT ? ProgressEvent : ProgressEventPolyfill; + const event = progressEvents.includes(type) ? new ProgressEventClass(type, { + lengthComputable: true, + loaded: (init == null ? void 0 : init.loaded) || 0, + total: (init == null ? void 0 : init.total) || 0 + }) : new EventPolyfill(type, { + target, + currentTarget: target + }); + return event; +} + +// src/utils/findPropertySource.ts +function findPropertySource(target, propertyName) { + if (!(propertyName in target)) { + return null; + } + const hasProperty = Object.prototype.hasOwnProperty.call(target, propertyName); + if (hasProperty) { + return target; + } + const prototype = Reflect.getPrototypeOf(target); + return prototype ? findPropertySource(prototype, propertyName) : null; +} + +// src/utils/createProxy.ts +function createProxy(target, options) { + const proxy = new Proxy(target, optionsToProxyHandler(options)); + return proxy; +} +function optionsToProxyHandler(options) { + const { constructorCall, methodCall, getProperty, setProperty } = options; + const handler = {}; + if (typeof constructorCall !== "undefined") { + handler.construct = function(target, args, newTarget) { + const next = Reflect.construct.bind(null, target, args, newTarget); + return constructorCall.call(newTarget, args, next); + }; + } + handler.set = function(target, propertyName, nextValue) { + const next = () => { + const propertySource = findPropertySource(target, propertyName) || target; + const ownDescriptors = Reflect.getOwnPropertyDescriptor( + propertySource, + propertyName + ); + if (typeof (ownDescriptors == null ? void 0 : ownDescriptors.set) !== "undefined") { + ownDescriptors.set.apply(target, [nextValue]); + return true; + } + return Reflect.defineProperty(propertySource, propertyName, { + writable: true, + enumerable: true, + configurable: true, + value: nextValue + }); + }; + if (typeof setProperty !== "undefined") { + return setProperty.call(target, [propertyName, nextValue], next); + } + return next(); + }; + handler.get = function(target, propertyName, receiver) { + const next = () => target[propertyName]; + const value = typeof getProperty !== "undefined" ? getProperty.call(target, [propertyName, receiver], next) : next(); + if (typeof value === "function") { + return (...args) => { + const next2 = value.bind(target, ...args); + if (typeof methodCall !== "undefined") { + return methodCall.call(target, [propertyName, args], next2); + } + return next2(); + }; + } + return value; + }; + return handler; +} + +// src/interceptors/XMLHttpRequest/utils/isDomParserSupportedType.ts +function isDomParserSupportedType(type) { + const supportedTypes = [ + "application/xhtml+xml", + "application/xml", + "image/svg+xml", + "text/html", + "text/xml" + ]; + return supportedTypes.some((supportedType) => { + return type.startsWith(supportedType); + }); +} + +// src/utils/parseJson.ts +function parseJson(data) { + try { + const json = JSON.parse(data); + return json; + } catch (_) { + return null; + } +} + +// src/interceptors/XMLHttpRequest/utils/createResponse.ts +function createResponse(request, body) { + const responseBodyOrNull = isResponseWithoutBody(request.status) ? null : body; + return new Response(responseBodyOrNull, { + status: request.status, + statusText: request.statusText, + headers: createHeadersFromXMLHttpReqestHeaders( + request.getAllResponseHeaders() + ) + }); +} +function createHeadersFromXMLHttpReqestHeaders(headersString) { + const headers = new Headers(); + const lines = headersString.split(/[\r\n]+/); + for (const line of lines) { + if (line.trim() === "") { + continue; + } + const [name, ...parts] = line.split(": "); + const value = parts.join(": "); + headers.append(name, value); + } + return headers; +} + +// src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts +var IS_MOCKED_RESPONSE = Symbol("isMockedResponse"); +var IS_NODE = isNodeProcess(); +var XMLHttpRequestController = class { + constructor(initialRequest, logger) { + this.initialRequest = initialRequest; + this.logger = logger; + this.method = "GET"; + this.url = null; + this.events = /* @__PURE__ */ new Map(); + this.requestId = createRequestId(); + this.requestHeaders = new Headers(); + this.responseBuffer = new Uint8Array(); + this.request = createProxy(initialRequest, { + setProperty: ([propertyName, nextValue], invoke) => { + switch (propertyName) { + case "ontimeout": { + const eventName = propertyName.slice( + 2 + ); + this.request.addEventListener(eventName, nextValue); + return invoke(); + } + default: { + return invoke(); + } + } + }, + methodCall: ([methodName, args], invoke) => { + var _a; + switch (methodName) { + case "open": { + const [method, url] = args; + if (typeof url === "undefined") { + this.method = "GET"; + this.url = toAbsoluteUrl(method); + } else { + this.method = method; + this.url = toAbsoluteUrl(url); + } + this.logger = this.logger.extend(`${this.method} ${this.url.href}`); + this.logger.info("open", this.method, this.url.href); + return invoke(); + } + case "addEventListener": { + const [eventName, listener] = args; + this.registerEvent(eventName, listener); + this.logger.info("addEventListener", eventName, listener); + return invoke(); + } + case "setRequestHeader": { + const [name, value] = args; + this.requestHeaders.set(name, value); + this.logger.info("setRequestHeader", name, value); + return invoke(); + } + case "send": { + const [body] = args; + if (body != null) { + this.requestBody = typeof body === "string" ? encodeBuffer(body) : body; + } + this.request.addEventListener("load", () => { + if (typeof this.onResponse !== "undefined") { + const fetchResponse = createResponse( + this.request, + /** + * The `response` property is the right way to read + * the ambiguous response body, as the request's "responseType" may differ. + * @see https://xhr.spec.whatwg.org/#the-response-attribute + */ + this.request.response + ); + this.onResponse.call(this, { + response: fetchResponse, + isMockedResponse: IS_MOCKED_RESPONSE in this.request, + request: fetchRequest, + requestId: this.requestId + }); + } + }); + const fetchRequest = this.toFetchApiRequest(); + const onceRequestSettled = ((_a = this.onRequest) == null ? void 0 : _a.call(this, { + request: fetchRequest, + requestId: this.requestId + })) || Promise.resolve(); + onceRequestSettled.finally(() => { + if (this.request.readyState < this.request.LOADING) { + this.logger.info( + "request callback settled but request has not been handled (readystate %d), performing as-is...", + this.request.readyState + ); + if (IS_NODE) { + this.request.setRequestHeader( + INTERNAL_REQUEST_ID_HEADER_NAME, + this.requestId + ); + } + return invoke(); + } + }); + break; + } + default: { + return invoke(); + } + } + } + }); + } + registerEvent(eventName, listener) { + const prevEvents = this.events.get(eventName) || []; + const nextEvents = prevEvents.concat(listener); + this.events.set(eventName, nextEvents); + this.logger.info('registered event "%s"', eventName, listener); + } + /** + * Responds to the current request with the given + * Fetch API `Response` instance. + */ + respondWith(response) { + this.logger.info( + "responding with a mocked response: %d %s", + response.status, + response.statusText + ); + define(this.request, IS_MOCKED_RESPONSE, true); + define(this.request, "status", response.status); + define(this.request, "statusText", response.statusText); + define(this.request, "responseURL", this.url.href); + this.request.getResponseHeader = new Proxy(this.request.getResponseHeader, { + apply: (_, __, args) => { + this.logger.info("getResponseHeader", args[0]); + if (this.request.readyState < this.request.HEADERS_RECEIVED) { + this.logger.info("headers not received yet, returning null"); + return null; + } + const headerValue = response.headers.get(args[0]); + this.logger.info( + 'resolved response header "%s" to', + args[0], + headerValue + ); + return headerValue; + } + }); + this.request.getAllResponseHeaders = new Proxy( + this.request.getAllResponseHeaders, + { + apply: () => { + this.logger.info("getAllResponseHeaders"); + if (this.request.readyState < this.request.HEADERS_RECEIVED) { + this.logger.info("headers not received yet, returning empty string"); + return ""; + } + const headersList = Array.from(response.headers.entries()); + const allHeaders = headersList.map(([headerName, headerValue]) => { + return `${headerName}: ${headerValue}`; + }).join("\r\n"); + this.logger.info("resolved all response headers to", allHeaders); + return allHeaders; + } + } + ); + Object.defineProperties(this.request, { + response: { + enumerable: true, + configurable: false, + get: () => this.response + }, + responseText: { + enumerable: true, + configurable: false, + get: () => this.responseText + }, + responseXML: { + enumerable: true, + configurable: false, + get: () => this.responseXML + } + }); + const totalResponseBodyLength = response.headers.has("Content-Length") ? Number(response.headers.get("Content-Length")) : ( + /** + * @todo Infer the response body length from the response body. + */ + void 0 + ); + this.logger.info("calculated response body length", totalResponseBodyLength); + this.trigger("loadstart", { + loaded: 0, + total: totalResponseBodyLength + }); + this.setReadyState(this.request.HEADERS_RECEIVED); + this.setReadyState(this.request.LOADING); + const finalizeResponse = () => { + this.logger.info("finalizing the mocked response..."); + this.setReadyState(this.request.DONE); + this.trigger("load", { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength + }); + this.trigger("loadend", { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength + }); + }; + if (response.body) { + this.logger.info("mocked response has body, streaming..."); + const reader = response.body.getReader(); + const readNextResponseBodyChunk = async () => { + const { value, done } = await reader.read(); + if (done) { + this.logger.info("response body stream done!"); + finalizeResponse(); + return; + } + if (value) { + this.logger.info("read response body chunk:", value); + this.responseBuffer = concatArrayBuffer(this.responseBuffer, value); + this.trigger("progress", { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength + }); + } + readNextResponseBodyChunk(); + }; + readNextResponseBodyChunk(); + } else { + finalizeResponse(); + } + } + responseBufferToText() { + return decodeBuffer(this.responseBuffer); + } + get response() { + this.logger.info( + "getResponse (responseType: %s)", + this.request.responseType + ); + if (this.request.readyState !== this.request.DONE) { + return null; + } + switch (this.request.responseType) { + case "json": { + const responseJson = parseJson(this.responseBufferToText()); + this.logger.info("resolved response JSON", responseJson); + return responseJson; + } + case "arraybuffer": { + const arrayBuffer = toArrayBuffer(this.responseBuffer); + this.logger.info("resolved response ArrayBuffer", arrayBuffer); + return arrayBuffer; + } + case "blob": { + const mimeType = this.request.getResponseHeader("Content-Type") || "text/plain"; + const responseBlob = new Blob([this.responseBufferToText()], { + type: mimeType + }); + this.logger.info( + "resolved response Blob (mime type: %s)", + responseBlob, + mimeType + ); + return responseBlob; + } + default: { + const responseText = this.responseBufferToText(); + this.logger.info( + 'resolving "%s" response type as text', + this.request.responseType, + responseText + ); + return responseText; + } + } + } + get responseText() { + invariant( + this.request.responseType === "" || this.request.responseType === "text", + "InvalidStateError: The object is in invalid state." + ); + if (this.request.readyState !== this.request.LOADING && this.request.readyState !== this.request.DONE) { + return ""; + } + const responseText = this.responseBufferToText(); + this.logger.info('getResponseText: "%s"', responseText); + return responseText; + } + get responseXML() { + invariant( + this.request.responseType === "" || this.request.responseType === "document", + "InvalidStateError: The object is in invalid state." + ); + if (this.request.readyState !== this.request.DONE) { + return null; + } + const contentType = this.request.getResponseHeader("Content-Type") || ""; + if (typeof DOMParser === "undefined") { + console.warn( + "Cannot retrieve XMLHttpRequest response body as XML: DOMParser is not defined. You are likely using an environment that is not browser or does not polyfill browser globals correctly." + ); + return null; + } + if (isDomParserSupportedType(contentType)) { + return new DOMParser().parseFromString( + this.responseBufferToText(), + contentType + ); + } + return null; + } + errorWith(error) { + this.logger.info("responding with an error"); + this.setReadyState(this.request.DONE); + this.trigger("error"); + this.trigger("loadend"); + } + /** + * Transitions this request's `readyState` to the given one. + */ + setReadyState(nextReadyState) { + this.logger.info( + "setReadyState: %d -> %d", + this.request.readyState, + nextReadyState + ); + if (this.request.readyState === nextReadyState) { + this.logger.info("ready state identical, skipping transition..."); + return; + } + define(this.request, "readyState", nextReadyState); + this.logger.info("set readyState to: %d", nextReadyState); + if (nextReadyState !== this.request.UNSENT) { + this.logger.info('triggerring "readystatechange" event...'); + this.trigger("readystatechange"); + } + } + /** + * Triggers given event on the `XMLHttpRequest` instance. + */ + trigger(eventName, options) { + const callback = this.request[`on${eventName}`]; + const event = createEvent(this.request, eventName, options); + this.logger.info('trigger "%s"', eventName, options || ""); + if (typeof callback === "function") { + this.logger.info('found a direct "%s" callback, calling...', eventName); + callback.call(this.request, event); + } + for (const [registeredEventName, listeners] of this.events) { + if (registeredEventName === eventName) { + this.logger.info( + 'found %d listener(s) for "%s" event, calling...', + listeners.length, + eventName + ); + listeners.forEach((listener) => listener.call(this.request, event)); + } + } + } + /** + * Converts this `XMLHttpRequest` instance into a Fetch API `Request` instance. + */ + toFetchApiRequest() { + this.logger.info("converting request to a Fetch API Request..."); + const fetchRequest = new Request(this.url.href, { + method: this.method, + headers: this.requestHeaders, + /** + * @see https://xhr.spec.whatwg.org/#cross-origin-credentials + */ + credentials: this.request.withCredentials ? "include" : "same-origin", + body: ["GET", "HEAD"].includes(this.method) ? null : this.requestBody + }); + const proxyHeaders = createProxy(fetchRequest.headers, { + methodCall: ([methodName, args], invoke) => { + switch (methodName) { + case "append": + case "set": { + const [headerName, headerValue] = args; + this.request.setRequestHeader(headerName, headerValue); + break; + } + case "delete": { + const [headerName] = args; + console.warn( + `XMLHttpRequest: Cannot remove a "${headerName}" header from the Fetch API representation of the "${fetchRequest.method} ${fetchRequest.url}" request. XMLHttpRequest headers cannot be removed.` + ); + break; + } + } + return invoke(); + } + }); + define(fetchRequest, "headers", proxyHeaders); + this.logger.info("converted request to a Fetch API Request!", fetchRequest); + return fetchRequest; + } +}; +function toAbsoluteUrl(url) { + if (typeof location === "undefined") { + return new URL(url); + } + return new URL(url.toString(), location.href); +} +function define(target, property, value) { + Reflect.defineProperty(target, property, { + // Ensure writable properties to allow redefining readonly properties. + writable: true, + enumerable: true, + value + }); +} + +// src/interceptors/XMLHttpRequest/XMLHttpRequestProxy.ts +function createXMLHttpRequestProxy({ + emitter, + logger +}) { + const XMLHttpRequestProxy = new Proxy(globalThis.XMLHttpRequest, { + construct(target, args, newTarget) { + logger.info("constructed new XMLHttpRequest"); + const originalRequest = Reflect.construct( + target, + args, + newTarget + ); + const prototypeDescriptors = Object.getOwnPropertyDescriptors( + target.prototype + ); + for (const propertyName in prototypeDescriptors) { + Reflect.defineProperty( + originalRequest, + propertyName, + prototypeDescriptors[propertyName] + ); + } + const xhrRequestController = new XMLHttpRequestController( + originalRequest, + logger + ); + xhrRequestController.onRequest = async function({ request, requestId }) { + const { interactiveRequest, requestController } = toInteractiveRequest(request); + this.logger.info("awaiting mocked response..."); + emitter.once("request", ({ requestId: pendingRequestId }) => { + if (pendingRequestId !== requestId) { + return; + } + if (requestController.responsePromise.state === "pending") { + requestController.respondWith(void 0); + } + }); + const resolverResult = await until(async () => { + this.logger.info( + 'emitting the "request" event for %s listener(s)...', + emitter.listenerCount("request") + ); + await emitAsync(emitter, "request", { + request: interactiveRequest, + requestId + }); + this.logger.info('all "request" listeners settled!'); + const mockedResponse2 = await requestController.responsePromise; + this.logger.info("event.respondWith called with:", mockedResponse2); + return mockedResponse2; + }); + if (resolverResult.error) { + this.logger.info( + "request listener threw an exception, aborting request...", + resolverResult.error + ); + if (resolverResult.error instanceof Response) { + if (isResponseError(resolverResult.error)) { + xhrRequestController.errorWith(new TypeError("Network error")); + } else { + this.respondWith(resolverResult.error); + } + return; + } + if (emitter.listenerCount("unhandledException") > 0) { + await emitAsync(emitter, "unhandledException", { + error: resolverResult.error, + request, + requestId, + controller: { + respondWith: xhrRequestController.respondWith.bind(xhrRequestController), + errorWith: xhrRequestController.errorWith.bind(xhrRequestController) + } + }); + if (originalRequest.readyState > XMLHttpRequest.OPENED) { + return; + } + } + xhrRequestController.respondWith( + createServerErrorResponse(resolverResult.error) + ); + return; + } + const mockedResponse = resolverResult.data; + if (typeof mockedResponse !== "undefined") { + this.logger.info( + "received mocked response: %d %s", + mockedResponse.status, + mockedResponse.statusText + ); + if (isResponseError(mockedResponse)) { + this.logger.info( + "received a network error response, rejecting the request promise..." + ); + xhrRequestController.errorWith(new TypeError("Network error")); + return; + } + return xhrRequestController.respondWith(mockedResponse); + } + this.logger.info( + "no mocked response received, performing request as-is..." + ); + }; + xhrRequestController.onResponse = async function({ + response, + isMockedResponse, + request, + requestId + }) { + this.logger.info( + 'emitting the "response" event for %s listener(s)...', + emitter.listenerCount("response") + ); + emitter.emit("response", { + response, + isMockedResponse, + request, + requestId + }); + }; + return xhrRequestController.request; + } + }); + return XMLHttpRequestProxy; +} + +// src/interceptors/XMLHttpRequest/index.ts +var _XMLHttpRequestInterceptor = class extends Interceptor { + constructor() { + super(_XMLHttpRequestInterceptor.interceptorSymbol); + } + checkEnvironment() { + return typeof globalThis.XMLHttpRequest !== "undefined"; + } + setup() { + const logger = this.logger.extend("setup"); + logger.info('patching "XMLHttpRequest" module...'); + const PureXMLHttpRequest = globalThis.XMLHttpRequest; + invariant2( + !PureXMLHttpRequest[IS_PATCHED_MODULE], + 'Failed to patch the "XMLHttpRequest" module: already patched.' + ); + globalThis.XMLHttpRequest = createXMLHttpRequestProxy({ + emitter: this.emitter, + logger: this.logger + }); + logger.info( + 'native "XMLHttpRequest" module patched!', + globalThis.XMLHttpRequest.name + ); + Object.defineProperty(globalThis.XMLHttpRequest, IS_PATCHED_MODULE, { + enumerable: true, + configurable: true, + value: true + }); + this.subscriptions.push(() => { + Object.defineProperty(globalThis.XMLHttpRequest, IS_PATCHED_MODULE, { + value: void 0 + }); + globalThis.XMLHttpRequest = PureXMLHttpRequest; + logger.info( + 'native "XMLHttpRequest" module restored!', + globalThis.XMLHttpRequest.name + ); + }); + } +}; +var XMLHttpRequestInterceptor = _XMLHttpRequestInterceptor; +XMLHttpRequestInterceptor.interceptorSymbol = Symbol("xhr"); + +export { + XMLHttpRequestInterceptor +}; +//# sourceMappingURL=chunk-KSHIDGUL.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/chunk-KSHIDGUL.mjs.map b/node_modules/@mswjs/interceptors/lib/node/chunk-KSHIDGUL.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..be0412b37715efb667c94e9820fc418354fc8fb9 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/chunk-KSHIDGUL.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/interceptors/XMLHttpRequest/index.ts","../../src/interceptors/XMLHttpRequest/XMLHttpRequestProxy.ts","../../src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts","../../src/interceptors/XMLHttpRequest/utils/concatArrayBuffer.ts","../../src/interceptors/XMLHttpRequest/polyfills/EventPolyfill.ts","../../src/interceptors/XMLHttpRequest/polyfills/ProgressEventPolyfill.ts","../../src/interceptors/XMLHttpRequest/utils/createEvent.ts","../../src/utils/findPropertySource.ts","../../src/utils/createProxy.ts","../../src/interceptors/XMLHttpRequest/utils/isDomParserSupportedType.ts","../../src/utils/parseJson.ts","../../src/interceptors/XMLHttpRequest/utils/createResponse.ts"],"sourcesContent":["import { invariant } from 'outvariant'\nimport { Emitter } from 'strict-event-emitter'\nimport { HttpRequestEventMap, IS_PATCHED_MODULE } from '../../glossary'\nimport { InteractiveRequest } from '../../utils/toInteractiveRequest'\nimport { Interceptor } from '../../Interceptor'\nimport { createXMLHttpRequestProxy } from './XMLHttpRequestProxy'\n\nexport type XMLHttpRequestEventListener = (args: {\n request: InteractiveRequest\n requestId: string\n}) => Promise | void\n\nexport type XMLHttpRequestEmitter = Emitter\n\nexport class XMLHttpRequestInterceptor extends Interceptor {\n static interceptorSymbol = Symbol('xhr')\n\n constructor() {\n super(XMLHttpRequestInterceptor.interceptorSymbol)\n }\n\n protected checkEnvironment() {\n return typeof globalThis.XMLHttpRequest !== 'undefined'\n }\n\n protected setup() {\n const logger = this.logger.extend('setup')\n\n logger.info('patching \"XMLHttpRequest\" module...')\n\n const PureXMLHttpRequest = globalThis.XMLHttpRequest\n\n invariant(\n !(PureXMLHttpRequest as any)[IS_PATCHED_MODULE],\n 'Failed to patch the \"XMLHttpRequest\" module: already patched.'\n )\n\n globalThis.XMLHttpRequest = createXMLHttpRequestProxy({\n emitter: this.emitter,\n logger: this.logger,\n })\n\n logger.info(\n 'native \"XMLHttpRequest\" module patched!',\n globalThis.XMLHttpRequest.name\n )\n\n Object.defineProperty(globalThis.XMLHttpRequest, IS_PATCHED_MODULE, {\n enumerable: true,\n configurable: true,\n value: true,\n })\n\n this.subscriptions.push(() => {\n Object.defineProperty(globalThis.XMLHttpRequest, IS_PATCHED_MODULE, {\n value: undefined,\n })\n\n globalThis.XMLHttpRequest = PureXMLHttpRequest\n logger.info(\n 'native \"XMLHttpRequest\" module restored!',\n globalThis.XMLHttpRequest.name\n )\n })\n }\n}\n","import { until } from '@open-draft/until'\nimport type { Logger } from '@open-draft/logger'\nimport { XMLHttpRequestEmitter } from '.'\nimport { toInteractiveRequest } from '../../utils/toInteractiveRequest'\nimport { emitAsync } from '../../utils/emitAsync'\nimport { XMLHttpRequestController } from './XMLHttpRequestController'\nimport {\n createServerErrorResponse,\n isResponseError,\n} from '../../utils/responseUtils'\n\nexport interface XMLHttpRequestProxyOptions {\n emitter: XMLHttpRequestEmitter\n logger: Logger\n}\n\n/**\n * Create a proxied `XMLHttpRequest` class.\n * The proxied class establishes spies on certain methods,\n * allowing us to intercept requests and respond to them.\n */\nexport function createXMLHttpRequestProxy({\n emitter,\n logger,\n}: XMLHttpRequestProxyOptions) {\n const XMLHttpRequestProxy = new Proxy(globalThis.XMLHttpRequest, {\n construct(target, args, newTarget) {\n logger.info('constructed new XMLHttpRequest')\n\n const originalRequest = Reflect.construct(\n target,\n args,\n newTarget\n ) as XMLHttpRequest\n\n /**\n * @note Forward prototype descriptors onto the proxied object.\n * XMLHttpRequest is implemented in JSDOM in a way that assigns\n * a bunch of descriptors, like \"set responseType()\" on the prototype.\n * With this propagation, we make sure that those descriptors trigger\n * when the user operates with the proxied request instance.\n */\n const prototypeDescriptors = Object.getOwnPropertyDescriptors(\n target.prototype\n )\n for (const propertyName in prototypeDescriptors) {\n Reflect.defineProperty(\n originalRequest,\n propertyName,\n prototypeDescriptors[propertyName]\n )\n }\n\n const xhrRequestController = new XMLHttpRequestController(\n originalRequest,\n logger\n )\n\n xhrRequestController.onRequest = async function ({ request, requestId }) {\n const { interactiveRequest, requestController } =\n toInteractiveRequest(request)\n\n this.logger.info('awaiting mocked response...')\n\n emitter.once('request', ({ requestId: pendingRequestId }) => {\n if (pendingRequestId !== requestId) {\n return\n }\n\n if (requestController.responsePromise.state === 'pending') {\n requestController.respondWith(undefined)\n }\n })\n\n const resolverResult = await until(async () => {\n this.logger.info(\n 'emitting the \"request\" event for %s listener(s)...',\n emitter.listenerCount('request')\n )\n\n await emitAsync(emitter, 'request', {\n request: interactiveRequest,\n requestId,\n })\n\n this.logger.info('all \"request\" listeners settled!')\n\n const mockedResponse = await requestController.responsePromise\n\n this.logger.info('event.respondWith called with:', mockedResponse)\n\n return mockedResponse\n })\n\n if (resolverResult.error) {\n this.logger.info(\n 'request listener threw an exception, aborting request...',\n resolverResult.error\n )\n\n // Treat thrown Responses as mocked responses.\n if (resolverResult.error instanceof Response) {\n if (isResponseError(resolverResult.error)) {\n xhrRequestController.errorWith(new TypeError('Network error'))\n } else {\n this.respondWith(resolverResult.error)\n }\n\n return\n }\n\n if (emitter.listenerCount('unhandledException') > 0) {\n // Emit the \"unhandledException\" event so the client can opt-out\n // from the default exception handling (producing 500 error responses).\n await emitAsync(emitter, 'unhandledException', {\n error: resolverResult.error,\n request,\n requestId,\n controller: {\n respondWith:\n xhrRequestController.respondWith.bind(xhrRequestController),\n errorWith:\n xhrRequestController.errorWith.bind(xhrRequestController),\n },\n })\n\n // If any of the \"unhandledException\" listeners handled the request,\n // do nothing. Note that mocked responses will dispatch\n // HEADERS_RECEIVED (2), then LOADING (3), and DONE (4) can take\n // time as the mocked response body finishes streaming.\n if (originalRequest.readyState > XMLHttpRequest.OPENED) {\n return\n }\n }\n\n // Unhandled exceptions in the request listeners are\n // synonymous to unhandled exceptions on the server.\n // Those are represented as 500 error responses.\n xhrRequestController.respondWith(\n createServerErrorResponse(resolverResult.error)\n )\n\n return\n }\n\n const mockedResponse = resolverResult.data\n\n if (typeof mockedResponse !== 'undefined') {\n this.logger.info(\n 'received mocked response: %d %s',\n mockedResponse.status,\n mockedResponse.statusText\n )\n\n if (isResponseError(mockedResponse)) {\n this.logger.info(\n 'received a network error response, rejecting the request promise...'\n )\n\n xhrRequestController.errorWith(new TypeError('Network error'))\n return\n }\n\n return xhrRequestController.respondWith(mockedResponse)\n }\n\n this.logger.info(\n 'no mocked response received, performing request as-is...'\n )\n }\n\n xhrRequestController.onResponse = async function ({\n response,\n isMockedResponse,\n request,\n requestId,\n }) {\n this.logger.info(\n 'emitting the \"response\" event for %s listener(s)...',\n emitter.listenerCount('response')\n )\n\n emitter.emit('response', {\n response,\n isMockedResponse,\n request,\n requestId,\n })\n }\n\n // Return the proxied request from the controller\n // so that the controller can react to the consumer's interactions\n // with this request (opening/sending/etc).\n return xhrRequestController.request\n },\n })\n\n return XMLHttpRequestProxy\n}\n","import { invariant } from 'outvariant'\nimport { isNodeProcess } from 'is-node-process'\nimport type { Logger } from '@open-draft/logger'\nimport { concatArrayBuffer } from './utils/concatArrayBuffer'\nimport { createEvent } from './utils/createEvent'\nimport {\n decodeBuffer,\n encodeBuffer,\n toArrayBuffer,\n} from '../../utils/bufferUtils'\nimport { createProxy } from '../../utils/createProxy'\nimport { isDomParserSupportedType } from './utils/isDomParserSupportedType'\nimport { parseJson } from '../../utils/parseJson'\nimport { createResponse } from './utils/createResponse'\nimport { INTERNAL_REQUEST_ID_HEADER_NAME } from '../../Interceptor'\nimport { createRequestId } from '../../createRequestId'\n\nconst IS_MOCKED_RESPONSE = Symbol('isMockedResponse')\nconst IS_NODE = isNodeProcess()\n\n/**\n * An `XMLHttpRequest` instance controller that allows us\n * to handle any given request instance (e.g. responding to it).\n */\nexport class XMLHttpRequestController {\n public request: XMLHttpRequest\n public requestId: string\n public onRequest?: (\n this: XMLHttpRequestController,\n args: {\n request: Request\n requestId: string\n }\n ) => Promise\n public onResponse?: (\n this: XMLHttpRequestController,\n args: {\n response: Response\n isMockedResponse: boolean\n request: Request\n requestId: string\n }\n ) => void\n\n private method: string = 'GET'\n private url: URL = null as any\n private requestHeaders: Headers\n private requestBody?: XMLHttpRequestBodyInit | Document | null\n private responseBuffer: Uint8Array\n private events: Map>\n\n constructor(readonly initialRequest: XMLHttpRequest, public logger: Logger) {\n this.events = new Map()\n this.requestId = createRequestId()\n this.requestHeaders = new Headers()\n this.responseBuffer = new Uint8Array()\n\n this.request = createProxy(initialRequest, {\n setProperty: ([propertyName, nextValue], invoke) => {\n switch (propertyName) {\n case 'ontimeout': {\n const eventName = propertyName.slice(\n 2\n ) as keyof XMLHttpRequestEventTargetEventMap\n\n /**\n * @note Proxy callbacks to event listeners because JSDOM has trouble\n * translating these properties to callbacks. It seemed to be operating\n * on events exclusively.\n */\n this.request.addEventListener(eventName, nextValue as any)\n\n return invoke()\n }\n\n default: {\n return invoke()\n }\n }\n },\n methodCall: ([methodName, args], invoke) => {\n switch (methodName) {\n case 'open': {\n const [method, url] = args as [string, string | undefined]\n\n if (typeof url === 'undefined') {\n this.method = 'GET'\n this.url = toAbsoluteUrl(method)\n } else {\n this.method = method\n this.url = toAbsoluteUrl(url)\n }\n\n this.logger = this.logger.extend(`${this.method} ${this.url.href}`)\n this.logger.info('open', this.method, this.url.href)\n\n return invoke()\n }\n\n case 'addEventListener': {\n const [eventName, listener] = args as [\n keyof XMLHttpRequestEventTargetEventMap,\n Function\n ]\n\n this.registerEvent(eventName, listener)\n this.logger.info('addEventListener', eventName, listener)\n\n return invoke()\n }\n\n case 'setRequestHeader': {\n const [name, value] = args as [string, string]\n this.requestHeaders.set(name, value)\n\n this.logger.info('setRequestHeader', name, value)\n\n return invoke()\n }\n\n case 'send': {\n const [body] = args as [\n body?: XMLHttpRequestBodyInit | Document | null\n ]\n\n if (body != null) {\n this.requestBody =\n typeof body === 'string' ? encodeBuffer(body) : body\n }\n\n this.request.addEventListener('load', () => {\n if (typeof this.onResponse !== 'undefined') {\n // Create a Fetch API Response representation of whichever\n // response this XMLHttpRequest received. Note those may\n // be either a mocked and the original response.\n const fetchResponse = createResponse(\n this.request,\n /**\n * The `response` property is the right way to read\n * the ambiguous response body, as the request's \"responseType\" may differ.\n * @see https://xhr.spec.whatwg.org/#the-response-attribute\n */\n this.request.response\n )\n\n // Notify the consumer about the response.\n this.onResponse.call(this, {\n response: fetchResponse,\n isMockedResponse: IS_MOCKED_RESPONSE in this.request,\n request: fetchRequest,\n requestId: this.requestId!,\n })\n }\n })\n\n // Delegate request handling to the consumer.\n const fetchRequest = this.toFetchApiRequest()\n const onceRequestSettled =\n this.onRequest?.call(this, {\n request: fetchRequest,\n requestId: this.requestId!,\n }) || Promise.resolve()\n\n onceRequestSettled.finally(() => {\n // If the consumer didn't handle the request perform it as-is.\n // Note that the request may not yet be DONE and may, in fact,\n // be LOADING while the \"respondWith\" method does its magic.\n if (this.request.readyState < this.request.LOADING) {\n this.logger.info(\n 'request callback settled but request has not been handled (readystate %d), performing as-is...',\n this.request.readyState\n )\n\n /**\n * @note Set the intercepted request ID on the original request in Node.js\n * so that if it triggers any other interceptors, they don't attempt\n * to process it once again.\n *\n * For instance, XMLHttpRequest is often implemented via \"http.ClientRequest\"\n * and we don't want for both XHR and ClientRequest interceptors to\n * handle the same request at the same time (e.g. emit the \"response\" event twice).\n */\n if (IS_NODE) {\n this.request.setRequestHeader(\n INTERNAL_REQUEST_ID_HEADER_NAME,\n this.requestId!\n )\n }\n\n return invoke()\n }\n })\n\n break\n }\n\n default: {\n return invoke()\n }\n }\n },\n })\n }\n\n private registerEvent(\n eventName: keyof XMLHttpRequestEventTargetEventMap,\n listener: Function\n ): void {\n const prevEvents = this.events.get(eventName) || []\n const nextEvents = prevEvents.concat(listener)\n this.events.set(eventName, nextEvents)\n\n this.logger.info('registered event \"%s\"', eventName, listener)\n }\n\n /**\n * Responds to the current request with the given\n * Fetch API `Response` instance.\n */\n public respondWith(response: Response): void {\n this.logger.info(\n 'responding with a mocked response: %d %s',\n response.status,\n response.statusText\n )\n\n /**\n * @note Since `XMLHttpRequestController` delegates the handling of the responses\n * to the \"load\" event listener that doesn't distinguish between the mocked and original\n * responses, mark the request that had a mocked response with a corresponding symbol.\n */\n define(this.request, IS_MOCKED_RESPONSE, true)\n\n define(this.request, 'status', response.status)\n define(this.request, 'statusText', response.statusText)\n define(this.request, 'responseURL', this.url.href)\n\n this.request.getResponseHeader = new Proxy(this.request.getResponseHeader, {\n apply: (_, __, args: [name: string]) => {\n this.logger.info('getResponseHeader', args[0])\n\n if (this.request.readyState < this.request.HEADERS_RECEIVED) {\n this.logger.info('headers not received yet, returning null')\n\n // Headers not received yet, nothing to return.\n return null\n }\n\n const headerValue = response.headers.get(args[0])\n this.logger.info(\n 'resolved response header \"%s\" to',\n args[0],\n headerValue\n )\n\n return headerValue\n },\n })\n\n this.request.getAllResponseHeaders = new Proxy(\n this.request.getAllResponseHeaders,\n {\n apply: () => {\n this.logger.info('getAllResponseHeaders')\n\n if (this.request.readyState < this.request.HEADERS_RECEIVED) {\n this.logger.info('headers not received yet, returning empty string')\n\n // Headers not received yet, nothing to return.\n return ''\n }\n\n const headersList = Array.from(response.headers.entries())\n const allHeaders = headersList\n .map(([headerName, headerValue]) => {\n return `${headerName}: ${headerValue}`\n })\n .join('\\r\\n')\n\n this.logger.info('resolved all response headers to', allHeaders)\n\n return allHeaders\n },\n }\n )\n\n // Update the response getters to resolve against the mocked response.\n Object.defineProperties(this.request, {\n response: {\n enumerable: true,\n configurable: false,\n get: () => this.response,\n },\n responseText: {\n enumerable: true,\n configurable: false,\n get: () => this.responseText,\n },\n responseXML: {\n enumerable: true,\n configurable: false,\n get: () => this.responseXML,\n },\n })\n\n const totalResponseBodyLength = response.headers.has('Content-Length')\n ? Number(response.headers.get('Content-Length'))\n : /**\n * @todo Infer the response body length from the response body.\n */\n undefined\n\n this.logger.info('calculated response body length', totalResponseBodyLength)\n\n this.trigger('loadstart', {\n loaded: 0,\n total: totalResponseBodyLength,\n })\n\n this.setReadyState(this.request.HEADERS_RECEIVED)\n this.setReadyState(this.request.LOADING)\n\n const finalizeResponse = () => {\n this.logger.info('finalizing the mocked response...')\n\n this.setReadyState(this.request.DONE)\n\n this.trigger('load', {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n\n this.trigger('loadend', {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n }\n\n if (response.body) {\n this.logger.info('mocked response has body, streaming...')\n\n const reader = response.body.getReader()\n\n const readNextResponseBodyChunk = async () => {\n const { value, done } = await reader.read()\n\n if (done) {\n this.logger.info('response body stream done!')\n finalizeResponse()\n return\n }\n\n if (value) {\n this.logger.info('read response body chunk:', value)\n this.responseBuffer = concatArrayBuffer(this.responseBuffer, value)\n\n this.trigger('progress', {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n }\n\n readNextResponseBodyChunk()\n }\n\n readNextResponseBodyChunk()\n } else {\n finalizeResponse()\n }\n }\n\n private responseBufferToText(): string {\n return decodeBuffer(this.responseBuffer)\n }\n\n get response(): unknown {\n this.logger.info(\n 'getResponse (responseType: %s)',\n this.request.responseType\n )\n\n if (this.request.readyState !== this.request.DONE) {\n return null\n }\n\n switch (this.request.responseType) {\n case 'json': {\n const responseJson = parseJson(this.responseBufferToText())\n this.logger.info('resolved response JSON', responseJson)\n\n return responseJson\n }\n\n case 'arraybuffer': {\n const arrayBuffer = toArrayBuffer(this.responseBuffer)\n this.logger.info('resolved response ArrayBuffer', arrayBuffer)\n\n return arrayBuffer\n }\n\n case 'blob': {\n const mimeType =\n this.request.getResponseHeader('Content-Type') || 'text/plain'\n const responseBlob = new Blob([this.responseBufferToText()], {\n type: mimeType,\n })\n\n this.logger.info(\n 'resolved response Blob (mime type: %s)',\n responseBlob,\n mimeType\n )\n\n return responseBlob\n }\n\n default: {\n const responseText = this.responseBufferToText()\n this.logger.info(\n 'resolving \"%s\" response type as text',\n this.request.responseType,\n responseText\n )\n\n return responseText\n }\n }\n }\n\n get responseText(): string {\n /**\n * Throw when trying to read the response body as text when the\n * \"responseType\" doesn't expect text. This just respects the spec better.\n * @see https://xhr.spec.whatwg.org/#the-responsetext-attribute\n */\n invariant(\n this.request.responseType === '' || this.request.responseType === 'text',\n 'InvalidStateError: The object is in invalid state.'\n )\n\n if (\n this.request.readyState !== this.request.LOADING &&\n this.request.readyState !== this.request.DONE\n ) {\n return ''\n }\n\n const responseText = this.responseBufferToText()\n this.logger.info('getResponseText: \"%s\"', responseText)\n\n return responseText\n }\n\n get responseXML(): Document | null {\n invariant(\n this.request.responseType === '' ||\n this.request.responseType === 'document',\n 'InvalidStateError: The object is in invalid state.'\n )\n\n if (this.request.readyState !== this.request.DONE) {\n return null\n }\n\n const contentType = this.request.getResponseHeader('Content-Type') || ''\n\n if (typeof DOMParser === 'undefined') {\n console.warn(\n 'Cannot retrieve XMLHttpRequest response body as XML: DOMParser is not defined. You are likely using an environment that is not browser or does not polyfill browser globals correctly.'\n )\n return null\n }\n\n if (isDomParserSupportedType(contentType)) {\n return new DOMParser().parseFromString(\n this.responseBufferToText(),\n contentType\n )\n }\n\n return null\n }\n\n public errorWith(error: Error): void {\n this.logger.info('responding with an error')\n\n this.setReadyState(this.request.DONE)\n this.trigger('error')\n this.trigger('loadend')\n }\n\n /**\n * Transitions this request's `readyState` to the given one.\n */\n private setReadyState(nextReadyState: number): void {\n this.logger.info(\n 'setReadyState: %d -> %d',\n this.request.readyState,\n nextReadyState\n )\n\n if (this.request.readyState === nextReadyState) {\n this.logger.info('ready state identical, skipping transition...')\n return\n }\n\n define(this.request, 'readyState', nextReadyState)\n\n this.logger.info('set readyState to: %d', nextReadyState)\n\n if (nextReadyState !== this.request.UNSENT) {\n this.logger.info('triggerring \"readystatechange\" event...')\n\n this.trigger('readystatechange')\n }\n }\n\n /**\n * Triggers given event on the `XMLHttpRequest` instance.\n */\n private trigger<\n EventName extends keyof (XMLHttpRequestEventTargetEventMap & {\n readystatechange: ProgressEvent\n })\n >(eventName: EventName, options?: ProgressEventInit): void {\n const callback = this.request[`on${eventName}`]\n const event = createEvent(this.request, eventName, options)\n\n this.logger.info('trigger \"%s\"', eventName, options || '')\n\n // Invoke direct callbacks.\n if (typeof callback === 'function') {\n this.logger.info('found a direct \"%s\" callback, calling...', eventName)\n callback.call(this.request, event)\n }\n\n // Invoke event listeners.\n for (const [registeredEventName, listeners] of this.events) {\n if (registeredEventName === eventName) {\n this.logger.info(\n 'found %d listener(s) for \"%s\" event, calling...',\n listeners.length,\n eventName\n )\n\n listeners.forEach((listener) => listener.call(this.request, event))\n }\n }\n }\n\n /**\n * Converts this `XMLHttpRequest` instance into a Fetch API `Request` instance.\n */\n public toFetchApiRequest(): Request {\n this.logger.info('converting request to a Fetch API Request...')\n\n const fetchRequest = new Request(this.url.href, {\n method: this.method,\n headers: this.requestHeaders,\n /**\n * @see https://xhr.spec.whatwg.org/#cross-origin-credentials\n */\n credentials: this.request.withCredentials ? 'include' : 'same-origin',\n body: ['GET', 'HEAD'].includes(this.method)\n ? null\n : (this.requestBody as BodyInit),\n })\n\n const proxyHeaders = createProxy(fetchRequest.headers, {\n methodCall: ([methodName, args], invoke) => {\n // Forward the latest state of the internal request headers\n // because the interceptor might have modified them\n // without responding to the request.\n switch (methodName) {\n case 'append':\n case 'set': {\n const [headerName, headerValue] = args as [string, string]\n this.request.setRequestHeader(headerName, headerValue)\n break\n }\n\n case 'delete': {\n const [headerName] = args as [string]\n console.warn(\n `XMLHttpRequest: Cannot remove a \"${headerName}\" header from the Fetch API representation of the \"${fetchRequest.method} ${fetchRequest.url}\" request. XMLHttpRequest headers cannot be removed.`\n )\n break\n }\n }\n\n return invoke()\n },\n })\n define(fetchRequest, 'headers', proxyHeaders)\n\n this.logger.info('converted request to a Fetch API Request!', fetchRequest)\n\n return fetchRequest\n }\n}\n\nfunction toAbsoluteUrl(url: string | URL): URL {\n /**\n * @note XMLHttpRequest interceptor may run in environments\n * that implement XMLHttpRequest but don't implement \"location\"\n * (for example, React Native). If that's the case, return the\n * input URL as-is (nothing to be relative to).\n * @see https://github.com/mswjs/msw/issues/1777\n */\n if (typeof location === 'undefined') {\n return new URL(url)\n }\n\n return new URL(url.toString(), location.href)\n}\n\nfunction define(\n target: object,\n property: string | symbol,\n value: unknown\n): void {\n Reflect.defineProperty(target, property, {\n // Ensure writable properties to allow redefining readonly properties.\n writable: true,\n enumerable: true,\n value,\n })\n}\n","/**\n * Concatenate two `Uint8Array` buffers.\n */\nexport function concatArrayBuffer(\n left: Uint8Array,\n right: Uint8Array\n): Uint8Array {\n const result = new Uint8Array(left.byteLength + right.byteLength)\n result.set(left, 0)\n result.set(right, left.byteLength)\n return result\n}\n","export class EventPolyfill implements Event {\n readonly AT_TARGET: number = 0\n readonly BUBBLING_PHASE: number = 0\n readonly CAPTURING_PHASE: number = 0\n readonly NONE: number = 0\n\n public type: string = ''\n public srcElement: EventTarget | null = null\n public target: EventTarget | null\n public currentTarget: EventTarget | null = null\n public eventPhase: number = 0\n public timeStamp: number\n public isTrusted: boolean = true\n public composed: boolean = false\n public cancelable: boolean = true\n public defaultPrevented: boolean = false\n public bubbles: boolean = true\n public lengthComputable: boolean = true\n public loaded: number = 0\n public total: number = 0\n\n cancelBubble: boolean = false\n returnValue: boolean = true\n\n constructor(\n type: string,\n options?: { target: EventTarget; currentTarget: EventTarget }\n ) {\n this.type = type\n this.target = options?.target || null\n this.currentTarget = options?.currentTarget || null\n this.timeStamp = Date.now()\n }\n\n public composedPath(): EventTarget[] {\n return []\n }\n\n public initEvent(type: string, bubbles?: boolean, cancelable?: boolean) {\n this.type = type\n this.bubbles = !!bubbles\n this.cancelable = !!cancelable\n }\n\n public preventDefault() {\n this.defaultPrevented = true\n }\n\n public stopPropagation() {}\n public stopImmediatePropagation() {}\n}\n","import { EventPolyfill } from './EventPolyfill'\n\nexport class ProgressEventPolyfill extends EventPolyfill {\n readonly lengthComputable: boolean\n readonly composed: boolean\n readonly loaded: number\n readonly total: number\n\n constructor(type: string, init?: ProgressEventInit) {\n super(type)\n\n this.lengthComputable = init?.lengthComputable || false\n this.composed = init?.composed || false\n this.loaded = init?.loaded || 0\n this.total = init?.total || 0\n }\n}\n","import { EventPolyfill } from '../polyfills/EventPolyfill'\nimport { ProgressEventPolyfill } from '../polyfills/ProgressEventPolyfill'\n\nconst SUPPORTS_PROGRESS_EVENT = typeof ProgressEvent !== 'undefined'\n\nexport function createEvent(\n target: XMLHttpRequest,\n type: string,\n init?: ProgressEventInit\n): EventPolyfill {\n const progressEvents = [\n 'error',\n 'progress',\n 'loadstart',\n 'loadend',\n 'load',\n 'timeout',\n 'abort',\n ]\n\n /**\n * `ProgressEvent` is not supported in React Native.\n * @see https://github.com/mswjs/interceptors/issues/40\n */\n const ProgressEventClass = SUPPORTS_PROGRESS_EVENT\n ? ProgressEvent\n : ProgressEventPolyfill\n\n const event = progressEvents.includes(type)\n ? new ProgressEventClass(type, {\n lengthComputable: true,\n loaded: init?.loaded || 0,\n total: init?.total || 0,\n })\n : new EventPolyfill(type, {\n target,\n currentTarget: target,\n })\n\n return event\n}\n","/**\n * Returns the source object of the given property on the target object\n * (the target itself, any parent in its prototype, or null).\n */\nexport function findPropertySource(\n target: object,\n propertyName: string | symbol\n): object | null {\n if (!(propertyName in target)) {\n return null\n }\n\n const hasProperty = Object.prototype.hasOwnProperty.call(target, propertyName)\n if (hasProperty) {\n return target\n }\n\n const prototype = Reflect.getPrototypeOf(target)\n return prototype ? findPropertySource(prototype, propertyName) : null\n}\n","import { findPropertySource } from './findPropertySource'\n\nexport interface ProxyOptions> {\n constructorCall?(args: Array, next: NextFunction): Target\n\n methodCall?(\n this: Target,\n data: [methodName: F, args: Array],\n next: NextFunction\n ): void\n\n setProperty?(\n data: [propertyName: string | symbol, nextValue: unknown],\n next: NextFunction\n ): boolean\n\n getProperty?(\n data: [propertyName: string | symbol, receiver: Target],\n next: NextFunction\n ): void\n}\n\nexport type NextFunction = () => ReturnType\n\nexport function createProxy(\n target: Target,\n options: ProxyOptions\n): Target {\n const proxy = new Proxy(target, optionsToProxyHandler(options))\n\n return proxy\n}\n\nfunction optionsToProxyHandler>(\n options: ProxyOptions\n): ProxyHandler {\n const { constructorCall, methodCall, getProperty, setProperty } = options\n const handler: ProxyHandler = {}\n\n if (typeof constructorCall !== 'undefined') {\n handler.construct = function (target, args, newTarget) {\n const next = Reflect.construct.bind(null, target as any, args, newTarget)\n return constructorCall.call(newTarget, args, next)\n }\n }\n\n handler.set = function (target, propertyName, nextValue) {\n const next = () => {\n const propertySource = findPropertySource(target, propertyName) || target\n const ownDescriptors = Reflect.getOwnPropertyDescriptor(\n propertySource,\n propertyName\n )\n\n // Respect any custom setters present for this property.\n if (typeof ownDescriptors?.set !== 'undefined') {\n ownDescriptors.set.apply(target, [nextValue])\n return true\n }\n\n // Otherwise, set the property on the source.\n return Reflect.defineProperty(propertySource, propertyName, {\n writable: true,\n enumerable: true,\n configurable: true,\n value: nextValue,\n })\n }\n\n if (typeof setProperty !== 'undefined') {\n return setProperty.call(target, [propertyName, nextValue], next)\n }\n\n return next()\n }\n\n handler.get = function (target, propertyName, receiver) {\n /**\n * @note Using `Reflect.get()` here causes \"TypeError: Illegal invocation\".\n */\n const next = () => target[propertyName as any]\n\n const value =\n typeof getProperty !== 'undefined'\n ? getProperty.call(target, [propertyName, receiver], next)\n : next()\n\n if (typeof value === 'function') {\n return (...args: Array) => {\n const next = value.bind(target, ...args)\n\n if (typeof methodCall !== 'undefined') {\n return methodCall.call(target, [propertyName as any, args], next)\n }\n\n return next()\n }\n }\n\n return value\n }\n\n return handler\n}\n","export function isDomParserSupportedType(\n type: string\n): type is DOMParserSupportedType {\n const supportedTypes: Array = [\n 'application/xhtml+xml',\n 'application/xml',\n 'image/svg+xml',\n 'text/html',\n 'text/xml',\n ]\n return supportedTypes.some((supportedType) => {\n return type.startsWith(supportedType)\n })\n}\n","/**\n * Parses a given string into JSON.\n * Gracefully handles invalid JSON by returning `null`.\n */\nexport function parseJson(data: string): Record | null {\n try {\n const json = JSON.parse(data)\n return json\n } catch (_) {\n return null\n }\n}\n","import { isResponseWithoutBody } from '../../../utils/responseUtils'\n\n/**\n * Creates a Fetch API `Response` instance from the given\n * `XMLHttpRequest` instance and a response body.\n */\nexport function createResponse(\n request: XMLHttpRequest,\n body: BodyInit | null\n): Response {\n /**\n * Handle XMLHttpRequest responses that must have null as the\n * response body when represented using Fetch API Response.\n * XMLHttpRequest response will always have an empty string\n * as the \"request.response\" in those cases, resulting in an error\n * when constructing a Response instance.\n * @see https://github.com/mswjs/interceptors/issues/379\n */\n const responseBodyOrNull = isResponseWithoutBody(request.status) ? null : body\n\n return new Response(responseBodyOrNull, {\n status: request.status,\n statusText: request.statusText,\n headers: createHeadersFromXMLHttpReqestHeaders(\n request.getAllResponseHeaders()\n ),\n })\n}\n\nfunction createHeadersFromXMLHttpReqestHeaders(headersString: string): Headers {\n const headers = new Headers()\n\n const lines = headersString.split(/[\\r\\n]+/)\n for (const line of lines) {\n if (line.trim() === '') {\n continue\n }\n\n const [name, ...parts] = line.split(': ')\n const value = parts.join(': ')\n\n headers.append(name, value)\n }\n\n return headers\n}\n"],"mappings":"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","names":["invariant","next","mockedResponse","invariant"]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/chunk-LK6DILFK.js b/node_modules/@mswjs/interceptors/lib/node/chunk-LK6DILFK.js new file mode 100644 index 0000000000000000000000000000000000000000..f41d9eae5715ee544bf3d8f597fd16e59a271f58 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/chunk-LK6DILFK.js @@ -0,0 +1,22 @@ +"use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/utils/bufferUtils.ts +var encoder = new TextEncoder(); +function encodeBuffer(text) { + return encoder.encode(text); +} +function decodeBuffer(buffer, encoding) { + const decoder = new TextDecoder(encoding); + return decoder.decode(buffer); +} +function toArrayBuffer(array) { + return array.buffer.slice( + array.byteOffset, + array.byteOffset + array.byteLength + ); +} + + + + + +exports.encodeBuffer = encodeBuffer; exports.decodeBuffer = decodeBuffer; exports.toArrayBuffer = toArrayBuffer; +//# sourceMappingURL=chunk-LK6DILFK.js.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/chunk-LK6DILFK.js.map b/node_modules/@mswjs/interceptors/lib/node/chunk-LK6DILFK.js.map new file mode 100644 index 0000000000000000000000000000000000000000..691683680b4e26eecaa7dfe2d0466c8f348eb21f --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/chunk-LK6DILFK.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/utils/bufferUtils.ts"],"names":[],"mappings":";AAAA,IAAM,UAAU,IAAI,YAAY;AAEzB,SAAS,aAAa,MAA0B;AACrD,SAAO,QAAQ,OAAO,IAAI;AAC5B;AAEO,SAAS,aAAa,QAAqB,UAA2B;AAC3E,QAAM,UAAU,IAAI,YAAY,QAAQ;AACxC,SAAO,QAAQ,OAAO,MAAM;AAC9B;AAOO,SAAS,cAAc,OAAgC;AAC5D,SAAO,MAAM,OAAO;AAAA,IAClB,MAAM;AAAA,IACN,MAAM,aAAa,MAAM;AAAA,EAC3B;AACF","sourcesContent":["const encoder = new TextEncoder()\n\nexport function encodeBuffer(text: string): Uint8Array {\n return encoder.encode(text)\n}\n\nexport function decodeBuffer(buffer: ArrayBuffer, encoding?: string): string {\n const decoder = new TextDecoder(encoding)\n return decoder.decode(buffer)\n}\n\n/**\n * Create an `ArrayBuffer` from the given `Uint8Array`.\n * Takes the byte offset into account to produce the right buffer\n * in the case when the buffer is bigger than the data view.\n */\nexport function toArrayBuffer(array: Uint8Array): ArrayBuffer {\n return array.buffer.slice(\n array.byteOffset,\n array.byteOffset + array.byteLength\n )\n}\n"]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/chunk-LTEXDYJ6.js b/node_modules/@mswjs/interceptors/lib/node/chunk-LTEXDYJ6.js new file mode 100644 index 0000000000000000000000000000000000000000..02c7d085610706524a858e4447c6e0e8a94131c2 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/chunk-LTEXDYJ6.js @@ -0,0 +1,51 @@ +"use strict";Object.defineProperty(exports, "__esModule", {value: true}); + +var _chunkE4AC7YACjs = require('./chunk-E4AC7YAC.js'); + +// src/BatchInterceptor.ts +var BatchInterceptor = class extends _chunkE4AC7YACjs.Interceptor { + constructor(options) { + BatchInterceptor.symbol = Symbol(options.name); + super(BatchInterceptor.symbol); + this.interceptors = options.interceptors; + } + setup() { + const logger = this.logger.extend("setup"); + logger.info("applying all %d interceptors...", this.interceptors.length); + for (const interceptor of this.interceptors) { + logger.info('applying "%s" interceptor...', interceptor.constructor.name); + interceptor.apply(); + logger.info("adding interceptor dispose subscription"); + this.subscriptions.push(() => interceptor.dispose()); + } + } + on(event, listener) { + for (const interceptor of this.interceptors) { + interceptor.on(event, listener); + } + return this; + } + once(event, listener) { + for (const interceptor of this.interceptors) { + interceptor.once(event, listener); + } + return this; + } + off(event, listener) { + for (const interceptor of this.interceptors) { + interceptor.off(event, listener); + } + return this; + } + removeAllListeners(event) { + for (const interceptors of this.interceptors) { + interceptors.removeAllListeners(event); + } + return this; + } +}; + + + +exports.BatchInterceptor = BatchInterceptor; +//# sourceMappingURL=chunk-LTEXDYJ6.js.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/chunk-LTEXDYJ6.js.map b/node_modules/@mswjs/interceptors/lib/node/chunk-LTEXDYJ6.js.map new file mode 100644 index 0000000000000000000000000000000000000000..968f3b814bfe2243dd7081d7252f51194244f9cd --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/chunk-LTEXDYJ6.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/BatchInterceptor.ts"],"names":[],"mappings":";;;;;AAsBO,IAAM,mBAAN,cAGG,YAAoB;AAAA,EAK5B,YAAY,SAAmD;AAC7D,qBAAiB,SAAS,OAAO,QAAQ,IAAI;AAC7C,UAAM,iBAAiB,MAAM;AAC7B,SAAK,eAAe,QAAQ;AAAA,EAC9B;AAAA,EAEU,QAAQ;AAChB,UAAM,SAAS,KAAK,OAAO,OAAO,OAAO;AAEzC,WAAO,KAAK,mCAAmC,KAAK,aAAa,MAAM;AAEvE,eAAW,eAAe,KAAK,cAAc;AAC3C,aAAO,KAAK,gCAAgC,YAAY,YAAY,IAAI;AACxE,kBAAY,MAAM;AAElB,aAAO,KAAK,yCAAyC;AACrD,WAAK,cAAc,KAAK,MAAM,YAAY,QAAQ,CAAC;AAAA,IACrD;AAAA,EACF;AAAA,EAEO,GACL,OACA,UACM;AAGN,eAAW,eAAe,KAAK,cAAc;AAC3C,kBAAY,GAAG,OAAO,QAAQ;AAAA,IAChC;AAEA,WAAO;AAAA,EACT;AAAA,EAEO,KACL,OACA,UACM;AACN,eAAW,eAAe,KAAK,cAAc;AAC3C,kBAAY,KAAK,OAAO,QAAQ;AAAA,IAClC;AAEA,WAAO;AAAA,EACT;AAAA,EAEO,IACL,OACA,UACM;AACN,eAAW,eAAe,KAAK,cAAc;AAC3C,kBAAY,IAAI,OAAO,QAAQ;AAAA,IACjC;AAEA,WAAO;AAAA,EACT;AAAA,EAEO,mBACL,OACM;AACN,eAAW,gBAAgB,KAAK,cAAc;AAC5C,mBAAa,mBAAmB,KAAK;AAAA,IACvC;AAEA,WAAO;AAAA,EACT;AACF","sourcesContent":["import { EventMap, Listener } from 'strict-event-emitter'\nimport { Interceptor, ExtractEventNames } from './Interceptor'\n\nexport interface BatchInterceptorOptions<\n InterceptorList extends ReadonlyArray>\n> {\n name: string\n interceptors: InterceptorList\n}\n\nexport type ExtractEventMapType<\n InterceptorList extends ReadonlyArray>\n> = InterceptorList extends ReadonlyArray\n ? InterceptorType extends Interceptor\n ? EventMap\n : never\n : never\n\n/**\n * A batch interceptor that exposes a single interface\n * to apply and operate with multiple interceptors at once.\n */\nexport class BatchInterceptor<\n InterceptorList extends ReadonlyArray>,\n Events extends EventMap = ExtractEventMapType\n> extends Interceptor {\n static symbol: symbol\n\n private interceptors: InterceptorList\n\n constructor(options: BatchInterceptorOptions) {\n BatchInterceptor.symbol = Symbol(options.name)\n super(BatchInterceptor.symbol)\n this.interceptors = options.interceptors\n }\n\n protected setup() {\n const logger = this.logger.extend('setup')\n\n logger.info('applying all %d interceptors...', this.interceptors.length)\n\n for (const interceptor of this.interceptors) {\n logger.info('applying \"%s\" interceptor...', interceptor.constructor.name)\n interceptor.apply()\n\n logger.info('adding interceptor dispose subscription')\n this.subscriptions.push(() => interceptor.dispose())\n }\n }\n\n public on>(\n event: EventName,\n listener: Listener\n ): this {\n // Instead of adding a listener to the batch interceptor,\n // propagate the listener to each of the individual interceptors.\n for (const interceptor of this.interceptors) {\n interceptor.on(event, listener)\n }\n\n return this\n }\n\n public once>(\n event: EventName,\n listener: Listener\n ): this {\n for (const interceptor of this.interceptors) {\n interceptor.once(event, listener)\n }\n\n return this\n }\n\n public off>(\n event: EventName,\n listener: Listener\n ): this {\n for (const interceptor of this.interceptors) {\n interceptor.off(event, listener)\n }\n\n return this\n }\n\n public removeAllListeners>(\n event?: EventName | undefined\n ): this {\n for (const interceptors of this.interceptors) {\n interceptors.removeAllListeners(event)\n }\n\n return this\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/chunk-MQJ3JOOK.js b/node_modules/@mswjs/interceptors/lib/node/chunk-MQJ3JOOK.js new file mode 100644 index 0000000000000000000000000000000000000000..97c07c992c5b0f7f959cf10ace5cef097d5ae577 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/chunk-MQJ3JOOK.js @@ -0,0 +1,49 @@ +"use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/utils/RequestController.ts +var _outvariant = require('outvariant'); +var _deferredpromise = require('@open-draft/deferred-promise'); +var RequestController = class { + constructor(request) { + this.request = request; + this.responsePromise = new (0, _deferredpromise.DeferredPromise)(); + } + respondWith(response) { + _outvariant.invariant.call(void 0, + this.responsePromise.state === "pending", + 'Failed to respond to "%s %s" request: the "request" event has already been responded to.', + this.request.method, + this.request.url + ); + this.responsePromise.resolve(response); + } +}; + +// src/utils/toInteractiveRequest.ts +function toInteractiveRequest(request) { + const requestController = new RequestController(request); + Reflect.set( + request, + "respondWith", + requestController.respondWith.bind(requestController) + ); + return { + interactiveRequest: request, + requestController + }; +} + +// src/utils/emitAsync.ts +async function emitAsync(emitter, eventName, ...data) { + const listners = emitter.listeners(eventName); + if (listners.length === 0) { + return; + } + for (const listener of listners) { + await listener.apply(emitter, data); + } +} + + + + +exports.toInteractiveRequest = toInteractiveRequest; exports.emitAsync = emitAsync; +//# sourceMappingURL=chunk-MQJ3JOOK.js.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/chunk-MQJ3JOOK.js.map b/node_modules/@mswjs/interceptors/lib/node/chunk-MQJ3JOOK.js.map new file mode 100644 index 0000000000000000000000000000000000000000..300c2a93afe208427c3fc164257f75747e843566 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/chunk-MQJ3JOOK.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/utils/RequestController.ts","../../src/utils/toInteractiveRequest.ts","../../src/utils/emitAsync.ts"],"names":[],"mappings":";AAAA,SAAS,iBAAiB;AAC1B,SAAS,uBAAuB;AAEzB,IAAM,oBAAN,MAAwB;AAAA,EAG7B,YAAsB,SAAkB;AAAlB;AACpB,SAAK,kBAAkB,IAAI,gBAAgB;AAAA,EAC7C;AAAA,EAEO,YAAY,UAA2B;AAC5C;AAAA,MACE,KAAK,gBAAgB,UAAU;AAAA,MAC/B;AAAA,MACA,KAAK,QAAQ;AAAA,MACb,KAAK,QAAQ;AAAA,IACf;AAEA,SAAK,gBAAgB,QAAQ,QAAQ;AAAA,EACvC;AACF;;;ACdO,SAAS,qBAAqB,SAGnC;AACA,QAAM,oBAAoB,IAAI,kBAAkB,OAAO;AAEvD,UAAQ;AAAA,IACN;AAAA,IACA;AAAA,IACA,kBAAkB,YAAY,KAAK,iBAAiB;AAAA,EACtD;AAEA,SAAO;AAAA,IACL,oBAAoB;AAAA,IACpB;AAAA,EACF;AACF;;;ACfA,eAAsB,UAIpB,SACA,cACG,MACY;AACf,QAAM,WAAW,QAAQ,UAAU,SAAS;AAE5C,MAAI,SAAS,WAAW,GAAG;AACzB;AAAA,EACF;AAEA,aAAW,YAAY,UAAU;AAC/B,UAAM,SAAS,MAAM,SAAS,IAAI;AAAA,EACpC;AACF","sourcesContent":["import { invariant } from 'outvariant'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\n\nexport class RequestController {\n public responsePromise: DeferredPromise\n\n constructor(protected request: Request) {\n this.responsePromise = new DeferredPromise()\n }\n\n public respondWith(response?: Response): void {\n invariant(\n this.responsePromise.state === 'pending',\n 'Failed to respond to \"%s %s\" request: the \"request\" event has already been responded to.',\n this.request.method,\n this.request.url\n )\n\n this.responsePromise.resolve(response)\n }\n}\n","import { RequestController } from './RequestController'\n\nexport type InteractiveRequest = globalThis.Request & {\n respondWith: RequestController['respondWith']\n}\n\nexport function toInteractiveRequest(request: Request): {\n interactiveRequest: InteractiveRequest\n requestController: RequestController\n} {\n const requestController = new RequestController(request)\n\n Reflect.set(\n request,\n 'respondWith',\n requestController.respondWith.bind(requestController)\n )\n\n return {\n interactiveRequest: request as InteractiveRequest,\n requestController,\n }\n}\n","import { Emitter, EventMap } from 'strict-event-emitter'\n\n/**\n * Emits an event on the given emitter but executes\n * the listeners sequentially. This accounts for asynchronous\n * listeners (e.g. those having \"sleep\" and handling the request).\n */\nexport async function emitAsync<\n Events extends EventMap,\n EventName extends keyof Events\n>(\n emitter: Emitter,\n eventName: EventName,\n ...data: Events[EventName]\n): Promise {\n const listners = emitter.listeners(eventName)\n\n if (listners.length === 0) {\n return\n }\n\n for (const listener of listners) {\n await listener.apply(emitter, data)\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/chunk-OJ6O4LSC.mjs b/node_modules/@mswjs/interceptors/lib/node/chunk-OJ6O4LSC.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4e50cac43016fc6e92c45cf4f622ab0e18d6d80d --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/chunk-OJ6O4LSC.mjs @@ -0,0 +1,7 @@ +// src/glossary.ts +var IS_PATCHED_MODULE = Symbol("isPatchedModule"); + +export { + IS_PATCHED_MODULE +}; +//# sourceMappingURL=chunk-OJ6O4LSC.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/chunk-OJ6O4LSC.mjs.map b/node_modules/@mswjs/interceptors/lib/node/chunk-OJ6O4LSC.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..5ae019d1470aeb4fbcdfddc70f5727566c87549e --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/chunk-OJ6O4LSC.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/glossary.ts"],"sourcesContent":["import type { InteractiveRequest } from './utils/toInteractiveRequest'\n\nexport const IS_PATCHED_MODULE: unique symbol = Symbol('isPatchedModule')\n\nexport type RequestCredentials = 'omit' | 'include' | 'same-origin'\n\nexport type HttpRequestEventMap = {\n request: [\n args: {\n request: InteractiveRequest\n requestId: string\n }\n ]\n response: [\n args: {\n response: Response\n isMockedResponse: boolean\n request: Request\n requestId: string\n }\n ]\n unhandledException: [\n args: {\n error: unknown\n request: Request\n requestId: string\n controller: {\n respondWith(response: Response): void\n errorWith(error?: Error): void\n }\n }\n ]\n}\n"],"mappings":";AAEO,IAAM,oBAAmC,OAAO,iBAAiB;","names":[]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/chunk-OUWBQF3Z.mjs b/node_modules/@mswjs/interceptors/lib/node/chunk-OUWBQF3Z.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1446bd22220684eb39d551da6f884cfc32e18d70 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/chunk-OUWBQF3Z.mjs @@ -0,0 +1,49 @@ +// src/utils/RequestController.ts +import { invariant } from "outvariant"; +import { DeferredPromise } from "@open-draft/deferred-promise"; +var RequestController = class { + constructor(request) { + this.request = request; + this.responsePromise = new DeferredPromise(); + } + respondWith(response) { + invariant( + this.responsePromise.state === "pending", + 'Failed to respond to "%s %s" request: the "request" event has already been responded to.', + this.request.method, + this.request.url + ); + this.responsePromise.resolve(response); + } +}; + +// src/utils/toInteractiveRequest.ts +function toInteractiveRequest(request) { + const requestController = new RequestController(request); + Reflect.set( + request, + "respondWith", + requestController.respondWith.bind(requestController) + ); + return { + interactiveRequest: request, + requestController + }; +} + +// src/utils/emitAsync.ts +async function emitAsync(emitter, eventName, ...data) { + const listners = emitter.listeners(eventName); + if (listners.length === 0) { + return; + } + for (const listener of listners) { + await listener.apply(emitter, data); + } +} + +export { + toInteractiveRequest, + emitAsync +}; +//# sourceMappingURL=chunk-OUWBQF3Z.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/chunk-OUWBQF3Z.mjs.map b/node_modules/@mswjs/interceptors/lib/node/chunk-OUWBQF3Z.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..59c0e41729fb5411491de7308ab5ef869a3818dd --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/chunk-OUWBQF3Z.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/utils/RequestController.ts","../../src/utils/toInteractiveRequest.ts","../../src/utils/emitAsync.ts"],"sourcesContent":["import { invariant } from 'outvariant'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\n\nexport class RequestController {\n public responsePromise: DeferredPromise\n\n constructor(protected request: Request) {\n this.responsePromise = new DeferredPromise()\n }\n\n public respondWith(response?: Response): void {\n invariant(\n this.responsePromise.state === 'pending',\n 'Failed to respond to \"%s %s\" request: the \"request\" event has already been responded to.',\n this.request.method,\n this.request.url\n )\n\n this.responsePromise.resolve(response)\n }\n}\n","import { RequestController } from './RequestController'\n\nexport type InteractiveRequest = globalThis.Request & {\n respondWith: RequestController['respondWith']\n}\n\nexport function toInteractiveRequest(request: Request): {\n interactiveRequest: InteractiveRequest\n requestController: RequestController\n} {\n const requestController = new RequestController(request)\n\n Reflect.set(\n request,\n 'respondWith',\n requestController.respondWith.bind(requestController)\n )\n\n return {\n interactiveRequest: request as InteractiveRequest,\n requestController,\n }\n}\n","import { Emitter, EventMap } from 'strict-event-emitter'\n\n/**\n * Emits an event on the given emitter but executes\n * the listeners sequentially. This accounts for asynchronous\n * listeners (e.g. those having \"sleep\" and handling the request).\n */\nexport async function emitAsync<\n Events extends EventMap,\n EventName extends keyof Events\n>(\n emitter: Emitter,\n eventName: EventName,\n ...data: Events[EventName]\n): Promise {\n const listners = emitter.listeners(eventName)\n\n if (listners.length === 0) {\n return\n }\n\n for (const listener of listners) {\n await listener.apply(emitter, data)\n }\n}\n"],"mappings":";AAAA,SAAS,iBAAiB;AAC1B,SAAS,uBAAuB;AAEzB,IAAM,oBAAN,MAAwB;AAAA,EAG7B,YAAsB,SAAkB;AAAlB;AACpB,SAAK,kBAAkB,IAAI,gBAAgB;AAAA,EAC7C;AAAA,EAEO,YAAY,UAA2B;AAC5C;AAAA,MACE,KAAK,gBAAgB,UAAU;AAAA,MAC/B;AAAA,MACA,KAAK,QAAQ;AAAA,MACb,KAAK,QAAQ;AAAA,IACf;AAEA,SAAK,gBAAgB,QAAQ,QAAQ;AAAA,EACvC;AACF;;;ACdO,SAAS,qBAAqB,SAGnC;AACA,QAAM,oBAAoB,IAAI,kBAAkB,OAAO;AAEvD,UAAQ;AAAA,IACN;AAAA,IACA;AAAA,IACA,kBAAkB,YAAY,KAAK,iBAAiB;AAAA,EACtD;AAEA,SAAO;AAAA,IACL,oBAAoB;AAAA,IACpB;AAAA,EACF;AACF;;;ACfA,eAAsB,UAIpB,SACA,cACG,MACY;AACf,QAAM,WAAW,QAAQ,UAAU,SAAS;AAE5C,MAAI,SAAS,WAAW,GAAG;AACzB;AAAA,EACF;AAEA,aAAW,YAAY,UAAU;AAC/B,UAAM,SAAS,MAAM,SAAS,IAAI;AAAA,EACpC;AACF;","names":[]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/chunk-Q7POAM5N.mjs b/node_modules/@mswjs/interceptors/lib/node/chunk-Q7POAM5N.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b52f0412d95950057dd04f52187902c3a78b3b37 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/chunk-Q7POAM5N.mjs @@ -0,0 +1,215 @@ +// src/Interceptor.ts +import { Logger } from "@open-draft/logger"; +import { Emitter } from "strict-event-emitter"; +var INTERNAL_REQUEST_ID_HEADER_NAME = "x-interceptors-internal-request-id"; +function getGlobalSymbol(symbol) { + return ( + // @ts-ignore https://github.com/Microsoft/TypeScript/issues/24587 + globalThis[symbol] || void 0 + ); +} +function setGlobalSymbol(symbol, value) { + globalThis[symbol] = value; +} +function deleteGlobalSymbol(symbol) { + delete globalThis[symbol]; +} +var InterceptorReadyState = /* @__PURE__ */ ((InterceptorReadyState2) => { + InterceptorReadyState2["INACTIVE"] = "INACTIVE"; + InterceptorReadyState2["APPLYING"] = "APPLYING"; + InterceptorReadyState2["APPLIED"] = "APPLIED"; + InterceptorReadyState2["DISPOSING"] = "DISPOSING"; + InterceptorReadyState2["DISPOSED"] = "DISPOSED"; + return InterceptorReadyState2; +})(InterceptorReadyState || {}); +var Interceptor = class { + constructor(symbol) { + this.symbol = symbol; + this.readyState = "INACTIVE" /* INACTIVE */; + this.emitter = new Emitter(); + this.subscriptions = []; + this.logger = new Logger(symbol.description); + this.emitter.setMaxListeners(0); + this.logger.info("constructing the interceptor..."); + } + /** + * Determine if this interceptor can be applied + * in the current environment. + */ + checkEnvironment() { + return true; + } + /** + * Apply this interceptor to the current process. + * Returns an already running interceptor instance if it's present. + */ + apply() { + const logger = this.logger.extend("apply"); + logger.info("applying the interceptor..."); + if (this.readyState === "APPLIED" /* APPLIED */) { + logger.info("intercepted already applied!"); + return; + } + const shouldApply = this.checkEnvironment(); + if (!shouldApply) { + logger.info("the interceptor cannot be applied in this environment!"); + return; + } + this.readyState = "APPLYING" /* APPLYING */; + const runningInstance = this.getInstance(); + if (runningInstance) { + logger.info("found a running instance, reusing..."); + this.on = (event, listener) => { + logger.info('proxying the "%s" listener', event); + runningInstance.emitter.addListener(event, listener); + this.subscriptions.push(() => { + runningInstance.emitter.removeListener(event, listener); + logger.info('removed proxied "%s" listener!', event); + }); + return this; + }; + this.readyState = "APPLIED" /* APPLIED */; + return; + } + logger.info("no running instance found, setting up a new instance..."); + this.setup(); + this.setInstance(); + this.readyState = "APPLIED" /* APPLIED */; + } + /** + * Setup the module augments and stubs necessary for this interceptor. + * This method is not run if there's a running interceptor instance + * to prevent instantiating an interceptor multiple times. + */ + setup() { + } + /** + * Listen to the interceptor's public events. + */ + on(event, listener) { + const logger = this.logger.extend("on"); + if (this.readyState === "DISPOSING" /* DISPOSING */ || this.readyState === "DISPOSED" /* DISPOSED */) { + logger.info("cannot listen to events, already disposed!"); + return this; + } + logger.info('adding "%s" event listener:', event, listener); + this.emitter.on(event, listener); + return this; + } + once(event, listener) { + this.emitter.once(event, listener); + return this; + } + off(event, listener) { + this.emitter.off(event, listener); + return this; + } + removeAllListeners(event) { + this.emitter.removeAllListeners(event); + return this; + } + /** + * Disposes of any side-effects this interceptor has introduced. + */ + dispose() { + const logger = this.logger.extend("dispose"); + if (this.readyState === "DISPOSED" /* DISPOSED */) { + logger.info("cannot dispose, already disposed!"); + return; + } + logger.info("disposing the interceptor..."); + this.readyState = "DISPOSING" /* DISPOSING */; + if (!this.getInstance()) { + logger.info("no interceptors running, skipping dispose..."); + return; + } + this.clearInstance(); + logger.info("global symbol deleted:", getGlobalSymbol(this.symbol)); + if (this.subscriptions.length > 0) { + logger.info("disposing of %d subscriptions...", this.subscriptions.length); + for (const dispose of this.subscriptions) { + dispose(); + } + this.subscriptions = []; + logger.info("disposed of all subscriptions!", this.subscriptions.length); + } + this.emitter.removeAllListeners(); + logger.info("destroyed the listener!"); + this.readyState = "DISPOSED" /* DISPOSED */; + } + getInstance() { + var _a; + const instance = getGlobalSymbol(this.symbol); + this.logger.info("retrieved global instance:", (_a = instance == null ? void 0 : instance.constructor) == null ? void 0 : _a.name); + return instance; + } + setInstance() { + setGlobalSymbol(this.symbol, this); + this.logger.info("set global instance!", this.symbol.description); + } + clearInstance() { + deleteGlobalSymbol(this.symbol); + this.logger.info("cleared global instance!", this.symbol.description); + } +}; + +// src/createRequestId.ts +function createRequestId() { + return Math.random().toString(16).slice(2); +} + +// src/utils/isPropertyAccessible.ts +function isPropertyAccessible(obj, key) { + try { + obj[key]; + return true; + } catch (e) { + return false; + } +} + +// src/utils/responseUtils.ts +var RESPONSE_STATUS_CODES_WITHOUT_BODY = /* @__PURE__ */ new Set([ + 101, + 103, + 204, + 205, + 304 +]); +function isResponseWithoutBody(status) { + return RESPONSE_STATUS_CODES_WITHOUT_BODY.has(status); +} +function createServerErrorResponse(body) { + return new Response( + JSON.stringify( + body instanceof Error ? { + name: body.name, + message: body.message, + stack: body.stack + } : body + ), + { + status: 500, + statusText: "Unhandled Exception", + headers: { + "Content-Type": "application/json" + } + } + ); +} +function isResponseError(response) { + return isPropertyAccessible(response, "type") && response.type === "error"; +} + +export { + INTERNAL_REQUEST_ID_HEADER_NAME, + getGlobalSymbol, + deleteGlobalSymbol, + InterceptorReadyState, + Interceptor, + createRequestId, + isResponseWithoutBody, + createServerErrorResponse, + isResponseError +}; +//# sourceMappingURL=chunk-Q7POAM5N.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/chunk-Q7POAM5N.mjs.map b/node_modules/@mswjs/interceptors/lib/node/chunk-Q7POAM5N.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..6b24737074a87a3eea2cb8ecba199abeb3aa13ce --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/chunk-Q7POAM5N.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/Interceptor.ts","../../src/createRequestId.ts","../../src/utils/isPropertyAccessible.ts","../../src/utils/responseUtils.ts"],"sourcesContent":["import { Logger } from '@open-draft/logger'\nimport { Emitter, Listener } from 'strict-event-emitter'\n\nexport type InterceptorEventMap = Record\nexport type InterceptorSubscription = () => void\n\n/**\n * Request header name to detect when a single request\n * is being handled by nested interceptors (XHR -> ClientRequest).\n * Obscure by design to prevent collisions with user-defined headers.\n * Ideally, come up with the Interceptor-level mechanism for this.\n * @see https://github.com/mswjs/interceptors/issues/378\n */\nexport const INTERNAL_REQUEST_ID_HEADER_NAME =\n 'x-interceptors-internal-request-id'\n\nexport function getGlobalSymbol(symbol: Symbol): V | undefined {\n return (\n // @ts-ignore https://github.com/Microsoft/TypeScript/issues/24587\n globalThis[symbol] || undefined\n )\n}\n\nfunction setGlobalSymbol(symbol: Symbol, value: any): void {\n // @ts-ignore\n globalThis[symbol] = value\n}\n\nexport function deleteGlobalSymbol(symbol: Symbol): void {\n // @ts-ignore\n delete globalThis[symbol]\n}\n\nexport enum InterceptorReadyState {\n INACTIVE = 'INACTIVE',\n APPLYING = 'APPLYING',\n APPLIED = 'APPLIED',\n DISPOSING = 'DISPOSING',\n DISPOSED = 'DISPOSED',\n}\n\nexport type ExtractEventNames> =\n Events extends Record ? EventName : never\n\nexport class Interceptor {\n protected emitter: Emitter\n protected subscriptions: Array\n protected logger: Logger\n\n public readyState: InterceptorReadyState\n\n constructor(private readonly symbol: symbol) {\n this.readyState = InterceptorReadyState.INACTIVE\n\n this.emitter = new Emitter()\n this.subscriptions = []\n this.logger = new Logger(symbol.description!)\n\n // Do not limit the maximum number of listeners\n // so not to limit the maximum amount of parallel events emitted.\n this.emitter.setMaxListeners(0)\n\n this.logger.info('constructing the interceptor...')\n }\n\n /**\n * Determine if this interceptor can be applied\n * in the current environment.\n */\n protected checkEnvironment(): boolean {\n return true\n }\n\n /**\n * Apply this interceptor to the current process.\n * Returns an already running interceptor instance if it's present.\n */\n public apply(): void {\n const logger = this.logger.extend('apply')\n logger.info('applying the interceptor...')\n\n if (this.readyState === InterceptorReadyState.APPLIED) {\n logger.info('intercepted already applied!')\n return\n }\n\n const shouldApply = this.checkEnvironment()\n\n if (!shouldApply) {\n logger.info('the interceptor cannot be applied in this environment!')\n return\n }\n\n this.readyState = InterceptorReadyState.APPLYING\n\n // Whenever applying a new interceptor, check if it hasn't been applied already.\n // This enables to apply the same interceptor multiple times, for example from a different\n // interceptor, only proxying events but keeping the stubs in a single place.\n const runningInstance = this.getInstance()\n\n if (runningInstance) {\n logger.info('found a running instance, reusing...')\n\n // Proxy any listeners you set on this instance to the running instance.\n this.on = (event, listener) => {\n logger.info('proxying the \"%s\" listener', event)\n\n // Add listeners to the running instance so they appear\n // at the top of the event listeners list and are executed first.\n runningInstance.emitter.addListener(event, listener)\n\n // Ensure that once this interceptor instance is disposed,\n // it removes all listeners it has appended to the running interceptor instance.\n this.subscriptions.push(() => {\n runningInstance.emitter.removeListener(event, listener)\n logger.info('removed proxied \"%s\" listener!', event)\n })\n\n return this\n }\n\n this.readyState = InterceptorReadyState.APPLIED\n\n return\n }\n\n logger.info('no running instance found, setting up a new instance...')\n\n // Setup the interceptor.\n this.setup()\n\n // Store the newly applied interceptor instance globally.\n this.setInstance()\n\n this.readyState = InterceptorReadyState.APPLIED\n }\n\n /**\n * Setup the module augments and stubs necessary for this interceptor.\n * This method is not run if there's a running interceptor instance\n * to prevent instantiating an interceptor multiple times.\n */\n protected setup(): void {}\n\n /**\n * Listen to the interceptor's public events.\n */\n public on>(\n event: EventName,\n listener: Listener\n ): this {\n const logger = this.logger.extend('on')\n\n if (\n this.readyState === InterceptorReadyState.DISPOSING ||\n this.readyState === InterceptorReadyState.DISPOSED\n ) {\n logger.info('cannot listen to events, already disposed!')\n return this\n }\n\n logger.info('adding \"%s\" event listener:', event, listener)\n\n this.emitter.on(event, listener)\n return this\n }\n\n public once>(\n event: EventName,\n listener: Listener\n ): this {\n this.emitter.once(event, listener)\n return this\n }\n\n public off>(\n event: EventName,\n listener: Listener\n ): this {\n this.emitter.off(event, listener)\n return this\n }\n\n public removeAllListeners>(\n event?: EventName\n ): this {\n this.emitter.removeAllListeners(event)\n return this\n }\n\n /**\n * Disposes of any side-effects this interceptor has introduced.\n */\n public dispose(): void {\n const logger = this.logger.extend('dispose')\n\n if (this.readyState === InterceptorReadyState.DISPOSED) {\n logger.info('cannot dispose, already disposed!')\n return\n }\n\n logger.info('disposing the interceptor...')\n this.readyState = InterceptorReadyState.DISPOSING\n\n if (!this.getInstance()) {\n logger.info('no interceptors running, skipping dispose...')\n return\n }\n\n // Delete the global symbol as soon as possible,\n // indicating that the interceptor is no longer running.\n this.clearInstance()\n\n logger.info('global symbol deleted:', getGlobalSymbol(this.symbol))\n\n if (this.subscriptions.length > 0) {\n logger.info('disposing of %d subscriptions...', this.subscriptions.length)\n\n for (const dispose of this.subscriptions) {\n dispose()\n }\n\n this.subscriptions = []\n\n logger.info('disposed of all subscriptions!', this.subscriptions.length)\n }\n\n this.emitter.removeAllListeners()\n logger.info('destroyed the listener!')\n\n this.readyState = InterceptorReadyState.DISPOSED\n }\n\n private getInstance(): this | undefined {\n const instance = getGlobalSymbol(this.symbol)\n this.logger.info('retrieved global instance:', instance?.constructor?.name)\n return instance\n }\n\n private setInstance(): void {\n setGlobalSymbol(this.symbol, this)\n this.logger.info('set global instance!', this.symbol.description)\n }\n\n private clearInstance(): void {\n deleteGlobalSymbol(this.symbol)\n this.logger.info('cleared global instance!', this.symbol.description)\n }\n}\n","/**\n * Generate a random ID string to represent a request.\n * @example\n * createRequestId()\n * // \"f774b6c9c600f\"\n */\nexport function createRequestId(): string {\n return Math.random().toString(16).slice(2)\n}\n","/**\n * A function that validates if property access is possible on an object\n * without throwing. It returns `true` if the property access is possible\n * and `false` otherwise.\n *\n * Environments like miniflare will throw on property access on certain objects\n * like Request and Response, for unimplemented properties.\n */\nexport function isPropertyAccessible>(\n obj: Obj,\n key: keyof Obj\n) {\n try {\n obj[key]\n return true\n } catch {\n return false\n }\n}\n","import { isPropertyAccessible } from './isPropertyAccessible'\n\n/**\n * Response status codes for responses that cannot have body.\n * @see https://fetch.spec.whatwg.org/#statuses\n */\nexport const RESPONSE_STATUS_CODES_WITHOUT_BODY = new Set([\n 101, 103, 204, 205, 304,\n])\n\n/**\n * Returns a boolean indicating whether the given response status\n * code represents a response that cannot have a body.\n */\nexport function isResponseWithoutBody(status: number): boolean {\n return RESPONSE_STATUS_CODES_WITHOUT_BODY.has(status)\n}\n\n/**\n * Creates a generic 500 Unhandled Exception response.\n */\nexport function createServerErrorResponse(body: unknown): Response {\n return new Response(\n JSON.stringify(\n body instanceof Error\n ? {\n name: body.name,\n message: body.message,\n stack: body.stack,\n }\n : body\n ),\n {\n status: 500,\n statusText: 'Unhandled Exception',\n headers: {\n 'Content-Type': 'application/json',\n },\n }\n )\n}\n\n/**\n * Checks if the given response is a `Response.error()`.\n *\n * @note Some environments, like Miniflare (Cloudflare) do not\n * implement the \"Response.type\" property and throw on its access.\n * Safely check if we can access \"type\" on \"Response\" before continuing.\n * @see https://github.com/mswjs/msw/issues/1834\n */\nexport function isResponseError(\n response: Response\n): response is Response & { type: 'error' } {\n return isPropertyAccessible(response, 'type') && response.type === 'error'\n}\n"],"mappings":"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","names":["InterceptorReadyState"]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/chunk-SXGRMPXP.js b/node_modules/@mswjs/interceptors/lib/node/chunk-SXGRMPXP.js new file mode 100644 index 0000000000000000000000000000000000000000..a5129f18a9b754acf2bfb3b1545df2378b01a95a --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/chunk-SXGRMPXP.js @@ -0,0 +1,889 @@ +"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + +var _chunkMQJ3JOOKjs = require('./chunk-MQJ3JOOK.js'); + + + + + + + +var _chunkE4AC7YACjs = require('./chunk-E4AC7YAC.js'); + +// src/interceptors/ClientRequest/index.ts +var _http = require('http'); var _http2 = _interopRequireDefault(_http); +var _https = require('https'); var _https2 = _interopRequireDefault(_https); + +// src/interceptors/ClientRequest/NodeClientRequest.ts + +var _until = require('@open-draft/until'); +var _deferredpromise = require('@open-draft/deferred-promise'); + +// src/interceptors/ClientRequest/utils/normalizeClientRequestEndArgs.ts +var _logger = require('@open-draft/logger'); +var logger = new (0, _logger.Logger)("utils getUrlByRequestOptions"); +function normalizeClientRequestEndArgs(...args) { + logger.info("arguments", args); + const normalizedArgs = new Array(3).fill(null).map((value, index) => args[index] || value); + normalizedArgs.sort((a, b) => { + if (typeof a === "function") { + return 1; + } + if (typeof b === "function") { + return -1; + } + if (typeof a === "string" && typeof b === "string") { + return normalizedArgs.indexOf(a) - normalizedArgs.indexOf(b); + } + return 0; + }); + logger.info("normalized args", normalizedArgs); + return normalizedArgs; +} + +// src/interceptors/ClientRequest/utils/normalizeClientRequestWriteArgs.ts + +var logger2 = new (0, _logger.Logger)("http normalizeWriteArgs"); +function normalizeClientRequestWriteArgs(args) { + logger2.info("normalizing ClientRequest.write arguments...", args); + const chunk = args[0]; + const encoding = typeof args[1] === "string" ? args[1] : void 0; + const callback = typeof args[1] === "function" ? args[1] : args[2]; + const writeArgs = [ + chunk, + encoding, + callback + ]; + logger2.info( + "successfully normalized ClientRequest.write arguments:", + writeArgs + ); + return writeArgs; +} + +// src/interceptors/ClientRequest/utils/cloneIncomingMessage.ts + +var _stream = require('stream'); +var IS_CLONE = Symbol("isClone"); +function cloneIncomingMessage(message) { + const clone = message.pipe(new (0, _stream.PassThrough)()); + inheritProperties(message, clone); + const clonedPrototype = Object.create(_http.IncomingMessage.prototype); + getPrototypes(clone).forEach((prototype) => { + inheritProperties(prototype, clonedPrototype); + }); + Object.setPrototypeOf(clone, clonedPrototype); + Object.defineProperty(clone, IS_CLONE, { + enumerable: true, + value: true + }); + return clone; +} +function getPrototypes(source) { + const prototypes = []; + let current = source; + while (current = Object.getPrototypeOf(current)) { + prototypes.push(current); + } + return prototypes; +} +function inheritProperties(source, target) { + const properties = [ + ...Object.getOwnPropertyNames(source), + ...Object.getOwnPropertySymbols(source) + ]; + for (const property of properties) { + if (target.hasOwnProperty(property)) { + continue; + } + const descriptor = Object.getOwnPropertyDescriptor(source, property); + if (!descriptor) { + continue; + } + Object.defineProperty(target, property, descriptor); + } +} + +// src/interceptors/ClientRequest/utils/createResponse.ts +function createResponse(message) { + const responseBodyOrNull = _chunkE4AC7YACjs.isResponseWithoutBody.call(void 0, message.statusCode || 200) ? null : new ReadableStream({ + start(controller) { + message.on("data", (chunk) => controller.enqueue(chunk)); + message.on("end", () => controller.close()); + } + }); + return new Response(responseBodyOrNull, { + status: message.statusCode, + statusText: message.statusMessage, + headers: createHeadersFromIncomingHttpHeaders(message.headers) + }); +} +function createHeadersFromIncomingHttpHeaders(httpHeaders) { + const headers = new Headers(); + for (const headerName in httpHeaders) { + const headerValues = httpHeaders[headerName]; + if (typeof headerValues === "undefined") { + continue; + } + if (Array.isArray(headerValues)) { + headerValues.forEach((headerValue) => { + headers.append(headerName, headerValue); + }); + continue; + } + headers.set(headerName, headerValues); + } + return headers; +} + +// src/interceptors/ClientRequest/utils/createRequest.ts +function createRequest(clientRequest) { + const headers = new Headers(); + const outgoingHeaders = clientRequest.getHeaders(); + for (const headerName in outgoingHeaders) { + const headerValue = outgoingHeaders[headerName]; + if (typeof headerValue === "undefined") { + continue; + } + const valuesList = Array.prototype.concat([], headerValue); + for (const value of valuesList) { + headers.append(headerName, value.toString()); + } + } + if (clientRequest.url.username || clientRequest.url.password) { + const username = decodeURIComponent(clientRequest.url.username || ""); + const password = decodeURIComponent(clientRequest.url.password || ""); + const auth = `${username}:${password}`; + headers.set("Authorization", `Basic ${btoa(auth)}`); + clientRequest.url.username = ""; + clientRequest.url.password = ""; + } + const method = clientRequest.method || "GET"; + return new Request(clientRequest.url, { + method, + headers, + credentials: "same-origin", + body: method === "HEAD" || method === "GET" ? null : clientRequest.requestBuffer + }); +} + +// src/utils/getValueBySymbol.ts +function getValueBySymbol(symbolName, source) { + const ownSymbols = Object.getOwnPropertySymbols(source); + const symbol = ownSymbols.find((symbol2) => { + return symbol2.description === symbolName; + }); + if (symbol) { + return Reflect.get(source, symbol); + } + return; +} + +// src/utils/isObject.ts +function isObject(value, loose = false) { + return loose ? Object.prototype.toString.call(value).startsWith("[object ") : Object.prototype.toString.call(value) === "[object Object]"; +} + +// src/utils/getRawFetchHeaders.ts +function getRawFetchHeaders(headers) { + const headersList = getValueBySymbol("headers list", headers); + if (!headersList) { + return; + } + const headersMap = getValueBySymbol("headers map", headersList); + if (!headersMap || !isHeadersMapWithRawHeaderNames(headersMap)) { + return; + } + const rawHeaders = /* @__PURE__ */ new Map(); + headersMap.forEach(({ name, value }) => { + rawHeaders.set(name, value); + }); + return rawHeaders; +} +function isHeadersMapWithRawHeaderNames(headersMap) { + return Array.from( + headersMap.values() + ).every((value) => { + return isObject(value) && "name" in value; + }); +} + +// src/utils/isNodeLikeError.ts +function isNodeLikeError(error) { + if (error == null) { + return false; + } + if (!(error instanceof Error)) { + return false; + } + return "code" in error && "errno" in error; +} + +// src/interceptors/ClientRequest/NodeClientRequest.ts +var _NodeClientRequest = class extends _http.ClientRequest { + constructor([url, requestOptions, callback], options) { + super(requestOptions, callback); + this.chunks = []; + this.logger = options.logger.extend( + `request ${requestOptions.method} ${url.href}` + ); + this.logger.info("constructing ClientRequest using options:", { + url, + requestOptions, + callback + }); + this.state = 0 /* Idle */; + this.url = url; + this.emitter = options.emitter; + this.requestBuffer = null; + this.response = new (0, _http.IncomingMessage)(this.socket); + } + writeRequestBodyChunk(chunk, encoding) { + if (chunk == null) { + return; + } + if (this.requestBuffer == null) { + this.requestBuffer = Buffer.from([]); + } + const resolvedChunk = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding); + this.requestBuffer = Buffer.concat([this.requestBuffer, resolvedChunk]); + } + write(...args) { + var _a; + const [chunk, encoding, callback] = normalizeClientRequestWriteArgs(args); + this.logger.info("write:", { chunk, encoding, callback }); + this.chunks.push({ chunk, encoding }); + this.writeRequestBodyChunk(chunk, encoding); + this.logger.info( + "chunk successfully stored!", + (_a = this.requestBuffer) == null ? void 0 : _a.byteLength + ); + if (!chunk || chunk.length === 0) { + this.logger.info("written chunk is empty, skipping callback..."); + } else { + callback == null ? void 0 : callback(); + } + return true; + } + end(...args) { + this.logger.info("end", args); + const requestId = _chunkE4AC7YACjs.createRequestId.call(void 0, ); + const [chunk, encoding, callback] = normalizeClientRequestEndArgs(...args); + this.logger.info("normalized arguments:", { chunk, encoding, callback }); + this.writeRequestBodyChunk(chunk, encoding || void 0); + this.state = 2 /* Sent */; + const capturedRequest = createRequest(this); + const { interactiveRequest, requestController } = _chunkMQJ3JOOKjs.toInteractiveRequest.call(void 0, capturedRequest); + Object.defineProperty(capturedRequest, "respondWith", { + value: requestController.respondWith.bind(requestController) + }); + if (this.hasHeader(_chunkE4AC7YACjs.INTERNAL_REQUEST_ID_HEADER_NAME)) { + this.removeHeader(_chunkE4AC7YACjs.INTERNAL_REQUEST_ID_HEADER_NAME); + return this.passthrough(chunk, encoding, callback); + } + this.emitter.once("request", ({ requestId: pendingRequestId }) => { + if (pendingRequestId !== requestId) { + return; + } + if (requestController.responsePromise.state === "pending") { + this.logger.info( + "request has not been handled in listeners, executing fail-safe listener..." + ); + requestController.responsePromise.resolve(void 0); + } + }); + _until.until.call(void 0, async () => { + this.logger.info( + 'emitting the "request" event for %d listener(s)...', + this.emitter.listenerCount("request") + ); + this.state = 3 /* MockLookupStart */; + await _chunkMQJ3JOOKjs.emitAsync.call(void 0, this.emitter, "request", { + request: interactiveRequest, + requestId + }); + this.logger.info('all "request" listeners done!'); + const mockedResponse = await requestController.responsePromise; + this.logger.info("event.respondWith called with:", mockedResponse); + return mockedResponse; + }).then((resolverResult) => { + this.logger.info("the listeners promise awaited!"); + this.state = 4 /* MockLookupEnd */; + if (!this.headersSent) { + for (const [headerName, headerValue] of capturedRequest.headers) { + this.setHeader(headerName, headerValue); + } + } + if (resolverResult.error) { + this.logger.info( + "unhandled resolver exception, coercing to an error response...", + resolverResult.error + ); + if (resolverResult.error instanceof Response) { + if (_chunkE4AC7YACjs.isResponseError.call(void 0, resolverResult.error)) { + this.logger.info( + "received network error response, erroring request..." + ); + this.errorWith(new TypeError("Network error")); + } else { + this.respondWith(resolverResult.error); + } + return; + } + if (isNodeLikeError(resolverResult.error)) { + this.errorWith(resolverResult.error); + return this; + } + _until.until.call(void 0, async () => { + if (this.emitter.listenerCount("unhandledException") > 0) { + await _chunkMQJ3JOOKjs.emitAsync.call(void 0, this.emitter, "unhandledException", { + error: resolverResult.error, + request: capturedRequest, + requestId, + controller: { + respondWith: this.respondWith.bind(this), + errorWith: this.errorWith.bind(this) + } + }); + if (this.writableEnded || this.destroyed) { + return; + } + } + this.respondWith(_chunkE4AC7YACjs.createServerErrorResponse.call(void 0, resolverResult.error)); + }); + return this; + } + const mockedResponse = resolverResult.data; + if (mockedResponse) { + this.logger.info( + "received mocked response:", + mockedResponse.status, + mockedResponse.statusText + ); + this.destroyed = false; + if (_chunkE4AC7YACjs.isResponseError.call(void 0, mockedResponse)) { + this.logger.info( + "received network error response, erroring request..." + ); + this.errorWith(new TypeError("Network error")); + return this; + } + const responseClone = mockedResponse.clone(); + this.respondWith(mockedResponse); + this.logger.info( + mockedResponse.status, + mockedResponse.statusText, + "(MOCKED)" + ); + callback == null ? void 0 : callback(); + this.logger.info('emitting the custom "response" event...'); + this.emitter.emit("response", { + response: responseClone, + isMockedResponse: true, + request: capturedRequest, + requestId + }); + this.logger.info("request (mock) is completed"); + return this; + } + this.logger.info("no mocked response received!"); + this.once("response-internal", (message) => { + this.logger.info(message.statusCode, message.statusMessage); + this.logger.info("original response headers:", message.headers); + this.logger.info('emitting the custom "response" event...'); + this.emitter.emit("response", { + response: createResponse(message), + isMockedResponse: false, + request: capturedRequest, + requestId + }); + }); + return this.passthrough(chunk, encoding, callback); + }); + return this; + } + emit(event, ...data) { + this.logger.info("emit: %s", event); + if (event === "response") { + this.logger.info('found "response" event, cloning the response...'); + try { + const response = data[0]; + const firstClone = cloneIncomingMessage(response); + const secondClone = cloneIncomingMessage(response); + this.emit("response-internal", secondClone); + this.logger.info( + 'response successfully cloned, emitting "response" event...' + ); + return super.emit(event, firstClone, ...data.slice(1)); + } catch (error) { + this.logger.info("error when cloning response:", error); + return super.emit(event, ...data); + } + } + if (event === "error") { + const error = data[0]; + const errorCode = error.code || ""; + this.logger.info("error:\n", error); + if (_NodeClientRequest.suppressErrorCodes.includes(errorCode)) { + if (this.state < 4 /* MockLookupEnd */) { + if (!this.capturedError) { + this.capturedError = error; + this.logger.info("captured the first error:", this.capturedError); + } + return false; + } + if (this.state === 5 /* ResponseReceived */ && this.responseType === "mock") { + return false; + } + } + } + return super.emit(event, ...data); + } + /** + * Performs the intercepted request as-is. + * Replays the captured request body chunks, + * still emits the internal events, and wraps + * up the request with `super.end()`. + */ + passthrough(chunk, encoding, callback) { + this.state = 5 /* ResponseReceived */; + this.responseType = "passthrough"; + if (this.capturedError) { + this.emit("error", this.capturedError); + return this; + } + this.logger.info("writing request chunks...", this.chunks); + for (const { chunk: chunk2, encoding: encoding2 } of this.chunks) { + if (encoding2) { + super.write(chunk2, encoding2); + } else { + super.write(chunk2); + } + } + this.once("error", (error) => { + this.logger.info("original request error:", error); + }); + this.once("abort", () => { + this.logger.info("original request aborted!"); + }); + this.once("response-internal", (message) => { + this.logger.info(message.statusCode, message.statusMessage); + this.logger.info("original response headers:", message.headers); + }); + this.logger.info("performing original request..."); + return super.end(...[chunk, encoding, callback].filter(Boolean)); + } + /** + * Responds to this request instance using a mocked response. + */ + respondWith(mockedResponse) { + this.logger.info("responding with a mocked response...", mockedResponse); + this.state = 5 /* ResponseReceived */; + this.responseType = "mock"; + Object.defineProperties(this, { + writableFinished: { value: true }, + writableEnded: { value: true } + }); + this.emit("finish"); + const { status, statusText, headers, body } = mockedResponse; + this.response.statusCode = status; + this.response.statusMessage = statusText || _http.STATUS_CODES[status]; + const rawHeaders = getRawFetchHeaders(headers) || headers; + if (rawHeaders) { + this.response.headers = {}; + rawHeaders.forEach((headerValue, headerName) => { + this.response.rawHeaders.push(headerName, headerValue); + const insensitiveHeaderName = headerName.toLowerCase(); + const prevHeaders = this.response.headers[insensitiveHeaderName]; + this.response.headers[insensitiveHeaderName] = prevHeaders ? Array.prototype.concat([], prevHeaders, headerValue) : headerValue; + }); + } + this.logger.info("mocked response headers ready:", headers); + this.res = this.response; + this.emit("response", this.response); + const isResponseStreamFinished = new (0, _deferredpromise.DeferredPromise)(); + const finishResponseStream = () => { + this.logger.info("finished response stream!"); + this.response.push(null); + this.response.complete = true; + isResponseStreamFinished.resolve(); + }; + if (body) { + const bodyReader = body.getReader(); + const readNextChunk = async () => { + const { done, value } = await bodyReader.read(); + if (done) { + finishResponseStream(); + return; + } + this.response.emit("data", value); + return readNextChunk(); + }; + readNextChunk(); + } else { + finishResponseStream(); + } + isResponseStreamFinished.then(() => { + this.logger.info("finalizing response..."); + this.response.emit("end"); + this.terminate(); + this.logger.info("request complete!"); + }); + } + errorWith(error) { + this.destroyed = true; + this.emit("error", error); + this.terminate(); + } + /** + * Terminates a pending request. + */ + terminate() { + var _a; + (_a = this.agent) == null ? void 0 : _a.destroy(); + } +}; +var NodeClientRequest = _NodeClientRequest; +/** + * The list of internal Node.js errors to suppress while + * using the "mock" response source. + */ +NodeClientRequest.suppressErrorCodes = [ + "ENOTFOUND", + "ECONNREFUSED", + "ECONNRESET", + "EAI_AGAIN", + "ENETUNREACH", + "EHOSTUNREACH" +]; + +// src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.ts + + + + + + + + +var _url = require('url'); + + +// src/utils/getRequestOptionsByUrl.ts +function getRequestOptionsByUrl(url) { + const options = { + method: "GET", + protocol: url.protocol, + hostname: typeof url.hostname === "string" && url.hostname.startsWith("[") ? url.hostname.slice(1, -1) : url.hostname, + host: url.host, + path: `${url.pathname}${url.search || ""}` + }; + if (!!url.port) { + options.port = Number(url.port); + } + if (url.username || url.password) { + options.auth = `${url.username}:${url.password}`; + } + return options; +} + +// src/utils/getUrlByRequestOptions.ts + + +var logger3 = new (0, _logger.Logger)("utils getUrlByRequestOptions"); +var DEFAULT_PATH = "/"; +var DEFAULT_PROTOCOL = "http:"; +var DEFAULT_HOSTNAME = "localhost"; +var SSL_PORT = 443; +function getAgent(options) { + return options.agent instanceof _http.Agent ? options.agent : void 0; +} +function getProtocolByRequestOptions(options) { + var _a; + if (options.protocol) { + return options.protocol; + } + const agent = getAgent(options); + const agentProtocol = agent == null ? void 0 : agent.protocol; + if (agentProtocol) { + return agentProtocol; + } + const port = getPortByRequestOptions(options); + const isSecureRequest = options.cert || port === SSL_PORT; + return isSecureRequest ? "https:" : ((_a = options.uri) == null ? void 0 : _a.protocol) || DEFAULT_PROTOCOL; +} +function getPortByRequestOptions(options) { + if (options.port) { + return Number(options.port); + } + const agent = getAgent(options); + if (agent == null ? void 0 : agent.options.port) { + return Number(agent.options.port); + } + if (agent == null ? void 0 : agent.defaultPort) { + return Number(agent.defaultPort); + } + return void 0; +} +function getAuthByRequestOptions(options) { + if (options.auth) { + const [username, password] = options.auth.split(":"); + return { username, password }; + } +} +function isRawIPv6Address(host) { + return host.includes(":") && !host.startsWith("[") && !host.endsWith("]"); +} +function getHostname(options) { + let host = options.hostname || options.host; + if (host) { + if (isRawIPv6Address(host)) { + host = `[${host}]`; + } + return new URL(`http://${host}`).hostname; + } + return DEFAULT_HOSTNAME; +} +function getUrlByRequestOptions(options) { + logger3.info("request options", options); + if (options.uri) { + logger3.info( + 'constructing url from explicitly provided "options.uri": %s', + options.uri + ); + return new URL(options.uri.href); + } + logger3.info("figuring out url from request options..."); + const protocol = getProtocolByRequestOptions(options); + logger3.info("protocol", protocol); + const port = getPortByRequestOptions(options); + logger3.info("port", port); + const hostname = getHostname(options); + logger3.info("hostname", hostname); + const path = options.path || DEFAULT_PATH; + logger3.info("path", path); + const credentials = getAuthByRequestOptions(options); + logger3.info("credentials", credentials); + const authString = credentials ? `${credentials.username}:${credentials.password}@` : ""; + logger3.info("auth string:", authString); + const portString = typeof port !== "undefined" ? `:${port}` : ""; + const url = new URL(`${protocol}//${hostname}${portString}${path}`); + url.username = (credentials == null ? void 0 : credentials.username) || ""; + url.password = (credentials == null ? void 0 : credentials.password) || ""; + logger3.info("created url:", url); + return url; +} + +// src/utils/cloneObject.ts + +var logger4 = new (0, _logger.Logger)("cloneObject"); +function isPlainObject(obj) { + var _a; + logger4.info("is plain object?", obj); + if (obj == null || !((_a = obj.constructor) == null ? void 0 : _a.name)) { + logger4.info("given object is undefined, not a plain object..."); + return false; + } + logger4.info("checking the object constructor:", obj.constructor.name); + return obj.constructor.name === "Object"; +} +function cloneObject(obj) { + logger4.info("cloning object:", obj); + const enumerableProperties = Object.entries(obj).reduce( + (acc, [key, value]) => { + logger4.info("analyzing key-value pair:", key, value); + acc[key] = isPlainObject(value) ? cloneObject(value) : value; + return acc; + }, + {} + ); + return isPlainObject(obj) ? enumerableProperties : Object.assign(Object.getPrototypeOf(obj), enumerableProperties); +} + +// src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.ts +var logger5 = new (0, _logger.Logger)("http normalizeClientRequestArgs"); +function resolveRequestOptions(args, url) { + if (typeof args[1] === "undefined" || typeof args[1] === "function") { + logger5.info("request options not provided, deriving from the url", url); + return getRequestOptionsByUrl(url); + } + if (args[1]) { + logger5.info("has custom RequestOptions!", args[1]); + const requestOptionsFromUrl = getRequestOptionsByUrl(url); + logger5.info("derived RequestOptions from the URL:", requestOptionsFromUrl); + logger5.info("cloning RequestOptions..."); + const clonedRequestOptions = cloneObject(args[1]); + logger5.info("successfully cloned RequestOptions!", clonedRequestOptions); + return { + ...requestOptionsFromUrl, + ...clonedRequestOptions + }; + } + logger5.info("using an empty object as request options"); + return {}; +} +function overrideUrlByRequestOptions(url, options) { + url.host = options.host || url.host; + url.hostname = options.hostname || url.hostname; + url.port = options.port ? options.port.toString() : url.port; + if (options.path) { + const parsedOptionsPath = _url.parse.call(void 0, options.path, false); + url.pathname = parsedOptionsPath.pathname || ""; + url.search = parsedOptionsPath.search || ""; + } + return url; +} +function resolveCallback(args) { + return typeof args[1] === "function" ? args[1] : args[2]; +} +function normalizeClientRequestArgs(defaultProtocol, ...args) { + let url; + let options; + let callback; + logger5.info("arguments", args); + logger5.info("using default protocol:", defaultProtocol); + if (args.length === 0) { + const url2 = new URL("http://localhost"); + const options2 = resolveRequestOptions(args, url2); + return [url2, options2]; + } + if (typeof args[0] === "string") { + logger5.info("first argument is a location string:", args[0]); + url = new URL(args[0]); + logger5.info("created a url:", url); + const requestOptionsFromUrl = getRequestOptionsByUrl(url); + logger5.info("request options from url:", requestOptionsFromUrl); + options = resolveRequestOptions(args, url); + logger5.info("resolved request options:", options); + callback = resolveCallback(args); + } else if (args[0] instanceof URL) { + url = args[0]; + logger5.info("first argument is a URL:", url); + if (typeof args[1] !== "undefined" && isObject(args[1])) { + url = overrideUrlByRequestOptions(url, args[1]); + } + options = resolveRequestOptions(args, url); + logger5.info("derived request options:", options); + callback = resolveCallback(args); + } else if ("hash" in args[0] && !("method" in args[0])) { + const [legacyUrl] = args; + logger5.info("first argument is a legacy URL:", legacyUrl); + if (legacyUrl.hostname === null) { + logger5.info("given legacy URL is relative (no hostname)"); + return isObject(args[1]) ? normalizeClientRequestArgs( + defaultProtocol, + { path: legacyUrl.path, ...args[1] }, + args[2] + ) : normalizeClientRequestArgs( + defaultProtocol, + { path: legacyUrl.path }, + args[1] + ); + } + logger5.info("given legacy url is absolute"); + const resolvedUrl = new URL(legacyUrl.href); + return args[1] === void 0 ? normalizeClientRequestArgs(defaultProtocol, resolvedUrl) : typeof args[1] === "function" ? normalizeClientRequestArgs(defaultProtocol, resolvedUrl, args[1]) : normalizeClientRequestArgs( + defaultProtocol, + resolvedUrl, + args[1], + args[2] + ); + } else if (isObject(args[0])) { + options = args[0]; + logger5.info("first argument is RequestOptions:", options); + options.protocol = options.protocol || defaultProtocol; + logger5.info("normalized request options:", options); + url = getUrlByRequestOptions(options); + logger5.info("created a URL from RequestOptions:", url.href); + callback = resolveCallback(args); + } else { + throw new Error( + `Failed to construct ClientRequest with these parameters: ${args}` + ); + } + options.protocol = options.protocol || url.protocol; + options.method = options.method || "GET"; + if (typeof options.agent === "undefined") { + const agent = options.protocol === "https:" ? new (0, _https.Agent)({ + rejectUnauthorized: options.rejectUnauthorized + }) : new (0, _http.Agent)(); + options.agent = agent; + logger5.info("resolved fallback agent:", agent); + } + if (!options._defaultAgent) { + logger5.info( + 'has no default agent, setting the default agent for "%s"', + options.protocol + ); + options._defaultAgent = options.protocol === "https:" ? _https.globalAgent : _http.globalAgent; + } + logger5.info("successfully resolved url:", url.href); + logger5.info("successfully resolved options:", options); + logger5.info("successfully resolved callback:", callback); + return [url, options, callback]; +} + +// src/interceptors/ClientRequest/http.get.ts +function get(protocol, options) { + return function interceptorsHttpGet(...args) { + const clientRequestArgs = normalizeClientRequestArgs( + `${protocol}:`, + ...args + ); + const request2 = new NodeClientRequest(clientRequestArgs, options); + request2.end(); + return request2; + }; +} + +// src/interceptors/ClientRequest/http.request.ts + +var logger6 = new (0, _logger.Logger)("http request"); +function request(protocol, options) { + return function interceptorsHttpRequest(...args) { + logger6.info('request call (protocol "%s"):', protocol, args); + const clientRequestArgs = normalizeClientRequestArgs( + `${protocol}:`, + ...args + ); + return new NodeClientRequest(clientRequestArgs, options); + }; +} + +// src/interceptors/ClientRequest/index.ts +var _ClientRequestInterceptor = class extends _chunkE4AC7YACjs.Interceptor { + constructor() { + super(_ClientRequestInterceptor.interceptorSymbol); + this.modules = /* @__PURE__ */ new Map(); + this.modules.set("http", _http2.default); + this.modules.set("https", _https2.default); + } + setup() { + const logger7 = this.logger.extend("setup"); + for (const [protocol, requestModule] of this.modules) { + const { request: pureRequest, get: pureGet } = requestModule; + this.subscriptions.push(() => { + requestModule.request = pureRequest; + requestModule.get = pureGet; + logger7.info('native "%s" module restored!', protocol); + }); + const options = { + emitter: this.emitter, + logger: this.logger + }; + requestModule.request = // Force a line break. + request(protocol, options); + requestModule.get = // Force a line break. + get(protocol, options); + logger7.info('native "%s" module patched!', protocol); + } + } +}; +var ClientRequestInterceptor = _ClientRequestInterceptor; +ClientRequestInterceptor.interceptorSymbol = Symbol("http"); + + + +exports.ClientRequestInterceptor = ClientRequestInterceptor; +//# sourceMappingURL=chunk-SXGRMPXP.js.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/chunk-SXGRMPXP.js.map b/node_modules/@mswjs/interceptors/lib/node/chunk-SXGRMPXP.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a1fcfa820c93f417536529b6b5dd16f408f1a7c2 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/chunk-SXGRMPXP.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/interceptors/ClientRequest/index.ts","../../src/interceptors/ClientRequest/NodeClientRequest.ts","../../src/interceptors/ClientRequest/utils/normalizeClientRequestEndArgs.ts","../../src/interceptors/ClientRequest/utils/normalizeClientRequestWriteArgs.ts","../../src/interceptors/ClientRequest/utils/cloneIncomingMessage.ts","../../src/interceptors/ClientRequest/utils/createResponse.ts","../../src/interceptors/ClientRequest/utils/createRequest.ts","../../src/utils/getValueBySymbol.ts","../../src/utils/isObject.ts","../../src/utils/getRawFetchHeaders.ts","../../src/utils/isNodeLikeError.ts","../../src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.ts","../../src/utils/getRequestOptionsByUrl.ts","../../src/utils/getUrlByRequestOptions.ts","../../src/utils/cloneObject.ts","../../src/interceptors/ClientRequest/http.get.ts","../../src/interceptors/ClientRequest/http.request.ts"],"names":["IncomingMessage","Logger","logger","symbol","chunk","encoding","url","options","request"],"mappings":"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","sourcesContent":["import http from 'http'\nimport https from 'https'\nimport type { Emitter } from 'strict-event-emitter'\nimport { HttpRequestEventMap } from '../../glossary'\nimport { Interceptor } from '../../Interceptor'\nimport { get } from './http.get'\nimport { request } from './http.request'\nimport { NodeClientOptions, Protocol } from './NodeClientRequest'\n\nexport type ClientRequestEmitter = Emitter\n\nexport type ClientRequestModules = Map\n\n/**\n * Intercept requests made via the `ClientRequest` class.\n * Such requests include `http.get`, `https.request`, etc.\n */\nexport class ClientRequestInterceptor extends Interceptor {\n static interceptorSymbol = Symbol('http')\n private modules: ClientRequestModules\n\n constructor() {\n super(ClientRequestInterceptor.interceptorSymbol)\n\n this.modules = new Map()\n this.modules.set('http', http)\n this.modules.set('https', https)\n }\n\n protected setup(): void {\n const logger = this.logger.extend('setup')\n\n for (const [protocol, requestModule] of this.modules) {\n const { request: pureRequest, get: pureGet } = requestModule\n\n this.subscriptions.push(() => {\n requestModule.request = pureRequest\n requestModule.get = pureGet\n\n logger.info('native \"%s\" module restored!', protocol)\n })\n\n const options: NodeClientOptions = {\n emitter: this.emitter,\n logger: this.logger,\n }\n\n // @ts-ignore\n requestModule.request =\n // Force a line break.\n request(protocol, options)\n\n // @ts-ignore\n requestModule.get =\n // Force a line break.\n get(protocol, options)\n\n logger.info('native \"%s\" module patched!', protocol)\n }\n }\n}\n","import { ClientRequest, IncomingMessage, STATUS_CODES } from 'node:http'\nimport type { Logger } from '@open-draft/logger'\nimport { until } from '@open-draft/until'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport type { ClientRequestEmitter } from '.'\nimport {\n ClientRequestEndCallback,\n ClientRequestEndChunk,\n normalizeClientRequestEndArgs,\n} from './utils/normalizeClientRequestEndArgs'\nimport { NormalizedClientRequestArgs } from './utils/normalizeClientRequestArgs'\nimport {\n ClientRequestWriteArgs,\n normalizeClientRequestWriteArgs,\n} from './utils/normalizeClientRequestWriteArgs'\nimport { cloneIncomingMessage } from './utils/cloneIncomingMessage'\nimport { createResponse } from './utils/createResponse'\nimport { createRequest } from './utils/createRequest'\nimport { toInteractiveRequest } from '../../utils/toInteractiveRequest'\nimport { emitAsync } from '../../utils/emitAsync'\nimport { getRawFetchHeaders } from '../../utils/getRawFetchHeaders'\nimport { isNodeLikeError } from '../../utils/isNodeLikeError'\nimport { INTERNAL_REQUEST_ID_HEADER_NAME } from '../../Interceptor'\nimport { createRequestId } from '../../createRequestId'\nimport {\n createServerErrorResponse,\n isResponseError,\n} from '../../utils/responseUtils'\n\nexport type Protocol = 'http' | 'https'\n\nenum HttpClientInternalState {\n // Have the concept of an idle request because different\n // request methods can kick off request sending\n // (e.g. \".end()\" or \".flushHeaders()\").\n Idle,\n Sending,\n Sent,\n MockLookupStart,\n MockLookupEnd,\n ResponseReceived,\n}\n\nexport interface NodeClientOptions {\n emitter: ClientRequestEmitter\n logger: Logger\n}\n\nexport class NodeClientRequest extends ClientRequest {\n /**\n * The list of internal Node.js errors to suppress while\n * using the \"mock\" response source.\n */\n static suppressErrorCodes = [\n 'ENOTFOUND',\n 'ECONNREFUSED',\n 'ECONNRESET',\n 'EAI_AGAIN',\n 'ENETUNREACH',\n 'EHOSTUNREACH',\n ]\n\n /**\n * Internal state of the request.\n */\n private state: HttpClientInternalState\n private responseType?: 'mock' | 'passthrough'\n private response: IncomingMessage\n private emitter: ClientRequestEmitter\n private logger: Logger\n private chunks: Array<{\n chunk?: string | Buffer\n encoding?: BufferEncoding\n }> = []\n private capturedError?: NodeJS.ErrnoException\n\n public url: URL\n public requestBuffer: Buffer | null\n\n constructor(\n [url, requestOptions, callback]: NormalizedClientRequestArgs,\n options: NodeClientOptions\n ) {\n super(requestOptions, callback)\n\n this.logger = options.logger.extend(\n `request ${requestOptions.method} ${url.href}`\n )\n\n this.logger.info('constructing ClientRequest using options:', {\n url,\n requestOptions,\n callback,\n })\n\n this.state = HttpClientInternalState.Idle\n this.url = url\n this.emitter = options.emitter\n\n // Set request buffer to null by default so that GET/HEAD requests\n // without a body wouldn't suddenly get one.\n this.requestBuffer = null\n\n // Construct a mocked response message.\n this.response = new IncomingMessage(this.socket!)\n }\n\n private writeRequestBodyChunk(\n chunk: string | Buffer | null,\n encoding?: BufferEncoding\n ): void {\n if (chunk == null) {\n return\n }\n\n if (this.requestBuffer == null) {\n this.requestBuffer = Buffer.from([])\n }\n\n const resolvedChunk = Buffer.isBuffer(chunk)\n ? chunk\n : Buffer.from(chunk, encoding)\n\n this.requestBuffer = Buffer.concat([this.requestBuffer, resolvedChunk])\n }\n\n write(...args: ClientRequestWriteArgs): boolean {\n const [chunk, encoding, callback] = normalizeClientRequestWriteArgs(args)\n this.logger.info('write:', { chunk, encoding, callback })\n this.chunks.push({ chunk, encoding })\n\n // Write each request body chunk to the internal buffer.\n this.writeRequestBodyChunk(chunk, encoding)\n\n this.logger.info(\n 'chunk successfully stored!',\n this.requestBuffer?.byteLength\n )\n\n /**\n * Prevent invoking the callback if the written chunk is empty.\n * @see https://nodejs.org/api/http.html#requestwritechunk-encoding-callback\n */\n if (!chunk || chunk.length === 0) {\n this.logger.info('written chunk is empty, skipping callback...')\n } else {\n callback?.()\n }\n\n // Do not write the request body chunks to prevent\n // the Socket from sending data to a potentially existing\n // server when there is a mocked response defined.\n return true\n }\n\n end(...args: any): this {\n this.logger.info('end', args)\n\n const requestId = createRequestId()\n\n const [chunk, encoding, callback] = normalizeClientRequestEndArgs(...args)\n this.logger.info('normalized arguments:', { chunk, encoding, callback })\n\n // Write the last request body chunk passed to the \"end()\" method.\n this.writeRequestBodyChunk(chunk, encoding || undefined)\n\n /**\n * @note Mark the request as sent immediately when invoking \".end()\".\n * In Node.js, calling \".end()\" will flush the remaining request body\n * and mark the request as \"finished\" immediately (\"end\" is synchronous)\n * but we delegate that property update to:\n *\n * - respondWith(), in the case of mocked responses;\n * - super.end(), in the case of bypassed responses.\n *\n * For that reason, we have to keep an internal flag for a finished request.\n */\n this.state = HttpClientInternalState.Sent\n\n const capturedRequest = createRequest(this)\n const { interactiveRequest, requestController } =\n toInteractiveRequest(capturedRequest)\n\n /**\n * @todo Remove this modification of the original request\n * and expose the controller alongside it in the \"request\"\n * listener argument.\n */\n Object.defineProperty(capturedRequest, 'respondWith', {\n value: requestController.respondWith.bind(requestController),\n })\n\n // Prevent handling this request if it has already been handled\n // in another (parent) interceptor (like XMLHttpRequest -> ClientRequest).\n // That means some interceptor up the chain has concluded that\n // this request must be performed as-is.\n if (this.hasHeader(INTERNAL_REQUEST_ID_HEADER_NAME)) {\n this.removeHeader(INTERNAL_REQUEST_ID_HEADER_NAME)\n return this.passthrough(chunk, encoding, callback)\n }\n\n // Add the last \"request\" listener that always resolves\n // the pending response Promise. This way if the consumer\n // hasn't handled the request themselves, we will prevent\n // the response Promise from pending indefinitely.\n this.emitter.once('request', ({ requestId: pendingRequestId }) => {\n /**\n * @note Ignore request events emitted by irrelevant\n * requests. This happens when response patching.\n */\n if (pendingRequestId !== requestId) {\n return\n }\n\n if (requestController.responsePromise.state === 'pending') {\n this.logger.info(\n 'request has not been handled in listeners, executing fail-safe listener...'\n )\n\n requestController.responsePromise.resolve(undefined)\n }\n })\n\n // Execute the resolver Promise like a side-effect.\n // Node.js 16 forces \"ClientRequest.end\" to be synchronous and return \"this\".\n until(async () => {\n // Notify the interceptor about the request.\n // This will call any \"request\" listeners the users have.\n this.logger.info(\n 'emitting the \"request\" event for %d listener(s)...',\n this.emitter.listenerCount('request')\n )\n\n this.state = HttpClientInternalState.MockLookupStart\n\n await emitAsync(this.emitter, 'request', {\n request: interactiveRequest,\n requestId,\n })\n\n this.logger.info('all \"request\" listeners done!')\n\n const mockedResponse = await requestController.responsePromise\n this.logger.info('event.respondWith called with:', mockedResponse)\n\n return mockedResponse\n }).then((resolverResult) => {\n this.logger.info('the listeners promise awaited!')\n\n this.state = HttpClientInternalState.MockLookupEnd\n\n /**\n * @fixme We are in the \"end()\" method that still executes in parallel\n * to our mocking logic here. This can be solved by migrating to the\n * Proxy-based approach and deferring the passthrough \"end()\" properly.\n * @see https://github.com/mswjs/interceptors/issues/346\n */\n if (!this.headersSent) {\n // Forward any request headers that the \"request\" listener\n // may have modified before proceeding with this request.\n for (const [headerName, headerValue] of capturedRequest.headers) {\n this.setHeader(headerName, headerValue)\n }\n }\n\n if (resolverResult.error) {\n this.logger.info(\n 'unhandled resolver exception, coercing to an error response...',\n resolverResult.error\n )\n\n // Handle thrown Response instances.\n if (resolverResult.error instanceof Response) {\n // Treat thrown Response.error() as a request error.\n if (isResponseError(resolverResult.error)) {\n this.logger.info(\n 'received network error response, erroring request...'\n )\n\n this.errorWith(new TypeError('Network error'))\n } else {\n // Handle a thrown Response as a mocked response.\n this.respondWith(resolverResult.error)\n }\n\n return\n }\n\n // Allow throwing Node.js-like errors, like connection rejection errors.\n // Treat them as request errors.\n if (isNodeLikeError(resolverResult.error)) {\n this.errorWith(resolverResult.error)\n return this\n }\n\n until(async () => {\n if (this.emitter.listenerCount('unhandledException') > 0) {\n // Emit the \"unhandledException\" event to allow the client\n // to opt-out from the default handling of exceptions\n // as 500 error responses.\n await emitAsync(this.emitter, 'unhandledException', {\n error: resolverResult.error,\n request: capturedRequest,\n requestId,\n controller: {\n respondWith: this.respondWith.bind(this),\n errorWith: this.errorWith.bind(this),\n },\n })\n\n // If after the \"unhandledException\" listeners are done,\n // the request is either not writable (was mocked) or\n // destroyed (has errored), do nothing.\n if (this.writableEnded || this.destroyed) {\n return\n }\n }\n\n // Unhandled exceptions in the request listeners are\n // synonymous to unhandled exceptions on the server.\n // Those are represented as 500 error responses.\n this.respondWith(createServerErrorResponse(resolverResult.error))\n })\n\n return this\n }\n\n const mockedResponse = resolverResult.data\n\n if (mockedResponse) {\n this.logger.info(\n 'received mocked response:',\n mockedResponse.status,\n mockedResponse.statusText\n )\n\n /**\n * @note Ignore this request being destroyed by TLS in Node.js\n * due to connection errors.\n */\n this.destroyed = false\n\n // Handle mocked \"Response.error\" network error responses.\n if (isResponseError(mockedResponse)) {\n this.logger.info(\n 'received network error response, erroring request...'\n )\n\n /**\n * There is no standardized error format for network errors\n * in Node.js. Instead, emit a generic TypeError.\n */\n this.errorWith(new TypeError('Network error'))\n\n return this\n }\n\n const responseClone = mockedResponse.clone()\n\n this.respondWith(mockedResponse)\n this.logger.info(\n mockedResponse.status,\n mockedResponse.statusText,\n '(MOCKED)'\n )\n\n callback?.()\n\n this.logger.info('emitting the custom \"response\" event...')\n this.emitter.emit('response', {\n response: responseClone,\n isMockedResponse: true,\n request: capturedRequest,\n requestId,\n })\n\n this.logger.info('request (mock) is completed')\n\n return this\n }\n\n this.logger.info('no mocked response received!')\n\n this.once('response-internal', (message: IncomingMessage) => {\n this.logger.info(message.statusCode, message.statusMessage)\n this.logger.info('original response headers:', message.headers)\n\n this.logger.info('emitting the custom \"response\" event...')\n this.emitter.emit('response', {\n response: createResponse(message),\n isMockedResponse: false,\n request: capturedRequest,\n requestId,\n })\n })\n\n return this.passthrough(chunk, encoding, callback)\n })\n\n return this\n }\n\n emit(event: string, ...data: any[]) {\n this.logger.info('emit: %s', event)\n\n if (event === 'response') {\n this.logger.info('found \"response\" event, cloning the response...')\n\n try {\n /**\n * Clone the response object when emitting the \"response\" event.\n * This prevents the response body stream from locking\n * and allows reading it twice:\n * 1. Internal \"response\" event from the observer.\n * 2. Any external response body listeners.\n * @see https://github.com/mswjs/interceptors/issues/161\n */\n const response = data[0] as IncomingMessage\n const firstClone = cloneIncomingMessage(response)\n const secondClone = cloneIncomingMessage(response)\n\n this.emit('response-internal', secondClone)\n\n this.logger.info(\n 'response successfully cloned, emitting \"response\" event...'\n )\n return super.emit(event, firstClone, ...data.slice(1))\n } catch (error) {\n this.logger.info('error when cloning response:', error)\n return super.emit(event, ...data)\n }\n }\n\n if (event === 'error') {\n const error = data[0] as NodeJS.ErrnoException\n const errorCode = error.code || ''\n\n this.logger.info('error:\\n', error)\n\n // Suppress only specific Node.js connection errors.\n if (NodeClientRequest.suppressErrorCodes.includes(errorCode)) {\n // Until we aren't sure whether the request will be\n // passthrough, capture the first emitted connection\n // error in case we have to replay it for this request.\n if (this.state < HttpClientInternalState.MockLookupEnd) {\n if (!this.capturedError) {\n this.capturedError = error\n this.logger.info('captured the first error:', this.capturedError)\n }\n return false\n }\n\n // Ignore any connection errors once we know the request\n // has been resolved with a mocked response. Don't capture\n // them as they won't ever be replayed.\n if (\n this.state === HttpClientInternalState.ResponseReceived &&\n this.responseType === 'mock'\n ) {\n return false\n }\n }\n }\n\n return super.emit(event, ...data)\n }\n\n /**\n * Performs the intercepted request as-is.\n * Replays the captured request body chunks,\n * still emits the internal events, and wraps\n * up the request with `super.end()`.\n */\n private passthrough(\n chunk: ClientRequestEndChunk | null,\n encoding?: BufferEncoding | null,\n callback?: ClientRequestEndCallback | null\n ): this {\n this.state = HttpClientInternalState.ResponseReceived\n this.responseType = 'passthrough'\n\n // Propagate previously captured errors.\n // For example, a ECONNREFUSED error when connecting to a non-existing host.\n if (this.capturedError) {\n this.emit('error', this.capturedError)\n return this\n }\n\n this.logger.info('writing request chunks...', this.chunks)\n\n // Write the request body chunks in the order of \".write()\" calls.\n // Note that no request body has been written prior to this point\n // in order to prevent the Socket to communicate with a potentially\n // existing server.\n for (const { chunk, encoding } of this.chunks) {\n if (encoding) {\n super.write(chunk, encoding)\n } else {\n super.write(chunk)\n }\n }\n\n this.once('error', (error) => {\n this.logger.info('original request error:', error)\n })\n\n this.once('abort', () => {\n this.logger.info('original request aborted!')\n })\n\n this.once('response-internal', (message: IncomingMessage) => {\n this.logger.info(message.statusCode, message.statusMessage)\n this.logger.info('original response headers:', message.headers)\n })\n\n this.logger.info('performing original request...')\n\n // This call signature is way too dynamic.\n return super.end(...[chunk, encoding as any, callback].filter(Boolean))\n }\n\n /**\n * Responds to this request instance using a mocked response.\n */\n private respondWith(mockedResponse: Response): void {\n this.logger.info('responding with a mocked response...', mockedResponse)\n\n this.state = HttpClientInternalState.ResponseReceived\n this.responseType = 'mock'\n\n /**\n * Mark the request as finished right before streaming back the response.\n * This is not entirely conventional but this will allow the consumer to\n * modify the outoging request in the interceptor.\n *\n * The request is finished when its headers and bodies have been sent.\n * @see https://nodejs.org/api/http.html#event-finish\n */\n Object.defineProperties(this, {\n writableFinished: { value: true },\n writableEnded: { value: true },\n })\n this.emit('finish')\n\n const { status, statusText, headers, body } = mockedResponse\n this.response.statusCode = status\n this.response.statusMessage = statusText || STATUS_CODES[status]\n\n // Try extracting the raw headers from the headers instance.\n // If not possible, fallback to the headers instance as-is.\n const rawHeaders = getRawFetchHeaders(headers) || headers\n\n if (rawHeaders) {\n this.response.headers = {}\n\n rawHeaders.forEach((headerValue, headerName) => {\n /**\n * @note Make sure that multi-value headers are appended correctly.\n */\n this.response.rawHeaders.push(headerName, headerValue)\n\n const insensitiveHeaderName = headerName.toLowerCase()\n const prevHeaders = this.response.headers[insensitiveHeaderName]\n this.response.headers[insensitiveHeaderName] = prevHeaders\n ? Array.prototype.concat([], prevHeaders, headerValue)\n : headerValue\n })\n }\n this.logger.info('mocked response headers ready:', headers)\n\n /**\n * Set the internal \"res\" property to the mocked \"OutgoingMessage\"\n * to make the \"ClientRequest\" instance think there's data received\n * from the socket.\n * @see https://github.com/nodejs/node/blob/9c405f2591f5833d0247ed0fafdcd68c5b14ce7a/lib/_http_client.js#L501\n *\n * Set the response immediately so the interceptor could stream data\n * chunks to the request client as they come in.\n */\n // @ts-ignore\n this.res = this.response\n this.emit('response', this.response)\n\n const isResponseStreamFinished = new DeferredPromise()\n\n const finishResponseStream = () => {\n this.logger.info('finished response stream!')\n\n // Push \"null\" to indicate that the response body is complete\n // and shouldn't be written to anymore.\n this.response.push(null)\n this.response.complete = true\n\n isResponseStreamFinished.resolve()\n }\n\n if (body) {\n const bodyReader = body.getReader()\n const readNextChunk = async (): Promise => {\n const { done, value } = await bodyReader.read()\n\n if (done) {\n finishResponseStream()\n return\n }\n\n this.response.emit('data', value)\n\n return readNextChunk()\n }\n\n readNextChunk()\n } else {\n finishResponseStream()\n }\n\n isResponseStreamFinished.then(() => {\n this.logger.info('finalizing response...')\n this.response.emit('end')\n this.terminate()\n\n this.logger.info('request complete!')\n })\n }\n\n private errorWith(error: Error): void {\n this.destroyed = true\n this.emit('error', error)\n this.terminate()\n }\n\n /**\n * Terminates a pending request.\n */\n private terminate(): void {\n /**\n * @note Some request clients (e.g. Octokit) create a ClientRequest\n * in a way that it has no Agent set. Now, whether that's correct is\n * debatable, but we should still handle this case gracefully.\n * @see https://github.com/mswjs/interceptors/issues/304\n */\n // @ts-ignore\n this.agent?.destroy()\n }\n}\n","import { Logger } from '@open-draft/logger'\n\nconst logger = new Logger('utils getUrlByRequestOptions')\n\nexport type ClientRequestEndChunk = string | Buffer\nexport type ClientRequestEndCallback = () => void\n\ntype HttpRequestEndArgs =\n | []\n | [ClientRequestEndCallback]\n | [ClientRequestEndChunk, ClientRequestEndCallback?]\n | [ClientRequestEndChunk, BufferEncoding, ClientRequestEndCallback?]\n\ntype NormalizedHttpRequestEndParams = [\n ClientRequestEndChunk | null,\n BufferEncoding | null,\n ClientRequestEndCallback | null\n]\n\n/**\n * Normalizes a list of arguments given to the `ClientRequest.end()`\n * method to always include `chunk`, `encoding`, and `callback`.\n */\nexport function normalizeClientRequestEndArgs(\n ...args: HttpRequestEndArgs\n): NormalizedHttpRequestEndParams {\n logger.info('arguments', args)\n const normalizedArgs = new Array(3)\n .fill(null)\n .map((value, index) => args[index] || value)\n\n normalizedArgs.sort((a, b) => {\n // If first element is a function, move it rightwards.\n if (typeof a === 'function') {\n return 1\n }\n\n // If second element is a function, move the first leftwards.\n if (typeof b === 'function') {\n return -1\n }\n\n // If both elements are strings, preserve their original index.\n if (typeof a === 'string' && typeof b === 'string') {\n return normalizedArgs.indexOf(a) - normalizedArgs.indexOf(b)\n }\n\n return 0\n })\n\n logger.info('normalized args', normalizedArgs)\n return normalizedArgs as NormalizedHttpRequestEndParams\n}\n","import { Logger } from '@open-draft/logger'\n\nconst logger = new Logger('http normalizeWriteArgs')\n\nexport type ClientRequestWriteCallback = (error?: Error | null) => void\nexport type ClientRequestWriteArgs = [\n chunk: string | Buffer,\n encoding?: BufferEncoding | ClientRequestWriteCallback,\n callback?: ClientRequestWriteCallback\n]\n\nexport type NormalizedClientRequestWriteArgs = [\n chunk: string | Buffer,\n encoding?: BufferEncoding,\n callback?: ClientRequestWriteCallback\n]\n\nexport function normalizeClientRequestWriteArgs(\n args: ClientRequestWriteArgs\n): NormalizedClientRequestWriteArgs {\n logger.info('normalizing ClientRequest.write arguments...', args)\n\n const chunk = args[0]\n const encoding =\n typeof args[1] === 'string' ? (args[1] as BufferEncoding) : undefined\n const callback = typeof args[1] === 'function' ? args[1] : args[2]\n\n const writeArgs: NormalizedClientRequestWriteArgs = [\n chunk,\n encoding,\n callback,\n ]\n logger.info(\n 'successfully normalized ClientRequest.write arguments:',\n writeArgs\n )\n\n return writeArgs\n}\n","import { IncomingMessage } from 'http'\nimport { PassThrough } from 'stream'\n\nexport const IS_CLONE = Symbol('isClone')\n\nexport interface ClonedIncomingMessage extends IncomingMessage {\n [IS_CLONE]: boolean\n}\n\n/**\n * Clones a given `http.IncomingMessage` instance.\n */\nexport function cloneIncomingMessage(\n message: IncomingMessage\n): ClonedIncomingMessage {\n const clone = message.pipe(new PassThrough())\n\n // Inherit all direct \"IncomingMessage\" properties.\n inheritProperties(message, clone)\n\n // Deeply inherit the message prototypes (Readable, Stream, EventEmitter, etc.).\n const clonedPrototype = Object.create(IncomingMessage.prototype)\n getPrototypes(clone).forEach((prototype) => {\n inheritProperties(prototype, clonedPrototype)\n })\n Object.setPrototypeOf(clone, clonedPrototype)\n\n Object.defineProperty(clone, IS_CLONE, {\n enumerable: true,\n value: true,\n })\n\n return clone as unknown as ClonedIncomingMessage\n}\n\n/**\n * Returns a list of all prototypes the given object extends.\n */\nfunction getPrototypes(source: object): object[] {\n const prototypes: object[] = []\n let current = source\n\n while ((current = Object.getPrototypeOf(current))) {\n prototypes.push(current)\n }\n\n return prototypes\n}\n\n/**\n * Inherits a given target object properties and symbols\n * onto the given source object.\n * @param source Object which should acquire properties.\n * @param target Object to inherit the properties from.\n */\nfunction inheritProperties(source: object, target: object): void {\n const properties = [\n ...Object.getOwnPropertyNames(source),\n ...Object.getOwnPropertySymbols(source),\n ]\n\n for (const property of properties) {\n if (target.hasOwnProperty(property)) {\n continue\n }\n\n const descriptor = Object.getOwnPropertyDescriptor(source, property)\n if (!descriptor) {\n continue\n }\n\n Object.defineProperty(target, property, descriptor)\n }\n}\n","import type { IncomingHttpHeaders, IncomingMessage } from 'http'\nimport { isResponseWithoutBody } from '../../../utils/responseUtils'\n\n/**\n * Creates a Fetch API `Response` instance from the given\n * `http.IncomingMessage` instance.\n */\nexport function createResponse(message: IncomingMessage): Response {\n const responseBodyOrNull = isResponseWithoutBody(message.statusCode || 200)\n ? null\n : new ReadableStream({\n start(controller) {\n message.on('data', (chunk) => controller.enqueue(chunk))\n message.on('end', () => controller.close())\n\n /**\n * @todo Should also listen to the \"error\" on the message\n * and forward it to the controller. Otherwise the stream\n * will pend indefinitely.\n */\n },\n })\n\n return new Response(responseBodyOrNull, {\n status: message.statusCode,\n statusText: message.statusMessage,\n headers: createHeadersFromIncomingHttpHeaders(message.headers),\n })\n}\n\nfunction createHeadersFromIncomingHttpHeaders(\n httpHeaders: IncomingHttpHeaders\n): Headers {\n const headers = new Headers()\n\n for (const headerName in httpHeaders) {\n const headerValues = httpHeaders[headerName]\n\n if (typeof headerValues === 'undefined') {\n continue\n }\n\n if (Array.isArray(headerValues)) {\n headerValues.forEach((headerValue) => {\n headers.append(headerName, headerValue)\n })\n\n continue\n }\n\n headers.set(headerName, headerValues)\n }\n\n return headers\n}\n","import type { NodeClientRequest } from '../NodeClientRequest'\n\n/**\n * Creates a Fetch API `Request` instance from the given `http.ClientRequest`.\n */\nexport function createRequest(clientRequest: NodeClientRequest): Request {\n const headers = new Headers()\n\n const outgoingHeaders = clientRequest.getHeaders()\n for (const headerName in outgoingHeaders) {\n const headerValue = outgoingHeaders[headerName]\n\n if (typeof headerValue === 'undefined') {\n continue\n }\n\n const valuesList = Array.prototype.concat([], headerValue)\n for (const value of valuesList) {\n headers.append(headerName, value.toString())\n }\n }\n\n /**\n * Translate the authentication from the request URL to\n * the request \"Authorization\" header.\n * @see https://github.com/mswjs/interceptors/issues/438\n */\n if (clientRequest.url.username || clientRequest.url.password) {\n const username = decodeURIComponent(clientRequest.url.username || '')\n const password = decodeURIComponent(clientRequest.url.password || '')\n const auth = `${username}:${password}`\n headers.set('Authorization', `Basic ${btoa(auth)}`)\n\n // Remove the credentials from the URL since you cannot\n // construct a Request instance with such a URL.\n clientRequest.url.username = ''\n clientRequest.url.password = ''\n }\n\n const method = clientRequest.method || 'GET'\n\n return new Request(clientRequest.url, {\n method,\n headers,\n credentials: 'same-origin',\n body:\n method === 'HEAD' || method === 'GET'\n ? null\n : clientRequest.requestBuffer,\n })\n}\n","/**\n * Returns the value behind the symbol with the given name.\n */\nexport function getValueBySymbol(\n symbolName: string,\n source: object\n): T | undefined {\n const ownSymbols = Object.getOwnPropertySymbols(source)\n\n const symbol = ownSymbols.find((symbol) => {\n return symbol.description === symbolName\n })\n\n if (symbol) {\n return Reflect.get(source, symbol)\n }\n\n return\n}\n","/**\n * Determines if a given value is an instance of object.\n */\nexport function isObject(value: any, loose = false): value is T {\n return loose\n ? Object.prototype.toString.call(value).startsWith('[object ')\n : Object.prototype.toString.call(value) === '[object Object]'\n}\n","import { getValueBySymbol } from './getValueBySymbol'\nimport { isObject } from './isObject'\n\ntype RawHeadersMap = Map\ntype HeadersMapHeader = { name: string; value: string }\n\n/**\n * Returns raw headers from the given `Headers` instance.\n * @example\n * const headers = new Headers([\n * ['X-HeadeR-NamE', 'Value']\n * ])\n * getRawFetchHeaders(headers)\n * // { 'X-HeadeR-NamE': 'Value' }\n */\nexport function getRawFetchHeaders(\n headers: Headers\n): RawHeadersMap | undefined {\n const headersList = getValueBySymbol('headers list', headers)\n\n if (!headersList) {\n return\n }\n\n const headersMap = getValueBySymbol<\n Map | Map\n >('headers map', headersList)\n\n /**\n * @note Older versions of Node.js (e.g. 18.8.0) keep headers map\n * as Map without any means to tap\n * into raw header values. Detect that and return undefined.\n */\n if (!headersMap || !isHeadersMapWithRawHeaderNames(headersMap)) {\n return\n }\n\n // Raw headers is a map of { rawHeaderName: rawHeaderValue }\n const rawHeaders: RawHeadersMap = new Map()\n\n headersMap.forEach(({ name, value }) => {\n rawHeaders.set(name, value)\n })\n\n return rawHeaders\n}\n\nfunction isHeadersMapWithRawHeaderNames(\n headersMap: Map | Map\n): headersMap is Map {\n return Array.from(\n headersMap.values() as Iterable\n ).every((value) => {\n return isObject(value) && 'name' in value\n })\n}\n","export function isNodeLikeError(\n error: unknown\n): error is NodeJS.ErrnoException {\n if (error == null) {\n return false\n }\n\n if (!(error instanceof Error)) {\n return false\n }\n\n return 'code' in error && 'errno' in error\n}\n","import {\n Agent as HttpAgent,\n globalAgent as httpGlobalAgent,\n IncomingMessage,\n} from 'http'\nimport {\n RequestOptions,\n Agent as HttpsAgent,\n globalAgent as httpsGlobalAgent,\n} from 'https'\nimport { Url as LegacyURL, parse as parseUrl } from 'url'\nimport { Logger } from '@open-draft/logger'\nimport { getRequestOptionsByUrl } from '../../../utils/getRequestOptionsByUrl'\nimport {\n ResolvedRequestOptions,\n getUrlByRequestOptions,\n} from '../../../utils/getUrlByRequestOptions'\nimport { cloneObject } from '../../../utils/cloneObject'\nimport { isObject } from '../../../utils/isObject'\n\nconst logger = new Logger('http normalizeClientRequestArgs')\n\nexport type HttpRequestCallback = (response: IncomingMessage) => void\n\nexport type ClientRequestArgs =\n // Request without any arguments is also possible.\n | []\n | [string | URL | LegacyURL, HttpRequestCallback?]\n | [string | URL | LegacyURL, RequestOptions, HttpRequestCallback?]\n | [RequestOptions, HttpRequestCallback?]\n\nfunction resolveRequestOptions(\n args: ClientRequestArgs,\n url: URL\n): RequestOptions {\n // Calling `fetch` provides only URL to `ClientRequest`\n // without any `RequestOptions` or callback.\n if (typeof args[1] === 'undefined' || typeof args[1] === 'function') {\n logger.info('request options not provided, deriving from the url', url)\n return getRequestOptionsByUrl(url)\n }\n\n if (args[1]) {\n logger.info('has custom RequestOptions!', args[1])\n const requestOptionsFromUrl = getRequestOptionsByUrl(url)\n\n logger.info('derived RequestOptions from the URL:', requestOptionsFromUrl)\n\n /**\n * Clone the request options to lock their state\n * at the moment they are provided to `ClientRequest`.\n * @see https://github.com/mswjs/interceptors/issues/86\n */\n logger.info('cloning RequestOptions...')\n const clonedRequestOptions = cloneObject(args[1])\n logger.info('successfully cloned RequestOptions!', clonedRequestOptions)\n\n return {\n ...requestOptionsFromUrl,\n ...clonedRequestOptions,\n }\n }\n\n logger.info('using an empty object as request options')\n return {} as RequestOptions\n}\n\n/**\n * Overrides the given `URL` instance with the explicit properties provided\n * on the `RequestOptions` object. The options object takes precedence,\n * and will replace URL properties like \"host\", \"path\", and \"port\", if specified.\n */\nfunction overrideUrlByRequestOptions(url: URL, options: RequestOptions): URL {\n url.host = options.host || url.host\n url.hostname = options.hostname || url.hostname\n url.port = options.port ? options.port.toString() : url.port\n\n if (options.path) {\n const parsedOptionsPath = parseUrl(options.path, false)\n url.pathname = parsedOptionsPath.pathname || ''\n url.search = parsedOptionsPath.search || ''\n }\n\n return url\n}\n\nfunction resolveCallback(\n args: ClientRequestArgs\n): HttpRequestCallback | undefined {\n return typeof args[1] === 'function' ? args[1] : args[2]\n}\n\nexport type NormalizedClientRequestArgs = [\n url: URL,\n options: ResolvedRequestOptions,\n callback?: HttpRequestCallback\n]\n\n/**\n * Normalizes parameters given to a `http.request` call\n * so it always has a `URL` and `RequestOptions`.\n */\nexport function normalizeClientRequestArgs(\n defaultProtocol: string,\n ...args: ClientRequestArgs\n): NormalizedClientRequestArgs {\n let url: URL\n let options: ResolvedRequestOptions\n let callback: HttpRequestCallback | undefined\n\n logger.info('arguments', args)\n logger.info('using default protocol:', defaultProtocol)\n\n // Support \"http.request()\" calls without any arguments.\n // That call results in a \"GET http://localhost\" request.\n if (args.length === 0) {\n const url = new URL('http://localhost')\n const options = resolveRequestOptions(args, url)\n return [url, options]\n }\n\n // Convert a url string into a URL instance\n // and derive request options from it.\n if (typeof args[0] === 'string') {\n logger.info('first argument is a location string:', args[0])\n\n url = new URL(args[0])\n logger.info('created a url:', url)\n\n const requestOptionsFromUrl = getRequestOptionsByUrl(url)\n logger.info('request options from url:', requestOptionsFromUrl)\n\n options = resolveRequestOptions(args, url)\n logger.info('resolved request options:', options)\n\n callback = resolveCallback(args)\n }\n // Handle a given URL instance as-is\n // and derive request options from it.\n else if (args[0] instanceof URL) {\n url = args[0]\n logger.info('first argument is a URL:', url)\n\n // Check if the second provided argument is RequestOptions.\n // If it is, check if \"options.path\" was set and rewrite it\n // on the input URL.\n // Do this before resolving options from the URL below\n // to prevent query string from being duplicated in the path.\n if (typeof args[1] !== 'undefined' && isObject(args[1])) {\n url = overrideUrlByRequestOptions(url, args[1])\n }\n\n options = resolveRequestOptions(args, url)\n logger.info('derived request options:', options)\n\n callback = resolveCallback(args)\n }\n // Handle a legacy URL instance and re-normalize from either a RequestOptions object\n // or a WHATWG URL.\n else if ('hash' in args[0] && !('method' in args[0])) {\n const [legacyUrl] = args\n logger.info('first argument is a legacy URL:', legacyUrl)\n\n if (legacyUrl.hostname === null) {\n /**\n * We are dealing with a relative url, so use the path as an \"option\" and\n * merge in any existing options, giving priority to exising options -- i.e. a path in any\n * existing options will take precedence over the one contained in the url. This is consistent\n * with the behaviour in ClientRequest.\n * @see https://github.com/nodejs/node/blob/d84f1312915fe45fe0febe888db692c74894c382/lib/_http_client.js#L122\n */\n logger.info('given legacy URL is relative (no hostname)')\n\n return isObject(args[1])\n ? normalizeClientRequestArgs(\n defaultProtocol,\n { path: legacyUrl.path, ...args[1] },\n args[2]\n )\n : normalizeClientRequestArgs(\n defaultProtocol,\n { path: legacyUrl.path },\n args[1] as HttpRequestCallback\n )\n }\n\n logger.info('given legacy url is absolute')\n\n // We are dealing with an absolute URL, so convert to WHATWG and try again.\n const resolvedUrl = new URL(legacyUrl.href)\n\n return args[1] === undefined\n ? normalizeClientRequestArgs(defaultProtocol, resolvedUrl)\n : typeof args[1] === 'function'\n ? normalizeClientRequestArgs(defaultProtocol, resolvedUrl, args[1])\n : normalizeClientRequestArgs(\n defaultProtocol,\n resolvedUrl,\n args[1],\n args[2]\n )\n }\n // Handle a given \"RequestOptions\" object as-is\n // and derive the URL instance from it.\n else if (isObject(args[0])) {\n options = args[0] as any\n logger.info('first argument is RequestOptions:', options)\n\n // When handling a \"RequestOptions\" object without an explicit \"protocol\",\n // infer the protocol from the request issuing module (http/https).\n options.protocol = options.protocol || defaultProtocol\n logger.info('normalized request options:', options)\n\n url = getUrlByRequestOptions(options)\n logger.info('created a URL from RequestOptions:', url.href)\n\n callback = resolveCallback(args)\n } else {\n throw new Error(\n `Failed to construct ClientRequest with these parameters: ${args}`\n )\n }\n\n options.protocol = options.protocol || url.protocol\n options.method = options.method || 'GET'\n\n /**\n * Infer a fallback agent from the URL protocol.\n * The interception is done on the \"ClientRequest\" level (\"NodeClientRequest\")\n * and it may miss the correct agent. Always align the agent\n * with the URL protocol, if not provided.\n *\n * @note Respect the \"agent: false\" value.\n */\n if (typeof options.agent === 'undefined') {\n const agent =\n options.protocol === 'https:'\n ? new HttpsAgent({\n rejectUnauthorized: options.rejectUnauthorized,\n })\n : new HttpAgent()\n\n options.agent = agent\n logger.info('resolved fallback agent:', agent)\n }\n\n /**\n * Ensure that the default Agent is always set.\n * This prevents the protocol mismatch for requests with { agent: false },\n * where the global Agent is inferred.\n * @see https://github.com/mswjs/msw/issues/1150\n * @see https://github.com/nodejs/node/blob/418ff70b810f0e7112d48baaa72932a56cfa213b/lib/_http_client.js#L130\n * @see https://github.com/nodejs/node/blob/418ff70b810f0e7112d48baaa72932a56cfa213b/lib/_http_client.js#L157-L159\n */\n if (!options._defaultAgent) {\n logger.info(\n 'has no default agent, setting the default agent for \"%s\"',\n options.protocol\n )\n\n options._defaultAgent =\n options.protocol === 'https:' ? httpsGlobalAgent : httpGlobalAgent\n }\n\n logger.info('successfully resolved url:', url.href)\n logger.info('successfully resolved options:', options)\n logger.info('successfully resolved callback:', callback)\n\n return [url, options, callback]\n}\n","import { RequestOptions } from 'http'\n\n/**\n * Converts a URL instance into the RequestOptions object expected by\n * the `ClientRequest` class.\n * @see https://github.com/nodejs/node/blob/908292cf1f551c614a733d858528ffb13fb3a524/lib/internal/url.js#L1257\n */\nexport function getRequestOptionsByUrl(url: URL): RequestOptions {\n const options: RequestOptions = {\n method: 'GET',\n protocol: url.protocol,\n hostname:\n typeof url.hostname === 'string' && url.hostname.startsWith('[')\n ? url.hostname.slice(1, -1)\n : url.hostname,\n host: url.host,\n path: `${url.pathname}${url.search || ''}`,\n }\n\n if (!!url.port) {\n options.port = Number(url.port)\n }\n\n if (url.username || url.password) {\n options.auth = `${url.username}:${url.password}`\n }\n\n return options\n}\n","import { Agent } from 'http'\nimport { RequestOptions, Agent as HttpsAgent } from 'https'\nimport { Logger } from '@open-draft/logger'\n\nconst logger = new Logger('utils getUrlByRequestOptions')\n\n// Request instance constructed by the \"request\" library\n// has a \"self\" property that has a \"uri\" field. This is\n// reproducible by performing a \"XMLHttpRequest\" request in JSDOM.\nexport interface RequestSelf {\n uri?: URL\n}\n\nexport type ResolvedRequestOptions = RequestOptions & RequestSelf\n\nexport const DEFAULT_PATH = '/'\nconst DEFAULT_PROTOCOL = 'http:'\nconst DEFAULT_HOSTNAME = 'localhost'\nconst SSL_PORT = 443\n\nfunction getAgent(\n options: ResolvedRequestOptions\n): Agent | HttpsAgent | undefined {\n return options.agent instanceof Agent ? options.agent : undefined\n}\n\nfunction getProtocolByRequestOptions(options: ResolvedRequestOptions): string {\n if (options.protocol) {\n return options.protocol\n }\n\n const agent = getAgent(options)\n const agentProtocol = (agent as RequestOptions)?.protocol\n\n if (agentProtocol) {\n return agentProtocol\n }\n\n const port = getPortByRequestOptions(options)\n const isSecureRequest = options.cert || port === SSL_PORT\n\n return isSecureRequest ? 'https:' : options.uri?.protocol || DEFAULT_PROTOCOL\n}\n\nfunction getPortByRequestOptions(\n options: ResolvedRequestOptions\n): number | undefined {\n // Use the explicitly provided port.\n if (options.port) {\n return Number(options.port)\n }\n\n // Otherwise, try to resolve port from the agent.\n const agent = getAgent(options)\n\n if ((agent as HttpsAgent)?.options.port) {\n return Number((agent as HttpsAgent).options.port)\n }\n\n if ((agent as RequestOptions)?.defaultPort) {\n return Number((agent as RequestOptions).defaultPort)\n }\n\n // Lastly, return undefined indicating that the port\n // must inferred from the protocol. Do not infer it here.\n return undefined\n}\n\ninterface RequestAuth {\n username: string\n password: string\n}\n\nfunction getAuthByRequestOptions(\n options: ResolvedRequestOptions\n): RequestAuth | undefined {\n if (options.auth) {\n const [username, password] = options.auth.split(':')\n return { username, password }\n }\n}\n\n/**\n * Returns true if host looks like an IPv6 address without surrounding brackets\n * It assumes any host containing `:` is definitely not IPv4 and probably IPv6,\n * but note that this could include invalid IPv6 addresses as well.\n */\nfunction isRawIPv6Address(host: string): boolean {\n return host.includes(':') && !host.startsWith('[') && !host.endsWith(']')\n}\n\nfunction getHostname(options: ResolvedRequestOptions): string | undefined {\n let host = options.hostname || options.host\n\n if (host) {\n if (isRawIPv6Address(host)) {\n host = `[${host}]`\n }\n\n // Check the presence of the port, and if it's present,\n // remove it from the host, returning a hostname.\n return new URL(`http://${host}`).hostname\n }\n\n return DEFAULT_HOSTNAME\n}\n\n/**\n * Creates a `URL` instance from a given `RequestOptions` object.\n */\nexport function getUrlByRequestOptions(options: ResolvedRequestOptions): URL {\n logger.info('request options', options)\n\n if (options.uri) {\n logger.info(\n 'constructing url from explicitly provided \"options.uri\": %s',\n options.uri\n )\n return new URL(options.uri.href)\n }\n\n logger.info('figuring out url from request options...')\n\n const protocol = getProtocolByRequestOptions(options)\n logger.info('protocol', protocol)\n\n const port = getPortByRequestOptions(options)\n logger.info('port', port)\n\n const hostname = getHostname(options)\n logger.info('hostname', hostname)\n\n const path = options.path || DEFAULT_PATH\n logger.info('path', path)\n\n const credentials = getAuthByRequestOptions(options)\n logger.info('credentials', credentials)\n\n const authString = credentials\n ? `${credentials.username}:${credentials.password}@`\n : ''\n logger.info('auth string:', authString)\n\n const portString = typeof port !== 'undefined' ? `:${port}` : ''\n const url = new URL(`${protocol}//${hostname}${portString}${path}`)\n url.username = credentials?.username || ''\n url.password = credentials?.password || ''\n\n logger.info('created url:', url)\n\n return url\n}\n","import { Logger } from '@open-draft/logger'\n\nconst logger = new Logger('cloneObject')\n\nfunction isPlainObject(obj?: Record): boolean {\n logger.info('is plain object?', obj)\n\n if (obj == null || !obj.constructor?.name) {\n logger.info('given object is undefined, not a plain object...')\n return false\n }\n\n logger.info('checking the object constructor:', obj.constructor.name)\n return obj.constructor.name === 'Object'\n}\n\nexport function cloneObject>(\n obj: ObjectType\n): ObjectType {\n logger.info('cloning object:', obj)\n\n const enumerableProperties = Object.entries(obj).reduce>(\n (acc, [key, value]) => {\n logger.info('analyzing key-value pair:', key, value)\n\n // Recursively clone only plain objects, omitting class instances.\n acc[key] = isPlainObject(value) ? cloneObject(value) : value\n return acc\n },\n {}\n )\n\n return isPlainObject(obj)\n ? enumerableProperties\n : Object.assign(Object.getPrototypeOf(obj), enumerableProperties)\n}\n","import { ClientRequest } from 'node:http'\nimport {\n NodeClientOptions,\n NodeClientRequest,\n Protocol,\n} from './NodeClientRequest'\nimport {\n ClientRequestArgs,\n normalizeClientRequestArgs,\n} from './utils/normalizeClientRequestArgs'\n\nexport function get(protocol: Protocol, options: NodeClientOptions) {\n return function interceptorsHttpGet(\n ...args: ClientRequestArgs\n ): ClientRequest {\n const clientRequestArgs = normalizeClientRequestArgs(\n `${protocol}:`,\n ...args\n )\n const request = new NodeClientRequest(clientRequestArgs, options)\n\n /**\n * @note https://nodejs.org/api/http.html#httpgetoptions-callback\n * \"http.get\" sets the method to \"GET\" and calls \"req.end()\" automatically.\n */\n request.end()\n\n return request\n }\n}\n","import { ClientRequest } from 'http'\nimport { Logger } from '@open-draft/logger'\nimport {\n NodeClientOptions,\n NodeClientRequest,\n Protocol,\n} from './NodeClientRequest'\nimport {\n normalizeClientRequestArgs,\n ClientRequestArgs,\n} from './utils/normalizeClientRequestArgs'\n\nconst logger = new Logger('http request')\n\nexport function request(protocol: Protocol, options: NodeClientOptions) {\n return function interceptorsHttpRequest(\n ...args: ClientRequestArgs\n ): ClientRequest {\n logger.info('request call (protocol \"%s\"):', protocol, args)\n\n const clientRequestArgs = normalizeClientRequestArgs(\n `${protocol}:`,\n ...args\n )\n return new NodeClientRequest(clientRequestArgs, options)\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/index.d.ts b/node_modules/@mswjs/interceptors/lib/node/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6cb1ae96b30ce78648333b1c2e4a646b12f54806 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/index.d.ts @@ -0,0 +1,29 @@ +export { E as ExtractEventNames, H as HttpRequestEventMap, c as INTERNAL_REQUEST_ID_HEADER_NAME, I as IS_PATCHED_MODULE, f as Interceptor, a as InterceptorEventMap, e as InterceptorReadyState, b as InterceptorSubscription, R as RequestCredentials, d as deleteGlobalSymbol, g as getGlobalSymbol } from './Interceptor-88ee47c0.js'; +export { a as BatchInterceptor, B as BatchInterceptorOptions, E as ExtractEventMapType } from './BatchInterceptor-2badedde.js'; +import '@open-draft/deferred-promise'; +import '@open-draft/logger'; +import 'strict-event-emitter'; + +/** + * Generate a random ID string to represent a request. + * @example + * createRequestId() + * // "f774b6c9c600f" + */ +declare function createRequestId(): string; + +/** + * Removes query parameters and hashes from a given URL. + */ +declare function getCleanUrl(url: URL, isAbsolute?: boolean): string; + +declare function encodeBuffer(text: string): Uint8Array; +declare function decodeBuffer(buffer: ArrayBuffer, encoding?: string): string; + +/** + * Returns a boolean indicating whether the given response status + * code represents a response that cannot have a body. + */ +declare function isResponseWithoutBody(status: number): boolean; + +export { createRequestId, decodeBuffer, encodeBuffer, getCleanUrl, isResponseWithoutBody }; diff --git a/node_modules/@mswjs/interceptors/lib/node/index.js b/node_modules/@mswjs/interceptors/lib/node/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ef38b5f38022e5f14ae438abbe31c2fae2fd8299 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/index.js @@ -0,0 +1,39 @@ +"use strict";Object.defineProperty(exports, "__esModule", {value: true}); + +var _chunkLTEXDYJ6js = require('./chunk-LTEXDYJ6.js'); + + + +var _chunkLK6DILFKjs = require('./chunk-LK6DILFK.js'); + + +var _chunkEIBTX65Ojs = require('./chunk-EIBTX65O.js'); + + + + + + + + +var _chunkE4AC7YACjs = require('./chunk-E4AC7YAC.js'); + +// src/utils/getCleanUrl.ts +function getCleanUrl(url, isAbsolute = true) { + return [isAbsolute && url.origin, url.pathname].filter(Boolean).join(""); +} + + + + + + + + + + + + + +exports.BatchInterceptor = _chunkLTEXDYJ6js.BatchInterceptor; exports.INTERNAL_REQUEST_ID_HEADER_NAME = _chunkE4AC7YACjs.INTERNAL_REQUEST_ID_HEADER_NAME; exports.IS_PATCHED_MODULE = _chunkEIBTX65Ojs.IS_PATCHED_MODULE; exports.Interceptor = _chunkE4AC7YACjs.Interceptor; exports.InterceptorReadyState = _chunkE4AC7YACjs.InterceptorReadyState; exports.createRequestId = _chunkE4AC7YACjs.createRequestId; exports.decodeBuffer = _chunkLK6DILFKjs.decodeBuffer; exports.deleteGlobalSymbol = _chunkE4AC7YACjs.deleteGlobalSymbol; exports.encodeBuffer = _chunkLK6DILFKjs.encodeBuffer; exports.getCleanUrl = getCleanUrl; exports.getGlobalSymbol = _chunkE4AC7YACjs.getGlobalSymbol; exports.isResponseWithoutBody = _chunkE4AC7YACjs.isResponseWithoutBody; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/index.js.map b/node_modules/@mswjs/interceptors/lib/node/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ee90ca4d4e56dbd08ee1f9a7fdc299cdc6c1aa51 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/utils/getCleanUrl.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;AAGO,SAAS,YAAY,KAAU,aAAsB,MAAc;AACxE,SAAO,CAAC,cAAc,IAAI,QAAQ,IAAI,QAAQ,EAAE,OAAO,OAAO,EAAE,KAAK,EAAE;AACzE","sourcesContent":["/**\n * Removes query parameters and hashes from a given URL.\n */\nexport function getCleanUrl(url: URL, isAbsolute: boolean = true): string {\n return [isAbsolute && url.origin, url.pathname].filter(Boolean).join('')\n}\n"]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/index.mjs b/node_modules/@mswjs/interceptors/lib/node/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..57186210a3c89aab7027ee3cf9b5a0525b5546a7 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/index.mjs @@ -0,0 +1,39 @@ +import { + BatchInterceptor +} from "./chunk-6FRASLM3.mjs"; +import { + decodeBuffer, + encodeBuffer +} from "./chunk-6HYIRFX2.mjs"; +import { + IS_PATCHED_MODULE +} from "./chunk-OJ6O4LSC.mjs"; +import { + INTERNAL_REQUEST_ID_HEADER_NAME, + Interceptor, + InterceptorReadyState, + createRequestId, + deleteGlobalSymbol, + getGlobalSymbol, + isResponseWithoutBody +} from "./chunk-Q7POAM5N.mjs"; + +// src/utils/getCleanUrl.ts +function getCleanUrl(url, isAbsolute = true) { + return [isAbsolute && url.origin, url.pathname].filter(Boolean).join(""); +} +export { + BatchInterceptor, + INTERNAL_REQUEST_ID_HEADER_NAME, + IS_PATCHED_MODULE, + Interceptor, + InterceptorReadyState, + createRequestId, + decodeBuffer, + deleteGlobalSymbol, + encodeBuffer, + getCleanUrl, + getGlobalSymbol, + isResponseWithoutBody +}; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/index.mjs.map b/node_modules/@mswjs/interceptors/lib/node/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..0c277e56ed286846b2f219e9f452255167395135 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/utils/getCleanUrl.ts"],"sourcesContent":["/**\n * Removes query parameters and hashes from a given URL.\n */\nexport function getCleanUrl(url: URL, isAbsolute: boolean = true): string {\n return [isAbsolute && url.origin, url.pathname].filter(Boolean).join('')\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAGO,SAAS,YAAY,KAAU,aAAsB,MAAc;AACxE,SAAO,CAAC,cAAc,IAAI,QAAQ,IAAI,QAAQ,EAAE,OAAO,OAAO,EAAE,KAAK,EAAE;AACzE;","names":[]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/interceptors/ClientRequest/index.d.ts b/node_modules/@mswjs/interceptors/lib/node/interceptors/ClientRequest/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..20a91009eae96bf0bb74cfac7e986656cbdf0594 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/interceptors/ClientRequest/index.d.ts @@ -0,0 +1,23 @@ +import http from 'http'; +import https from 'https'; +import { Emitter } from 'strict-event-emitter'; +import { H as HttpRequestEventMap, f as Interceptor } from '../../Interceptor-88ee47c0.js'; +import '@open-draft/deferred-promise'; +import '@open-draft/logger'; + +type Protocol = 'http' | 'https'; + +type ClientRequestEmitter = Emitter; +type ClientRequestModules = Map; +/** + * Intercept requests made via the `ClientRequest` class. + * Such requests include `http.get`, `https.request`, etc. + */ +declare class ClientRequestInterceptor extends Interceptor { + static interceptorSymbol: symbol; + private modules; + constructor(); + protected setup(): void; +} + +export { ClientRequestEmitter, ClientRequestInterceptor, ClientRequestModules }; diff --git a/node_modules/@mswjs/interceptors/lib/node/interceptors/ClientRequest/index.js b/node_modules/@mswjs/interceptors/lib/node/interceptors/ClientRequest/index.js new file mode 100644 index 0000000000000000000000000000000000000000..62e165ee9b7615c01f205b66654775ad5439fa80 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/interceptors/ClientRequest/index.js @@ -0,0 +1,9 @@ +"use strict";Object.defineProperty(exports, "__esModule", {value: true}); + +var _chunkSXGRMPXPjs = require('../../chunk-SXGRMPXP.js'); +require('../../chunk-MQJ3JOOK.js'); +require('../../chunk-E4AC7YAC.js'); + + +exports.ClientRequestInterceptor = _chunkSXGRMPXPjs.ClientRequestInterceptor; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/interceptors/ClientRequest/index.js.map b/node_modules/@mswjs/interceptors/lib/node/interceptors/ClientRequest/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a464c6732ec9fa9ef5cf78917d42f90f2200eb58 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/interceptors/ClientRequest/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/interceptors/ClientRequest/index.mjs b/node_modules/@mswjs/interceptors/lib/node/interceptors/ClientRequest/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ed2f461f70ea81cbd1d979e3d261e41f528d90dc --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/interceptors/ClientRequest/index.mjs @@ -0,0 +1,9 @@ +import { + ClientRequestInterceptor +} from "../../chunk-CVV3L375.mjs"; +import "../../chunk-OUWBQF3Z.mjs"; +import "../../chunk-Q7POAM5N.mjs"; +export { + ClientRequestInterceptor +}; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/interceptors/ClientRequest/index.mjs.map b/node_modules/@mswjs/interceptors/lib/node/interceptors/ClientRequest/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..84c51b288c478ac0d18748007ccfb8cddc797f3a --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/interceptors/ClientRequest/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/interceptors/XMLHttpRequest/index.d.ts b/node_modules/@mswjs/interceptors/lib/node/interceptors/XMLHttpRequest/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b954fea0347389a6c96860f9b581ade9be1f5fef --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/interceptors/XMLHttpRequest/index.d.ts @@ -0,0 +1,18 @@ +import { Emitter } from 'strict-event-emitter'; +import { h as InteractiveRequest, H as HttpRequestEventMap, f as Interceptor } from '../../Interceptor-88ee47c0.js'; +import '@open-draft/deferred-promise'; +import '@open-draft/logger'; + +type XMLHttpRequestEventListener = (args: { + request: InteractiveRequest; + requestId: string; +}) => Promise | void; +type XMLHttpRequestEmitter = Emitter; +declare class XMLHttpRequestInterceptor extends Interceptor { + static interceptorSymbol: symbol; + constructor(); + protected checkEnvironment(): boolean; + protected setup(): void; +} + +export { XMLHttpRequestEmitter, XMLHttpRequestEventListener, XMLHttpRequestInterceptor }; diff --git a/node_modules/@mswjs/interceptors/lib/node/interceptors/XMLHttpRequest/index.js b/node_modules/@mswjs/interceptors/lib/node/interceptors/XMLHttpRequest/index.js new file mode 100644 index 0000000000000000000000000000000000000000..bf7b41f6313cbe8f06785ab6284c8475c5f2e27d --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/interceptors/XMLHttpRequest/index.js @@ -0,0 +1,11 @@ +"use strict";Object.defineProperty(exports, "__esModule", {value: true}); + +var _chunkAPT7KA3Bjs = require('../../chunk-APT7KA3B.js'); +require('../../chunk-LK6DILFK.js'); +require('../../chunk-EIBTX65O.js'); +require('../../chunk-MQJ3JOOK.js'); +require('../../chunk-E4AC7YAC.js'); + + +exports.XMLHttpRequestInterceptor = _chunkAPT7KA3Bjs.XMLHttpRequestInterceptor; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/interceptors/XMLHttpRequest/index.js.map b/node_modules/@mswjs/interceptors/lib/node/interceptors/XMLHttpRequest/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a464c6732ec9fa9ef5cf78917d42f90f2200eb58 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/interceptors/XMLHttpRequest/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/interceptors/XMLHttpRequest/index.mjs b/node_modules/@mswjs/interceptors/lib/node/interceptors/XMLHttpRequest/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f1dc60b9df48ee621eb91d60df81e409a11c7aaf --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/interceptors/XMLHttpRequest/index.mjs @@ -0,0 +1,11 @@ +import { + XMLHttpRequestInterceptor +} from "../../chunk-KSHIDGUL.mjs"; +import "../../chunk-6HYIRFX2.mjs"; +import "../../chunk-OJ6O4LSC.mjs"; +import "../../chunk-OUWBQF3Z.mjs"; +import "../../chunk-Q7POAM5N.mjs"; +export { + XMLHttpRequestInterceptor +}; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/interceptors/XMLHttpRequest/index.mjs.map b/node_modules/@mswjs/interceptors/lib/node/interceptors/XMLHttpRequest/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..84c51b288c478ac0d18748007ccfb8cddc797f3a --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/interceptors/XMLHttpRequest/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/interceptors/fetch/index.d.ts b/node_modules/@mswjs/interceptors/lib/node/interceptors/fetch/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4b772559c6909a05db6114992f88a29bebcb1be6 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/interceptors/fetch/index.d.ts @@ -0,0 +1,13 @@ +import { f as Interceptor, H as HttpRequestEventMap } from '../../Interceptor-88ee47c0.js'; +import '@open-draft/deferred-promise'; +import '@open-draft/logger'; +import 'strict-event-emitter'; + +declare class FetchInterceptor extends Interceptor { + static symbol: symbol; + constructor(); + protected checkEnvironment(): boolean; + protected setup(): Promise; +} + +export { FetchInterceptor }; diff --git a/node_modules/@mswjs/interceptors/lib/node/interceptors/fetch/index.js b/node_modules/@mswjs/interceptors/lib/node/interceptors/fetch/index.js new file mode 100644 index 0000000000000000000000000000000000000000..615a3642d828fcd80279a4953ff9007be59487f9 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/interceptors/fetch/index.js @@ -0,0 +1,212 @@ +"use strict";Object.defineProperty(exports, "__esModule", {value: true}); + +var _chunkEIBTX65Ojs = require('../../chunk-EIBTX65O.js'); + + + +var _chunkMQJ3JOOKjs = require('../../chunk-MQJ3JOOK.js'); + + + + + +var _chunkE4AC7YACjs = require('../../chunk-E4AC7YAC.js'); + +// src/interceptors/fetch/index.ts +var _outvariant = require('outvariant'); +var _deferredpromise = require('@open-draft/deferred-promise'); +var _until = require('@open-draft/until'); + +// src/utils/canParseUrl.ts +function canParseUrl(url) { + try { + new URL(url); + return true; + } catch (_error) { + return false; + } +} + +// src/interceptors/fetch/index.ts +var _FetchInterceptor = class extends _chunkE4AC7YACjs.Interceptor { + constructor() { + super(_FetchInterceptor.symbol); + } + checkEnvironment() { + return typeof globalThis !== "undefined" && typeof globalThis.fetch !== "undefined"; + } + async setup() { + const pureFetch = globalThis.fetch; + _outvariant.invariant.call(void 0, + !pureFetch[_chunkEIBTX65Ojs.IS_PATCHED_MODULE], + 'Failed to patch the "fetch" module: already patched.' + ); + globalThis.fetch = async (input, init) => { + var _a; + const requestId = _chunkE4AC7YACjs.createRequestId.call(void 0, ); + const resolvedInput = typeof input === "string" && typeof location !== "undefined" && !canParseUrl(input) ? new URL(input, location.origin) : input; + const request = new Request(resolvedInput, init); + this.logger.info("[%s] %s", request.method, request.url); + const { interactiveRequest, requestController } = _chunkMQJ3JOOKjs.toInteractiveRequest.call(void 0, request); + this.logger.info( + 'emitting the "request" event for %d listener(s)...', + this.emitter.listenerCount("request") + ); + this.emitter.once("request", ({ requestId: pendingRequestId }) => { + if (pendingRequestId !== requestId) { + return; + } + if (requestController.responsePromise.state === "pending") { + requestController.responsePromise.resolve(void 0); + } + }); + this.logger.info("awaiting for the mocked response..."); + const signal = interactiveRequest.signal; + const requestAborted = new (0, _deferredpromise.DeferredPromise)(); + if (signal) { + signal.addEventListener( + "abort", + () => { + requestAborted.reject(signal.reason); + }, + { once: true } + ); + } + const responsePromise = new (0, _deferredpromise.DeferredPromise)(); + const respondWith = (response) => { + this.logger.info("responding with a mock response:", response); + if (this.emitter.listenerCount("response") > 0) { + this.logger.info('emitting the "response" event...'); + const responseClone = response.clone(); + this.emitter.emit("response", { + response: responseClone, + isMockedResponse: true, + request: interactiveRequest, + requestId + }); + } + Object.defineProperty(response, "url", { + writable: false, + enumerable: true, + configurable: false, + value: request.url + }); + responsePromise.resolve(response); + }; + const errorWith = (reason) => { + responsePromise.reject(reason); + }; + const resolverResult = await _until.until.call(void 0, + async () => { + const listenersFinished = _chunkMQJ3JOOKjs.emitAsync.call(void 0, this.emitter, "request", { + request: interactiveRequest, + requestId + }); + await Promise.race([ + requestAborted, + // Put the listeners invocation Promise in the same race condition + // with the request abort Promise because otherwise awaiting the listeners + // would always yield some response (or undefined). + listenersFinished, + requestController.responsePromise + ]); + this.logger.info("all request listeners have been resolved!"); + const mockedResponse2 = await requestController.responsePromise; + this.logger.info("event.respondWith called with:", mockedResponse2); + return mockedResponse2; + } + ); + if (requestAborted.state === "rejected") { + this.logger.info( + "request has been aborted:", + requestAborted.rejectionReason + ); + responsePromise.reject(requestAborted.rejectionReason); + return responsePromise; + } + if (resolverResult.error) { + this.logger.info( + "request listerner threw an error:", + resolverResult.error + ); + if (resolverResult.error instanceof Response) { + if (_chunkE4AC7YACjs.isResponseError.call(void 0, resolverResult.error)) { + errorWith(createNetworkError(resolverResult.error)); + } else { + respondWith(resolverResult.error); + } + } + if (this.emitter.listenerCount("unhandledException") > 0) { + await _chunkMQJ3JOOKjs.emitAsync.call(void 0, this.emitter, "unhandledException", { + error: resolverResult.error, + request, + requestId, + controller: { + respondWith, + errorWith + } + }); + if (responsePromise.state !== "pending") { + return responsePromise; + } + } + respondWith(_chunkE4AC7YACjs.createServerErrorResponse.call(void 0, resolverResult.error)); + return responsePromise; + } + const mockedResponse = resolverResult.data; + if (mockedResponse && !((_a = request.signal) == null ? void 0 : _a.aborted)) { + this.logger.info("received mocked response:", mockedResponse); + if (_chunkE4AC7YACjs.isResponseError.call(void 0, mockedResponse)) { + this.logger.info( + "received a network error response, rejecting the request promise..." + ); + errorWith(createNetworkError(mockedResponse)); + } else { + respondWith(mockedResponse); + } + return responsePromise; + } + this.logger.info("no mocked response received!"); + return pureFetch(request).then((response) => { + this.logger.info("original fetch performed", response); + if (this.emitter.listenerCount("response") > 0) { + this.logger.info('emitting the "response" event...'); + const responseClone = response.clone(); + this.emitter.emit("response", { + response: responseClone, + isMockedResponse: false, + request: interactiveRequest, + requestId + }); + } + return response; + }); + }; + Object.defineProperty(globalThis.fetch, _chunkEIBTX65Ojs.IS_PATCHED_MODULE, { + enumerable: true, + configurable: true, + value: true + }); + this.subscriptions.push(() => { + Object.defineProperty(globalThis.fetch, _chunkEIBTX65Ojs.IS_PATCHED_MODULE, { + value: void 0 + }); + globalThis.fetch = pureFetch; + this.logger.info( + 'restored native "globalThis.fetch"!', + globalThis.fetch.name + ); + }); + } +}; +var FetchInterceptor = _FetchInterceptor; +FetchInterceptor.symbol = Symbol("fetch"); +function createNetworkError(cause) { + return Object.assign(new TypeError("Failed to fetch"), { + cause + }); +} + + +exports.FetchInterceptor = FetchInterceptor; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/interceptors/fetch/index.js.map b/node_modules/@mswjs/interceptors/lib/node/interceptors/fetch/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..bec82862952414b3ffcfa1ece43976ffd1f87377 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/interceptors/fetch/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/interceptors/fetch/index.ts","../../../../src/utils/canParseUrl.ts"],"names":["mockedResponse"],"mappings":"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","sourcesContent":["import { invariant } from 'outvariant'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { until } from '@open-draft/until'\nimport { HttpRequestEventMap, IS_PATCHED_MODULE } from '../../glossary'\nimport { Interceptor } from '../../Interceptor'\nimport { toInteractiveRequest } from '../../utils/toInteractiveRequest'\nimport { emitAsync } from '../../utils/emitAsync'\nimport { canParseUrl } from '../../utils/canParseUrl'\nimport { createRequestId } from '../../createRequestId'\nimport {\n createServerErrorResponse,\n isResponseError,\n} from '../../utils/responseUtils'\n\nexport class FetchInterceptor extends Interceptor {\n static symbol = Symbol('fetch')\n\n constructor() {\n super(FetchInterceptor.symbol)\n }\n\n protected checkEnvironment() {\n return (\n typeof globalThis !== 'undefined' &&\n typeof globalThis.fetch !== 'undefined'\n )\n }\n\n protected async setup() {\n const pureFetch = globalThis.fetch\n\n invariant(\n !(pureFetch as any)[IS_PATCHED_MODULE],\n 'Failed to patch the \"fetch\" module: already patched.'\n )\n\n globalThis.fetch = async (input, init) => {\n const requestId = createRequestId()\n\n /**\n * @note Resolve potentially relative request URL\n * against the present `location`. This is mainly\n * for native `fetch` in JSDOM.\n * @see https://github.com/mswjs/msw/issues/1625\n */\n const resolvedInput =\n typeof input === 'string' &&\n typeof location !== 'undefined' &&\n !canParseUrl(input)\n ? new URL(input, location.origin)\n : input\n\n const request = new Request(resolvedInput, init)\n\n this.logger.info('[%s] %s', request.method, request.url)\n\n const { interactiveRequest, requestController } =\n toInteractiveRequest(request)\n\n this.logger.info(\n 'emitting the \"request\" event for %d listener(s)...',\n this.emitter.listenerCount('request')\n )\n\n this.emitter.once('request', ({ requestId: pendingRequestId }) => {\n if (pendingRequestId !== requestId) {\n return\n }\n\n if (requestController.responsePromise.state === 'pending') {\n requestController.responsePromise.resolve(undefined)\n }\n })\n\n this.logger.info('awaiting for the mocked response...')\n\n const signal = interactiveRequest.signal\n const requestAborted = new DeferredPromise()\n\n // Signal isn't always defined in react-native.\n if (signal) {\n signal.addEventListener(\n 'abort',\n () => {\n requestAborted.reject(signal.reason)\n },\n { once: true }\n )\n }\n\n const responsePromise = new DeferredPromise()\n\n const respondWith = (response: Response): void => {\n this.logger.info('responding with a mock response:', response)\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n // Clone the mocked response for the \"response\" event listener.\n // This way, the listener can read the response and not lock its body\n // for the actual fetch consumer.\n const responseClone = response.clone()\n\n this.emitter.emit('response', {\n response: responseClone,\n isMockedResponse: true,\n request: interactiveRequest,\n requestId,\n })\n }\n\n // Set the \"response.url\" property to equal the intercepted request URL.\n Object.defineProperty(response, 'url', {\n writable: false,\n enumerable: true,\n configurable: false,\n value: request.url,\n })\n\n responsePromise.resolve(response)\n }\n\n const errorWith = (reason: unknown): void => {\n responsePromise.reject(reason)\n }\n\n const resolverResult = await until(\n async () => {\n const listenersFinished = emitAsync(this.emitter, 'request', {\n request: interactiveRequest,\n requestId,\n })\n\n await Promise.race([\n requestAborted,\n // Put the listeners invocation Promise in the same race condition\n // with the request abort Promise because otherwise awaiting the listeners\n // would always yield some response (or undefined).\n listenersFinished,\n requestController.responsePromise,\n ])\n\n this.logger.info('all request listeners have been resolved!')\n\n const mockedResponse = await requestController.responsePromise\n this.logger.info('event.respondWith called with:', mockedResponse)\n\n return mockedResponse\n }\n )\n\n if (requestAborted.state === 'rejected') {\n this.logger.info(\n 'request has been aborted:',\n requestAborted.rejectionReason\n )\n\n responsePromise.reject(requestAborted.rejectionReason)\n return responsePromise\n }\n\n if (resolverResult.error) {\n this.logger.info(\n 'request listerner threw an error:',\n resolverResult.error\n )\n\n // Treat thrown Responses as mocked responses.\n if (resolverResult.error instanceof Response) {\n // Treat thrown Response.error() as a request error.\n if (isResponseError(resolverResult.error)) {\n errorWith(createNetworkError(resolverResult.error))\n } else {\n // Treat the rest of thrown Responses as mocked responses.\n respondWith(resolverResult.error)\n }\n }\n\n // Emit the \"unhandledException\" interceptor event so the client\n // can opt-out from exceptions translating to 500 error responses.\n\n if (this.emitter.listenerCount('unhandledException') > 0) {\n await emitAsync(this.emitter, 'unhandledException', {\n error: resolverResult.error,\n request,\n requestId,\n controller: {\n respondWith,\n errorWith,\n },\n })\n\n if (responsePromise.state !== 'pending') {\n return responsePromise\n }\n }\n\n // Unhandled exceptions in the request listeners are\n // synonymous to unhandled exceptions on the server.\n // Those are represented as 500 error responses.\n respondWith(createServerErrorResponse(resolverResult.error))\n return responsePromise\n }\n\n const mockedResponse = resolverResult.data\n\n if (mockedResponse && !request.signal?.aborted) {\n this.logger.info('received mocked response:', mockedResponse)\n\n // Reject the request Promise on mocked \"Response.error\" responses.\n if (isResponseError(mockedResponse)) {\n this.logger.info(\n 'received a network error response, rejecting the request promise...'\n )\n\n /**\n * Set the cause of the request promise rejection to the\n * network error Response instance. This differs from Undici.\n * Undici will forward the \"response.error\" custom property\n * as the rejection reason but for \"Response.error()\" static method\n * \"response.error\" will equal to undefined, making \"cause\" an empty Error.\n * @see https://github.com/nodejs/undici/blob/83cb522ae0157a19d149d72c7d03d46e34510d0a/lib/fetch/response.js#L344\n */\n errorWith(createNetworkError(mockedResponse))\n } else {\n respondWith(mockedResponse)\n }\n\n return responsePromise\n }\n\n this.logger.info('no mocked response received!')\n\n return pureFetch(request).then((response) => {\n this.logger.info('original fetch performed', response)\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n const responseClone = response.clone()\n\n this.emitter.emit('response', {\n response: responseClone,\n isMockedResponse: false,\n request: interactiveRequest,\n requestId,\n })\n }\n\n return response\n })\n }\n\n Object.defineProperty(globalThis.fetch, IS_PATCHED_MODULE, {\n enumerable: true,\n configurable: true,\n value: true,\n })\n\n this.subscriptions.push(() => {\n Object.defineProperty(globalThis.fetch, IS_PATCHED_MODULE, {\n value: undefined,\n })\n\n globalThis.fetch = pureFetch\n\n this.logger.info(\n 'restored native \"globalThis.fetch\"!',\n globalThis.fetch.name\n )\n })\n }\n}\n\nfunction createNetworkError(cause: unknown) {\n return Object.assign(new TypeError('Failed to fetch'), {\n cause,\n })\n}\n","/**\n * Returns a boolean indicating whether the given URL string\n * can be parsed into a `URL` instance.\n * A substitute for `URL.canParse()` for Node.js 18.\n */\nexport function canParseUrl(url: string): boolean {\n try {\n new URL(url)\n return true\n } catch (_error) {\n return false\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/interceptors/fetch/index.mjs b/node_modules/@mswjs/interceptors/lib/node/interceptors/fetch/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4b1b5067433edcca6a108421e6ecaffe52e5500d --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/interceptors/fetch/index.mjs @@ -0,0 +1,212 @@ +import { + IS_PATCHED_MODULE +} from "../../chunk-OJ6O4LSC.mjs"; +import { + emitAsync, + toInteractiveRequest +} from "../../chunk-OUWBQF3Z.mjs"; +import { + Interceptor, + createRequestId, + createServerErrorResponse, + isResponseError +} from "../../chunk-Q7POAM5N.mjs"; + +// src/interceptors/fetch/index.ts +import { invariant } from "outvariant"; +import { DeferredPromise } from "@open-draft/deferred-promise"; +import { until } from "@open-draft/until"; + +// src/utils/canParseUrl.ts +function canParseUrl(url) { + try { + new URL(url); + return true; + } catch (_error) { + return false; + } +} + +// src/interceptors/fetch/index.ts +var _FetchInterceptor = class extends Interceptor { + constructor() { + super(_FetchInterceptor.symbol); + } + checkEnvironment() { + return typeof globalThis !== "undefined" && typeof globalThis.fetch !== "undefined"; + } + async setup() { + const pureFetch = globalThis.fetch; + invariant( + !pureFetch[IS_PATCHED_MODULE], + 'Failed to patch the "fetch" module: already patched.' + ); + globalThis.fetch = async (input, init) => { + var _a; + const requestId = createRequestId(); + const resolvedInput = typeof input === "string" && typeof location !== "undefined" && !canParseUrl(input) ? new URL(input, location.origin) : input; + const request = new Request(resolvedInput, init); + this.logger.info("[%s] %s", request.method, request.url); + const { interactiveRequest, requestController } = toInteractiveRequest(request); + this.logger.info( + 'emitting the "request" event for %d listener(s)...', + this.emitter.listenerCount("request") + ); + this.emitter.once("request", ({ requestId: pendingRequestId }) => { + if (pendingRequestId !== requestId) { + return; + } + if (requestController.responsePromise.state === "pending") { + requestController.responsePromise.resolve(void 0); + } + }); + this.logger.info("awaiting for the mocked response..."); + const signal = interactiveRequest.signal; + const requestAborted = new DeferredPromise(); + if (signal) { + signal.addEventListener( + "abort", + () => { + requestAborted.reject(signal.reason); + }, + { once: true } + ); + } + const responsePromise = new DeferredPromise(); + const respondWith = (response) => { + this.logger.info("responding with a mock response:", response); + if (this.emitter.listenerCount("response") > 0) { + this.logger.info('emitting the "response" event...'); + const responseClone = response.clone(); + this.emitter.emit("response", { + response: responseClone, + isMockedResponse: true, + request: interactiveRequest, + requestId + }); + } + Object.defineProperty(response, "url", { + writable: false, + enumerable: true, + configurable: false, + value: request.url + }); + responsePromise.resolve(response); + }; + const errorWith = (reason) => { + responsePromise.reject(reason); + }; + const resolverResult = await until( + async () => { + const listenersFinished = emitAsync(this.emitter, "request", { + request: interactiveRequest, + requestId + }); + await Promise.race([ + requestAborted, + // Put the listeners invocation Promise in the same race condition + // with the request abort Promise because otherwise awaiting the listeners + // would always yield some response (or undefined). + listenersFinished, + requestController.responsePromise + ]); + this.logger.info("all request listeners have been resolved!"); + const mockedResponse2 = await requestController.responsePromise; + this.logger.info("event.respondWith called with:", mockedResponse2); + return mockedResponse2; + } + ); + if (requestAborted.state === "rejected") { + this.logger.info( + "request has been aborted:", + requestAborted.rejectionReason + ); + responsePromise.reject(requestAborted.rejectionReason); + return responsePromise; + } + if (resolverResult.error) { + this.logger.info( + "request listerner threw an error:", + resolverResult.error + ); + if (resolverResult.error instanceof Response) { + if (isResponseError(resolverResult.error)) { + errorWith(createNetworkError(resolverResult.error)); + } else { + respondWith(resolverResult.error); + } + } + if (this.emitter.listenerCount("unhandledException") > 0) { + await emitAsync(this.emitter, "unhandledException", { + error: resolverResult.error, + request, + requestId, + controller: { + respondWith, + errorWith + } + }); + if (responsePromise.state !== "pending") { + return responsePromise; + } + } + respondWith(createServerErrorResponse(resolverResult.error)); + return responsePromise; + } + const mockedResponse = resolverResult.data; + if (mockedResponse && !((_a = request.signal) == null ? void 0 : _a.aborted)) { + this.logger.info("received mocked response:", mockedResponse); + if (isResponseError(mockedResponse)) { + this.logger.info( + "received a network error response, rejecting the request promise..." + ); + errorWith(createNetworkError(mockedResponse)); + } else { + respondWith(mockedResponse); + } + return responsePromise; + } + this.logger.info("no mocked response received!"); + return pureFetch(request).then((response) => { + this.logger.info("original fetch performed", response); + if (this.emitter.listenerCount("response") > 0) { + this.logger.info('emitting the "response" event...'); + const responseClone = response.clone(); + this.emitter.emit("response", { + response: responseClone, + isMockedResponse: false, + request: interactiveRequest, + requestId + }); + } + return response; + }); + }; + Object.defineProperty(globalThis.fetch, IS_PATCHED_MODULE, { + enumerable: true, + configurable: true, + value: true + }); + this.subscriptions.push(() => { + Object.defineProperty(globalThis.fetch, IS_PATCHED_MODULE, { + value: void 0 + }); + globalThis.fetch = pureFetch; + this.logger.info( + 'restored native "globalThis.fetch"!', + globalThis.fetch.name + ); + }); + } +}; +var FetchInterceptor = _FetchInterceptor; +FetchInterceptor.symbol = Symbol("fetch"); +function createNetworkError(cause) { + return Object.assign(new TypeError("Failed to fetch"), { + cause + }); +} +export { + FetchInterceptor +}; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/interceptors/fetch/index.mjs.map b/node_modules/@mswjs/interceptors/lib/node/interceptors/fetch/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..01fced53694c5e889593fd39df10486eccde74c3 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/interceptors/fetch/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/interceptors/fetch/index.ts","../../../../src/utils/canParseUrl.ts"],"sourcesContent":["import { invariant } from 'outvariant'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { until } from '@open-draft/until'\nimport { HttpRequestEventMap, IS_PATCHED_MODULE } from '../../glossary'\nimport { Interceptor } from '../../Interceptor'\nimport { toInteractiveRequest } from '../../utils/toInteractiveRequest'\nimport { emitAsync } from '../../utils/emitAsync'\nimport { canParseUrl } from '../../utils/canParseUrl'\nimport { createRequestId } from '../../createRequestId'\nimport {\n createServerErrorResponse,\n isResponseError,\n} from '../../utils/responseUtils'\n\nexport class FetchInterceptor extends Interceptor {\n static symbol = Symbol('fetch')\n\n constructor() {\n super(FetchInterceptor.symbol)\n }\n\n protected checkEnvironment() {\n return (\n typeof globalThis !== 'undefined' &&\n typeof globalThis.fetch !== 'undefined'\n )\n }\n\n protected async setup() {\n const pureFetch = globalThis.fetch\n\n invariant(\n !(pureFetch as any)[IS_PATCHED_MODULE],\n 'Failed to patch the \"fetch\" module: already patched.'\n )\n\n globalThis.fetch = async (input, init) => {\n const requestId = createRequestId()\n\n /**\n * @note Resolve potentially relative request URL\n * against the present `location`. This is mainly\n * for native `fetch` in JSDOM.\n * @see https://github.com/mswjs/msw/issues/1625\n */\n const resolvedInput =\n typeof input === 'string' &&\n typeof location !== 'undefined' &&\n !canParseUrl(input)\n ? new URL(input, location.origin)\n : input\n\n const request = new Request(resolvedInput, init)\n\n this.logger.info('[%s] %s', request.method, request.url)\n\n const { interactiveRequest, requestController } =\n toInteractiveRequest(request)\n\n this.logger.info(\n 'emitting the \"request\" event for %d listener(s)...',\n this.emitter.listenerCount('request')\n )\n\n this.emitter.once('request', ({ requestId: pendingRequestId }) => {\n if (pendingRequestId !== requestId) {\n return\n }\n\n if (requestController.responsePromise.state === 'pending') {\n requestController.responsePromise.resolve(undefined)\n }\n })\n\n this.logger.info('awaiting for the mocked response...')\n\n const signal = interactiveRequest.signal\n const requestAborted = new DeferredPromise()\n\n // Signal isn't always defined in react-native.\n if (signal) {\n signal.addEventListener(\n 'abort',\n () => {\n requestAborted.reject(signal.reason)\n },\n { once: true }\n )\n }\n\n const responsePromise = new DeferredPromise()\n\n const respondWith = (response: Response): void => {\n this.logger.info('responding with a mock response:', response)\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n // Clone the mocked response for the \"response\" event listener.\n // This way, the listener can read the response and not lock its body\n // for the actual fetch consumer.\n const responseClone = response.clone()\n\n this.emitter.emit('response', {\n response: responseClone,\n isMockedResponse: true,\n request: interactiveRequest,\n requestId,\n })\n }\n\n // Set the \"response.url\" property to equal the intercepted request URL.\n Object.defineProperty(response, 'url', {\n writable: false,\n enumerable: true,\n configurable: false,\n value: request.url,\n })\n\n responsePromise.resolve(response)\n }\n\n const errorWith = (reason: unknown): void => {\n responsePromise.reject(reason)\n }\n\n const resolverResult = await until(\n async () => {\n const listenersFinished = emitAsync(this.emitter, 'request', {\n request: interactiveRequest,\n requestId,\n })\n\n await Promise.race([\n requestAborted,\n // Put the listeners invocation Promise in the same race condition\n // with the request abort Promise because otherwise awaiting the listeners\n // would always yield some response (or undefined).\n listenersFinished,\n requestController.responsePromise,\n ])\n\n this.logger.info('all request listeners have been resolved!')\n\n const mockedResponse = await requestController.responsePromise\n this.logger.info('event.respondWith called with:', mockedResponse)\n\n return mockedResponse\n }\n )\n\n if (requestAborted.state === 'rejected') {\n this.logger.info(\n 'request has been aborted:',\n requestAborted.rejectionReason\n )\n\n responsePromise.reject(requestAborted.rejectionReason)\n return responsePromise\n }\n\n if (resolverResult.error) {\n this.logger.info(\n 'request listerner threw an error:',\n resolverResult.error\n )\n\n // Treat thrown Responses as mocked responses.\n if (resolverResult.error instanceof Response) {\n // Treat thrown Response.error() as a request error.\n if (isResponseError(resolverResult.error)) {\n errorWith(createNetworkError(resolverResult.error))\n } else {\n // Treat the rest of thrown Responses as mocked responses.\n respondWith(resolverResult.error)\n }\n }\n\n // Emit the \"unhandledException\" interceptor event so the client\n // can opt-out from exceptions translating to 500 error responses.\n\n if (this.emitter.listenerCount('unhandledException') > 0) {\n await emitAsync(this.emitter, 'unhandledException', {\n error: resolverResult.error,\n request,\n requestId,\n controller: {\n respondWith,\n errorWith,\n },\n })\n\n if (responsePromise.state !== 'pending') {\n return responsePromise\n }\n }\n\n // Unhandled exceptions in the request listeners are\n // synonymous to unhandled exceptions on the server.\n // Those are represented as 500 error responses.\n respondWith(createServerErrorResponse(resolverResult.error))\n return responsePromise\n }\n\n const mockedResponse = resolverResult.data\n\n if (mockedResponse && !request.signal?.aborted) {\n this.logger.info('received mocked response:', mockedResponse)\n\n // Reject the request Promise on mocked \"Response.error\" responses.\n if (isResponseError(mockedResponse)) {\n this.logger.info(\n 'received a network error response, rejecting the request promise...'\n )\n\n /**\n * Set the cause of the request promise rejection to the\n * network error Response instance. This differs from Undici.\n * Undici will forward the \"response.error\" custom property\n * as the rejection reason but for \"Response.error()\" static method\n * \"response.error\" will equal to undefined, making \"cause\" an empty Error.\n * @see https://github.com/nodejs/undici/blob/83cb522ae0157a19d149d72c7d03d46e34510d0a/lib/fetch/response.js#L344\n */\n errorWith(createNetworkError(mockedResponse))\n } else {\n respondWith(mockedResponse)\n }\n\n return responsePromise\n }\n\n this.logger.info('no mocked response received!')\n\n return pureFetch(request).then((response) => {\n this.logger.info('original fetch performed', response)\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n const responseClone = response.clone()\n\n this.emitter.emit('response', {\n response: responseClone,\n isMockedResponse: false,\n request: interactiveRequest,\n requestId,\n })\n }\n\n return response\n })\n }\n\n Object.defineProperty(globalThis.fetch, IS_PATCHED_MODULE, {\n enumerable: true,\n configurable: true,\n value: true,\n })\n\n this.subscriptions.push(() => {\n Object.defineProperty(globalThis.fetch, IS_PATCHED_MODULE, {\n value: undefined,\n })\n\n globalThis.fetch = pureFetch\n\n this.logger.info(\n 'restored native \"globalThis.fetch\"!',\n globalThis.fetch.name\n )\n })\n }\n}\n\nfunction createNetworkError(cause: unknown) {\n return Object.assign(new TypeError('Failed to fetch'), {\n cause,\n })\n}\n","/**\n * Returns a boolean indicating whether the given URL string\n * can be parsed into a `URL` instance.\n * A substitute for `URL.canParse()` for Node.js 18.\n */\nexport function canParseUrl(url: string): boolean {\n try {\n new URL(url)\n return true\n } catch (_error) {\n return false\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAAA,SAAS,iBAAiB;AAC1B,SAAS,uBAAuB;AAChC,SAAS,aAAa;;;ACGf,SAAS,YAAY,KAAsB;AAChD,MAAI;AACF,QAAI,IAAI,GAAG;AACX,WAAO;AAAA,EACT,SAAS,QAAP;AACA,WAAO;AAAA,EACT;AACF;;;ADEO,IAAM,oBAAN,cAA+B,YAAiC;AAAA,EAGrE,cAAc;AACZ,UAAM,kBAAiB,MAAM;AAAA,EAC/B;AAAA,EAEU,mBAAmB;AAC3B,WACE,OAAO,eAAe,eACtB,OAAO,WAAW,UAAU;AAAA,EAEhC;AAAA,EAEA,MAAgB,QAAQ;AACtB,UAAM,YAAY,WAAW;AAE7B;AAAA,MACE,CAAE,UAAkB,iBAAiB;AAAA,MACrC;AAAA,IACF;AAEA,eAAW,QAAQ,OAAO,OAAO,SAAS;AApC9C;AAqCM,YAAM,YAAY,gBAAgB;AAQlC,YAAM,gBACJ,OAAO,UAAU,YACjB,OAAO,aAAa,eACpB,CAAC,YAAY,KAAK,IACd,IAAI,IAAI,OAAO,SAAS,MAAM,IAC9B;AAEN,YAAM,UAAU,IAAI,QAAQ,eAAe,IAAI;AAE/C,WAAK,OAAO,KAAK,WAAW,QAAQ,QAAQ,QAAQ,GAAG;AAEvD,YAAM,EAAE,oBAAoB,kBAAkB,IAC5C,qBAAqB,OAAO;AAE9B,WAAK,OAAO;AAAA,QACV;AAAA,QACA,KAAK,QAAQ,cAAc,SAAS;AAAA,MACtC;AAEA,WAAK,QAAQ,KAAK,WAAW,CAAC,EAAE,WAAW,iBAAiB,MAAM;AAChE,YAAI,qBAAqB,WAAW;AAClC;AAAA,QACF;AAEA,YAAI,kBAAkB,gBAAgB,UAAU,WAAW;AACzD,4BAAkB,gBAAgB,QAAQ,MAAS;AAAA,QACrD;AAAA,MACF,CAAC;AAED,WAAK,OAAO,KAAK,qCAAqC;AAEtD,YAAM,SAAS,mBAAmB;AAClC,YAAM,iBAAiB,IAAI,gBAAgB;AAG3C,UAAI,QAAQ;AACV,eAAO;AAAA,UACL;AAAA,UACA,MAAM;AACJ,2BAAe,OAAO,OAAO,MAAM;AAAA,UACrC;AAAA,UACA,EAAE,MAAM,KAAK;AAAA,QACf;AAAA,MACF;AAEA,YAAM,kBAAkB,IAAI,gBAA0B;AAEtD,YAAM,cAAc,CAAC,aAA6B;AAChD,aAAK,OAAO,KAAK,oCAAoC,QAAQ;AAE7D,YAAI,KAAK,QAAQ,cAAc,UAAU,IAAI,GAAG;AAC9C,eAAK,OAAO,KAAK,kCAAkC;AAKnD,gBAAM,gBAAgB,SAAS,MAAM;AAErC,eAAK,QAAQ,KAAK,YAAY;AAAA,YAC5B,UAAU;AAAA,YACV,kBAAkB;AAAA,YAClB,SAAS;AAAA,YACT;AAAA,UACF,CAAC;AAAA,QACH;AAGA,eAAO,eAAe,UAAU,OAAO;AAAA,UACrC,UAAU;AAAA,UACV,YAAY;AAAA,UACZ,cAAc;AAAA,UACd,OAAO,QAAQ;AAAA,QACjB,CAAC;AAED,wBAAgB,QAAQ,QAAQ;AAAA,MAClC;AAEA,YAAM,YAAY,CAAC,WAA0B;AAC3C,wBAAgB,OAAO,MAAM;AAAA,MAC/B;AAEA,YAAM,iBAAiB,MAAM;AAAA,QAC3B,YAAY;AACV,gBAAM,oBAAoB,UAAU,KAAK,SAAS,WAAW;AAAA,YAC3D,SAAS;AAAA,YACT;AAAA,UACF,CAAC;AAED,gBAAM,QAAQ,KAAK;AAAA,YACjB;AAAA;AAAA;AAAA;AAAA,YAIA;AAAA,YACA,kBAAkB;AAAA,UACpB,CAAC;AAED,eAAK,OAAO,KAAK,2CAA2C;AAE5D,gBAAMA,kBAAiB,MAAM,kBAAkB;AAC/C,eAAK,OAAO,KAAK,kCAAkCA,eAAc;AAEjE,iBAAOA;AAAA,QACT;AAAA,MACF;AAEA,UAAI,eAAe,UAAU,YAAY;AACvC,aAAK,OAAO;AAAA,UACV;AAAA,UACA,eAAe;AAAA,QACjB;AAEA,wBAAgB,OAAO,eAAe,eAAe;AACrD,eAAO;AAAA,MACT;AAEA,UAAI,eAAe,OAAO;AACxB,aAAK,OAAO;AAAA,UACV;AAAA,UACA,eAAe;AAAA,QACjB;AAGA,YAAI,eAAe,iBAAiB,UAAU;AAE5C,cAAI,gBAAgB,eAAe,KAAK,GAAG;AACzC,sBAAU,mBAAmB,eAAe,KAAK,CAAC;AAAA,UACpD,OAAO;AAEL,wBAAY,eAAe,KAAK;AAAA,UAClC;AAAA,QACF;AAKA,YAAI,KAAK,QAAQ,cAAc,oBAAoB,IAAI,GAAG;AACxD,gBAAM,UAAU,KAAK,SAAS,sBAAsB;AAAA,YAClD,OAAO,eAAe;AAAA,YACtB;AAAA,YACA;AAAA,YACA,YAAY;AAAA,cACV;AAAA,cACA;AAAA,YACF;AAAA,UACF,CAAC;AAED,cAAI,gBAAgB,UAAU,WAAW;AACvC,mBAAO;AAAA,UACT;AAAA,QACF;AAKA,oBAAY,0BAA0B,eAAe,KAAK,CAAC;AAC3D,eAAO;AAAA,MACT;AAEA,YAAM,iBAAiB,eAAe;AAEtC,UAAI,kBAAkB,GAAC,aAAQ,WAAR,mBAAgB,UAAS;AAC9C,aAAK,OAAO,KAAK,6BAA6B,cAAc;AAG5D,YAAI,gBAAgB,cAAc,GAAG;AACnC,eAAK,OAAO;AAAA,YACV;AAAA,UACF;AAUA,oBAAU,mBAAmB,cAAc,CAAC;AAAA,QAC9C,OAAO;AACL,sBAAY,cAAc;AAAA,QAC5B;AAEA,eAAO;AAAA,MACT;AAEA,WAAK,OAAO,KAAK,8BAA8B;AAE/C,aAAO,UAAU,OAAO,EAAE,KAAK,CAAC,aAAa;AAC3C,aAAK,OAAO,KAAK,4BAA4B,QAAQ;AAErD,YAAI,KAAK,QAAQ,cAAc,UAAU,IAAI,GAAG;AAC9C,eAAK,OAAO,KAAK,kCAAkC;AAEnD,gBAAM,gBAAgB,SAAS,MAAM;AAErC,eAAK,QAAQ,KAAK,YAAY;AAAA,YAC5B,UAAU;AAAA,YACV,kBAAkB;AAAA,YAClB,SAAS;AAAA,YACT;AAAA,UACF,CAAC;AAAA,QACH;AAEA,eAAO;AAAA,MACT,CAAC;AAAA,IACH;AAEA,WAAO,eAAe,WAAW,OAAO,mBAAmB;AAAA,MACzD,YAAY;AAAA,MACZ,cAAc;AAAA,MACd,OAAO;AAAA,IACT,CAAC;AAED,SAAK,cAAc,KAAK,MAAM;AAC5B,aAAO,eAAe,WAAW,OAAO,mBAAmB;AAAA,QACzD,OAAO;AAAA,MACT,CAAC;AAED,iBAAW,QAAQ;AAEnB,WAAK,OAAO;AAAA,QACV;AAAA,QACA,WAAW,MAAM;AAAA,MACnB;AAAA,IACF,CAAC;AAAA,EACH;AACF;AAlQO,IAAM,mBAAN;AAAM,iBACJ,SAAS,OAAO,OAAO;AAmQhC,SAAS,mBAAmB,OAAgB;AAC1C,SAAO,OAAO,OAAO,IAAI,UAAU,iBAAiB,GAAG;AAAA,IACrD;AAAA,EACF,CAAC;AACH;","names":["mockedResponse"]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/presets/node.d.ts b/node_modules/@mswjs/interceptors/lib/node/presets/node.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4632e1243a082a04231543c9dd88d911e42684ca --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/presets/node.d.ts @@ -0,0 +1,16 @@ +import { ClientRequestInterceptor } from '../interceptors/ClientRequest/index.js'; +import { XMLHttpRequestInterceptor } from '../interceptors/XMLHttpRequest/index.js'; +import 'http'; +import 'https'; +import 'strict-event-emitter'; +import '../Interceptor-88ee47c0.js'; +import '@open-draft/deferred-promise'; +import '@open-draft/logger'; + +/** + * The default preset provisions the interception of requests + * regardless of their type (http/https/XMLHttpRequest). + */ +declare const _default: readonly [ClientRequestInterceptor, XMLHttpRequestInterceptor]; + +export { _default as default }; diff --git a/node_modules/@mswjs/interceptors/lib/node/presets/node.js b/node_modules/@mswjs/interceptors/lib/node/presets/node.js new file mode 100644 index 0000000000000000000000000000000000000000..b63698ab157d0bd94c4aea0cf285638c025326c8 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/presets/node.js @@ -0,0 +1,20 @@ +"use strict";Object.defineProperty(exports, "__esModule", {value: true}); + +var _chunkSXGRMPXPjs = require('../chunk-SXGRMPXP.js'); + + +var _chunkAPT7KA3Bjs = require('../chunk-APT7KA3B.js'); +require('../chunk-LK6DILFK.js'); +require('../chunk-EIBTX65O.js'); +require('../chunk-MQJ3JOOK.js'); +require('../chunk-E4AC7YAC.js'); + +// src/presets/node.ts +var node_default = [ + new (0, _chunkSXGRMPXPjs.ClientRequestInterceptor)(), + new (0, _chunkAPT7KA3Bjs.XMLHttpRequestInterceptor)() +]; + + +exports.default = node_default; +//# sourceMappingURL=node.js.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/presets/node.js.map b/node_modules/@mswjs/interceptors/lib/node/presets/node.js.map new file mode 100644 index 0000000000000000000000000000000000000000..4004cd39db4aa5e0965fe0c5718172cad6060f49 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/presets/node.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/presets/node.ts"],"names":[],"mappings":";;;;;;;;;;;;AAOA,IAAO,eAAQ;AAAA,EACb,IAAI,yBAAyB;AAAA,EAC7B,IAAI,0BAA0B;AAChC","sourcesContent":["import { ClientRequestInterceptor } from '../interceptors/ClientRequest'\nimport { XMLHttpRequestInterceptor } from '../interceptors/XMLHttpRequest'\n\n/**\n * The default preset provisions the interception of requests\n * regardless of their type (http/https/XMLHttpRequest).\n */\nexport default [\n new ClientRequestInterceptor(),\n new XMLHttpRequestInterceptor(),\n] as const\n"]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/presets/node.mjs b/node_modules/@mswjs/interceptors/lib/node/presets/node.mjs new file mode 100644 index 0000000000000000000000000000000000000000..29cce429ea13d0965a7c32cd37e5ce95d1d8188c --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/presets/node.mjs @@ -0,0 +1,20 @@ +import { + ClientRequestInterceptor +} from "../chunk-CVV3L375.mjs"; +import { + XMLHttpRequestInterceptor +} from "../chunk-KSHIDGUL.mjs"; +import "../chunk-6HYIRFX2.mjs"; +import "../chunk-OJ6O4LSC.mjs"; +import "../chunk-OUWBQF3Z.mjs"; +import "../chunk-Q7POAM5N.mjs"; + +// src/presets/node.ts +var node_default = [ + new ClientRequestInterceptor(), + new XMLHttpRequestInterceptor() +]; +export { + node_default as default +}; +//# sourceMappingURL=node.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/presets/node.mjs.map b/node_modules/@mswjs/interceptors/lib/node/presets/node.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..f881e550f7337babc74f23845f3d425135b09966 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/presets/node.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/presets/node.ts"],"sourcesContent":["import { ClientRequestInterceptor } from '../interceptors/ClientRequest'\nimport { XMLHttpRequestInterceptor } from '../interceptors/XMLHttpRequest'\n\n/**\n * The default preset provisions the interception of requests\n * regardless of their type (http/https/XMLHttpRequest).\n */\nexport default [\n new ClientRequestInterceptor(),\n new XMLHttpRequestInterceptor(),\n] as const\n"],"mappings":";;;;;;;;;;;;AAOA,IAAO,eAAQ;AAAA,EACb,IAAI,yBAAyB;AAAA,EAC7B,IAAI,0BAA0B;AAChC;","names":[]} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/package.json b/node_modules/@mswjs/interceptors/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ae0aa3490a16b17c4da4abdaa3480d08a612d0d0 --- /dev/null +++ b/node_modules/@mswjs/interceptors/package.json @@ -0,0 +1,240 @@ +{ + "_from": "@mswjs/interceptors@^0.29.0", + "_id": "@mswjs/interceptors@0.29.1", + "_inBundle": false, + "_integrity": "sha512-3rDakgJZ77+RiQUuSK69t1F0m8BQKA8Vh5DCS5V0DWvNY67zob2JhhQrhCO0AKLGINTRSFd1tBaHcJTkhefoSw==", + "_location": "/@mswjs/interceptors", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@mswjs/interceptors@^0.29.0", + "name": "@mswjs/interceptors", + "escapedName": "@mswjs%2finterceptors", + "scope": "@mswjs", + "rawSpec": "^0.29.0", + "saveSpec": null, + "fetchSpec": "^0.29.0" + }, + "_requiredBy": [ + "/msw" + ], + "_resolved": "https://registry.npmjs.org/@mswjs/interceptors/-/interceptors-0.29.1.tgz", + "_shasum": "e77fc58b5188569041d0440b25c9e9ebb1ccd60a", + "_spec": "@mswjs/interceptors@^0.29.0", + "_where": "/Users/sylvainfiloni/Documents/HuggingFace_Projects/live-vision/node_modules/msw", + "author": { + "name": "Artem Zakharchenko" + }, + "bugs": { + "url": "https://github.com/mswjs/interceptors/issues" + }, + "bundleDependencies": false, + "config": { + "commitizen": { + "path": "./node_modules/cz-conventional-changelog" + } + }, + "dependencies": { + "@open-draft/deferred-promise": "^2.2.0", + "@open-draft/logger": "^0.3.0", + "@open-draft/until": "^2.0.0", + "is-node-process": "^1.2.0", + "outvariant": "^1.2.1", + "strict-event-emitter": "^0.5.1" + }, + "deprecated": false, + "description": "Low-level HTTP/HTTPS/XHR/fetch request interception library.", + "devDependencies": { + "@commitlint/cli": "^16.0.2", + "@commitlint/config-conventional": "^16.0.0", + "@open-draft/test-server": "^0.5.1", + "@ossjs/release": "^0.8.1", + "@playwright/test": "^1.37.1", + "@types/cors": "^2.8.12", + "@types/express": "^4.17.13", + "@types/express-rate-limit": "^6.0.0", + "@types/follow-redirects": "^1.14.1", + "@types/jest": "^27.0.3", + "@types/node": "^16.11.26", + "@types/node-fetch": "2.5.12", + "@types/supertest": "^2.0.11", + "@types/ws": "^8.5.10", + "axios": "^1.6.0", + "body-parser": "^1.19.0", + "commitizen": "^4.2.4", + "cors": "^2.8.5", + "cross-env": "^7.0.3", + "cz-conventional-changelog": "3.3.0", + "engine.io-parser": "^5.2.1", + "express": "^4.17.3", + "express-rate-limit": "^6.3.0", + "follow-redirects": "^1.15.1", + "got": "^11.8.3", + "happy-dom": "^12.10.3", + "jest": "^27.4.3", + "node-fetch": "2.6.7", + "rimraf": "^3.0.2", + "simple-git-hooks": "^2.7.0", + "socket.io": "^4.7.4", + "socket.io-client": "^4.7.4", + "socket.io-parser": "^4.2.4", + "superagent": "^6.1.0", + "supertest": "^6.1.6", + "ts-jest": "^27.1.1", + "tsup": "^6.5.0", + "typescript": "^4.9.4", + "undici": "^6.6.2", + "vitest": "^1.2.2", + "vitest-environment-miniflare": "^2.14.1", + "wait-for-expect": "^3.0.2", + "web-encoding": "^1.1.5", + "webpack-http-server": "^0.5.0", + "ws": "^8.16.0" + }, + "engines": { + "node": ">=18" + }, + "exports": { + ".": { + "types": "./lib/node/index.d.ts", + "browser": { + "types": "./lib/browser/index.d.ts", + "require": "./lib/browser/index.js", + "import": "./lib/browser/index.mjs", + "default": "./lib/browser/index.js" + }, + "require": "./lib/node/index.js", + "import": "./lib/node/index.mjs", + "default": "./lib/node/index.js" + }, + "./ClientRequest": { + "types": "./lib/node/interceptors/ClientRequest/index.d.ts", + "node": { + "require": "./lib/node/interceptors/ClientRequest/index.js", + "import": "./lib/node/interceptors/ClientRequest/index.mjs" + }, + "browser": null, + "require": "./lib/node/interceptors/ClientRequest/index.js", + "import": "./lib/node/interceptors/ClientRequest/index.mjs", + "default": "./lib/node/interceptors/ClientRequest/index.js" + }, + "./XMLHttpRequest": { + "browser": { + "types": "./lib/browser/interceptors/XMLHttpRequest/index.d.ts", + "require": "./lib/browser/interceptors/XMLHttpRequest/index.js", + "import": "./lib/browser/interceptors/XMLHttpRequest/index.mjs", + "default": "./lib/browser/interceptors/XMLHttpRequest/index.js" + }, + "types": "./lib/node/interceptors/XMLHttpRequest/index.d.ts", + "require": "./lib/node/interceptors/XMLHttpRequest/index.js", + "import": "./lib/node/interceptors/XMLHttpRequest/index.mjs", + "default": "./lib/node/interceptors/XMLHttpRequest/index.js" + }, + "./fetch": { + "browser": { + "types": "./lib/browser/interceptors/fetch/index.d.ts", + "require": "./lib/browser/interceptors/fetch/index.js", + "import": "./lib/browser/interceptors/fetch/index.mjs", + "default": "./lib/browser/interceptors/fetch/index.js" + }, + "types": "./lib/node/interceptors/fetch/index.d.ts", + "require": "./lib/node/interceptors/fetch/index.js", + "import": "./lib/node/interceptors/fetch/index.mjs", + "default": "./lib/node/interceptors/fetch/index.js" + }, + "./WebSocket": { + "types": "./lib/browser/interceptors/WebSocket/index.d.ts", + "require": "./lib/browser/interceptors/WebSocket/index.js", + "import": "./lib/browser/interceptors/WebSocket/index.mjs", + "default": "./lib/browser/interceptors/WebSocket/index.js" + }, + "./RemoteHttpInterceptor": { + "types": "./lib/node/RemoteHttpInterceptor.d.ts", + "node": { + "require": "./lib/node/RemoteHttpInterceptor.js", + "import": "./lib/node/RemoteHttpInterceptor.mjs" + }, + "browser": null, + "require": "./lib/node/RemoteHttpInterceptor.js", + "import": "./lib/node/RemoteHttpInterceptor.mjs", + "default": "./lib/node/RemoteHttpInterceptor.js" + }, + "./presets/node": { + "types": "./lib/node/presets/node.d.ts", + "node": { + "require": "./lib/node/presets/node.js", + "import": "./lib/node/presets/node.mjs" + }, + "browser": null, + "require": "./lib/node/presets/node.js", + "import": "./lib/node/presets/node.mjs", + "default": "./lib/node/presets/node.js" + }, + "./presets/browser": { + "browser": { + "types": "./lib/browser/presets/browser.d.ts", + "require": "./lib/browser/presets/browser.js", + "import": "./lib/browser/presets/browser.mjs", + "default": "./lib/browser/presets/browser.js" + } + } + }, + "files": [ + "lib", + "README.md", + "src", + "ClientRequest", + "fetch", + "RemoteHttpInterceptor", + "XMLHttpRequest", + "WebSocket" + ], + "homepage": "https://github.com/mswjs/interceptors#readme", + "keywords": [ + "request", + "intercept", + "http", + "https", + "xmlhttprequest", + "xhr", + "fetch", + "low-level", + "mock", + "spy", + "testing" + ], + "license": "MIT", + "main": "./lib/node/index.js", + "module": "./lib/node/index.mjs", + "name": "@mswjs/interceptors", + "repository": { + "type": "git", + "url": "git+https://github.com/mswjs/interceptors.git" + }, + "resolutions": { + "memfs": "^3.4.13" + }, + "scripts": { + "build": "pnpm clean && cross-env NODE_ENV=production tsup --splitting", + "clean": "rimraf lib", + "release": "release publish", + "start": "tsc --build -w", + "test": "pnpm test:unit && pnpm test:integration", + "test:browser": "pnpm playwright test -c test/playwright.config.ts", + "test:integration": "pnpm test:node && pnpm test:browser", + "test:node": "vitest -c test/vitest.config.js", + "test:unit": "vitest" + }, + "types": "./lib/node/index.d.ts", + "version": "0.29.1", + "warnings": [ + { + "code": "ENOTSUP", + "required": { + "node": ">=18" + }, + "pkgid": "@mswjs/interceptors@0.29.1" + } + ] +} diff --git a/node_modules/@mswjs/interceptors/src/BatchInterceptor.test.ts b/node_modules/@mswjs/interceptors/src/BatchInterceptor.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..5891d626718a75d0c3ea2b3a98833f77a2885f0c --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/BatchInterceptor.test.ts @@ -0,0 +1,255 @@ +import { vi, it, expect, afterEach } from 'vitest' +import { Interceptor } from './Interceptor' +import { BatchInterceptor } from './BatchInterceptor' + +afterEach(() => { + vi.resetAllMocks() +}) + +it('applies child interceptors', () => { + class PrimaryInterceptor extends Interceptor { + constructor() { + super(Symbol('primary')) + } + } + + class SecondaryInterceptor extends Interceptor { + constructor() { + super(Symbol('secondary')) + } + } + + const instances = { + primary: new PrimaryInterceptor(), + secondary: new SecondaryInterceptor(), + } + + const interceptor = new BatchInterceptor({ + name: 'batch-apply', + interceptors: [instances.primary, instances.secondary], + }) + + const primaryApplySpy = vi.spyOn(instances.primary, 'apply') + const secondaryApplySpy = vi.spyOn(instances.secondary, 'apply') + + interceptor.apply() + + expect(primaryApplySpy).toHaveBeenCalledTimes(1) + expect(secondaryApplySpy).toHaveBeenCalledTimes(1) +}) + +it('proxies event listeners to the interceptors', () => { + class PrimaryInterceptor extends Interceptor<{ hello: [string] }> { + constructor() { + super(Symbol('primary')) + } + } + + class SecondaryInterceptor extends Interceptor<{ + goodbye: [string] + }> { + constructor() { + super(Symbol('secondary')) + } + } + + const instances = { + primary: new PrimaryInterceptor(), + secondary: new SecondaryInterceptor(), + } + + const interceptor = new BatchInterceptor({ + name: 'batch-proxy', + interceptors: [instances.primary, instances.secondary], + }) + + const helloListener = vi.fn() + interceptor.on('hello', helloListener) + + const goodbyeListener = vi.fn() + interceptor.on('goodbye', goodbyeListener) + + // Emulate the child interceptor emitting events. + instances.primary['emitter'].emit('hello', 'John') + instances.secondary['emitter'].emit('goodbye', 'Kate') + + // Must call the batch interceptor listener. + expect(helloListener).toHaveBeenCalledTimes(1) + expect(helloListener).toHaveBeenCalledWith('John') + expect(goodbyeListener).toHaveBeenCalledTimes(1) + expect(goodbyeListener).toHaveBeenCalledWith('Kate') +}) + +it('disposes of child interceptors', async () => { + class PrimaryInterceptor extends Interceptor { + constructor() { + super(Symbol('primary')) + } + } + + class SecondaryInterceptor extends Interceptor { + constructor() { + super(Symbol('secondary')) + } + } + + const instances = { + primary: new PrimaryInterceptor(), + secondary: new SecondaryInterceptor(), + } + + const interceptor = new BatchInterceptor({ + name: 'batch-dispose', + interceptors: [instances.primary, instances.secondary], + }) + + const primaryDisposeSpy = vi.spyOn(instances.primary, 'dispose') + const secondaryDisposeSpy = vi.spyOn(instances.secondary, 'dispose') + + interceptor.apply() + interceptor.dispose() + + expect(primaryDisposeSpy).toHaveBeenCalledTimes(1) + expect(secondaryDisposeSpy).toHaveBeenCalledTimes(1) +}) + +it('forwards listeners added via "on()"', () => { + class FirstInterceptor extends Interceptor { + constructor() { + super(Symbol('first')) + } + } + class SecondaryInterceptor extends Interceptor { + constructor() { + super(Symbol('second')) + } + } + + const firstInterceptor = new FirstInterceptor() + const secondInterceptor = new SecondaryInterceptor() + + const interceptor = new BatchInterceptor({ + name: 'batch', + interceptors: [firstInterceptor, secondInterceptor], + }) + + const listener = vi.fn() + interceptor.on('foo', listener) + + expect(firstInterceptor['emitter'].listenerCount('foo')).toBe(1) + expect(secondInterceptor['emitter'].listenerCount('foo')).toBe(1) + expect(interceptor['emitter'].listenerCount('foo')).toBe(0) +}) + +it('forwards listeners removal via "off()"', () => { + type Events = { + foo: [] + } + + class FirstInterceptor extends Interceptor { + constructor() { + super(Symbol('first')) + } + } + class SecondaryInterceptor extends Interceptor { + constructor() { + super(Symbol('second')) + } + } + + const firstInterceptor = new FirstInterceptor() + const secondInterceptor = new SecondaryInterceptor() + + const interceptor = new BatchInterceptor({ + name: 'batch', + interceptors: [firstInterceptor, secondInterceptor], + }) + + const listener = vi.fn() + interceptor.on('foo', listener) + interceptor.off('foo', listener) + + expect(firstInterceptor['emitter'].listenerCount('foo')).toBe(0) + expect(secondInterceptor['emitter'].listenerCount('foo')).toBe(0) +}) + +it('forwards removal of all listeners by name via ".removeAllListeners()"', () => { + type Events = { + foo: [] + bar: [] + } + + class FirstInterceptor extends Interceptor { + constructor() { + super(Symbol('first')) + } + } + class SecondaryInterceptor extends Interceptor { + constructor() { + super(Symbol('second')) + } + } + + const firstInterceptor = new FirstInterceptor() + const secondInterceptor = new SecondaryInterceptor() + + const interceptor = new BatchInterceptor({ + name: 'batch', + interceptors: [firstInterceptor, secondInterceptor], + }) + + const listener = vi.fn() + interceptor.on('foo', listener) + interceptor.on('foo', listener) + interceptor.on('bar', listener) + + expect(firstInterceptor['emitter'].listenerCount('foo')).toBe(2) + expect(secondInterceptor['emitter'].listenerCount('foo')).toBe(2) + expect(firstInterceptor['emitter'].listenerCount('bar')).toBe(1) + expect(secondInterceptor['emitter'].listenerCount('bar')).toBe(1) + + interceptor.removeAllListeners('foo') + + expect(firstInterceptor['emitter'].listenerCount('foo')).toBe(0) + expect(secondInterceptor['emitter'].listenerCount('foo')).toBe(0) + expect(firstInterceptor['emitter'].listenerCount('bar')).toBe(1) + expect(secondInterceptor['emitter'].listenerCount('bar')).toBe(1) +}) + +it('forwards removal of all listeners via ".removeAllListeners()"', () => { + class FirstInterceptor extends Interceptor { + constructor() { + super(Symbol('first')) + } + } + class SecondaryInterceptor extends Interceptor { + constructor() { + super(Symbol('second')) + } + } + + const firstInterceptor = new FirstInterceptor() + const secondInterceptor = new SecondaryInterceptor() + + const interceptor = new BatchInterceptor({ + name: 'batch', + interceptors: [firstInterceptor, secondInterceptor], + }) + + const listener = vi.fn() + interceptor.on('foo', listener) + interceptor.on('foo', listener) + interceptor.on('bar', listener) + + expect(firstInterceptor['emitter'].listenerCount('foo')).toBe(2) + expect(secondInterceptor['emitter'].listenerCount('foo')).toBe(2) + expect(firstInterceptor['emitter'].listenerCount('bar')).toBe(1) + expect(secondInterceptor['emitter'].listenerCount('bar')).toBe(1) + + interceptor.removeAllListeners() + + expect(firstInterceptor['emitter'].listenerCount('foo')).toBe(0) + expect(secondInterceptor['emitter'].listenerCount('foo')).toBe(0) + expect(firstInterceptor['emitter'].listenerCount('bar')).toBe(0) + expect(secondInterceptor['emitter'].listenerCount('bar')).toBe(0) +}) diff --git a/node_modules/@mswjs/interceptors/src/BatchInterceptor.ts b/node_modules/@mswjs/interceptors/src/BatchInterceptor.ts new file mode 100644 index 0000000000000000000000000000000000000000..083ce5fb2386109b72119293fa8a5f17d82553f1 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/BatchInterceptor.ts @@ -0,0 +1,95 @@ +import { EventMap, Listener } from 'strict-event-emitter' +import { Interceptor, ExtractEventNames } from './Interceptor' + +export interface BatchInterceptorOptions< + InterceptorList extends ReadonlyArray> +> { + name: string + interceptors: InterceptorList +} + +export type ExtractEventMapType< + InterceptorList extends ReadonlyArray> +> = InterceptorList extends ReadonlyArray + ? InterceptorType extends Interceptor + ? EventMap + : never + : never + +/** + * A batch interceptor that exposes a single interface + * to apply and operate with multiple interceptors at once. + */ +export class BatchInterceptor< + InterceptorList extends ReadonlyArray>, + Events extends EventMap = ExtractEventMapType +> extends Interceptor { + static symbol: symbol + + private interceptors: InterceptorList + + constructor(options: BatchInterceptorOptions) { + BatchInterceptor.symbol = Symbol(options.name) + super(BatchInterceptor.symbol) + this.interceptors = options.interceptors + } + + protected setup() { + const logger = this.logger.extend('setup') + + logger.info('applying all %d interceptors...', this.interceptors.length) + + for (const interceptor of this.interceptors) { + logger.info('applying "%s" interceptor...', interceptor.constructor.name) + interceptor.apply() + + logger.info('adding interceptor dispose subscription') + this.subscriptions.push(() => interceptor.dispose()) + } + } + + public on>( + event: EventName, + listener: Listener + ): this { + // Instead of adding a listener to the batch interceptor, + // propagate the listener to each of the individual interceptors. + for (const interceptor of this.interceptors) { + interceptor.on(event, listener) + } + + return this + } + + public once>( + event: EventName, + listener: Listener + ): this { + for (const interceptor of this.interceptors) { + interceptor.once(event, listener) + } + + return this + } + + public off>( + event: EventName, + listener: Listener + ): this { + for (const interceptor of this.interceptors) { + interceptor.off(event, listener) + } + + return this + } + + public removeAllListeners>( + event?: EventName | undefined + ): this { + for (const interceptors of this.interceptors) { + interceptors.removeAllListeners(event) + } + + return this + } +} diff --git a/node_modules/@mswjs/interceptors/src/Interceptor.test.ts b/node_modules/@mswjs/interceptors/src/Interceptor.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..6b76606a553d4e783a782af040ede90e2b0ce7fa --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/Interceptor.test.ts @@ -0,0 +1,205 @@ +import { describe, vi, it, expect, afterEach } from 'vitest' +import { + Interceptor, + getGlobalSymbol, + deleteGlobalSymbol, + InterceptorReadyState, +} from './Interceptor' +import { nextTickAsync } from './utils/nextTick' + +const symbol = Symbol('test') + +afterEach(() => { + deleteGlobalSymbol(symbol) +}) + +it('does not set a maximum listeners limit', () => { + const interceptor = new Interceptor(symbol) + expect(interceptor['emitter'].getMaxListeners()).toBe(0) +}) + +describe('on()', () => { + it('adds a new listener using "on()"', () => { + const interceptor = new Interceptor(symbol) + expect(interceptor['emitter'].listenerCount('event')).toBe(0) + + const listener = vi.fn() + interceptor.on('event', listener) + expect(interceptor['emitter'].listenerCount('event')).toBe(1) + }) +}) + +describe('once()', () => { + it('calls the listener only once', () => { + const interceptor = new Interceptor(symbol) + const listener = vi.fn() + + interceptor.once('foo', listener) + expect(listener).not.toHaveBeenCalled() + + interceptor['emitter'].emit('foo', 'bar') + + expect(listener).toHaveBeenCalledTimes(1) + expect(listener).toHaveBeenCalledWith('bar') + + listener.mockReset() + + interceptor['emitter'].emit('foo', 'baz') + interceptor['emitter'].emit('foo', 'xyz') + expect(listener).toHaveBeenCalledTimes(0) + }) +}) + +describe('off()', () => { + it('removes a listener using "off()"', () => { + const interceptor = new Interceptor(symbol) + expect(interceptor['emitter'].listenerCount('event')).toBe(0) + + const listener = vi.fn() + interceptor.on('event', listener) + expect(interceptor['emitter'].listenerCount('event')).toBe(1) + + interceptor.off('event', listener) + expect(interceptor['emitter'].listenerCount('event')).toBe(0) + }) +}) + +describe('persistence', () => { + it('stores global reference to the applied interceptor', () => { + const interceptor = new Interceptor(symbol) + interceptor.apply() + + expect(getGlobalSymbol(symbol)).toEqual(interceptor) + }) + + it('deletes global reference when the interceptor is disposed', () => { + const interceptor = new Interceptor(symbol) + + interceptor.apply() + interceptor.dispose() + + expect(getGlobalSymbol(symbol)).toBeUndefined() + }) +}) + +describe('readyState', () => { + it('sets the state to "INACTIVE" when the interceptor is created', () => { + const interceptor = new Interceptor(symbol) + expect(interceptor.readyState).toBe(InterceptorReadyState.INACTIVE) + }) + + it('leaves state as "INACTIVE" if the interceptor failed the environment check', async () => { + class MyInterceptor extends Interceptor { + protected checkEnvironment(): boolean { + return false + } + } + const interceptor = new MyInterceptor(symbol) + interceptor.apply() + + expect(interceptor.readyState).toBe(InterceptorReadyState.INACTIVE) + }) + + it('perfroms state transition when the interceptor is applying', async () => { + const interceptor = new Interceptor(symbol) + interceptor.apply() + + // The interceptor's state transitions to APPLIED immediately. + // The only exception is if something throws during the setup. + expect(interceptor.readyState).toBe(InterceptorReadyState.APPLIED) + }) + + it('perfroms state transition when disposing of the interceptor', async () => { + const interceptor = new Interceptor(symbol) + interceptor.apply() + interceptor.dispose() + + // The interceptor's state transitions to DISPOSED immediately. + // The only exception is if something throws during the teardown. + expect(interceptor.readyState).toBe(InterceptorReadyState.DISPOSED) + }) +}) + +describe('apply', () => { + it('does not apply the same interceptor multiple times', () => { + const interceptor = new Interceptor(symbol) + const setupSpy = vi.spyOn( + interceptor, + // @ts-expect-error Protected property spy. + 'setup' + ) + + // Intentionally apply the same interceptor multiple times. + interceptor.apply() + interceptor.apply() + interceptor.apply() + + // The "setup" must not be called repeatedly. + expect(setupSpy).toHaveBeenCalledTimes(1) + + expect(getGlobalSymbol(symbol)).toEqual(interceptor) + }) + + it('does not call "apply" if the interceptor fails environment check', () => { + class MyInterceptor extends Interceptor<{}> { + checkEnvironment() { + return false + } + } + + const interceptor = new MyInterceptor(Symbol('test')) + const setupSpy = vi.spyOn( + interceptor, + // @ts-expect-error Protected property spy. + 'setup' + ) + interceptor.apply() + + expect(setupSpy).not.toHaveBeenCalled() + }) + + it('proxies listeners from new interceptor to already running interceptor', () => { + const firstInterceptor = new Interceptor(symbol) + const secondInterceptor = new Interceptor(symbol) + + firstInterceptor.apply() + const firstListener = vi.fn() + firstInterceptor.on('test', firstListener) + + secondInterceptor.apply() + const secondListener = vi.fn() + secondInterceptor.on('test', secondListener) + + // Emitting event in the first interceptor will bubble to the second one. + firstInterceptor['emitter'].emit('test', 'hello world') + + expect(firstListener).toHaveBeenCalledTimes(1) + expect(firstListener).toHaveBeenCalledWith('hello world') + + expect(secondListener).toHaveBeenCalledTimes(1) + expect(secondListener).toHaveBeenCalledWith('hello world') + + expect(secondInterceptor['emitter'].listenerCount('test')).toBe(0) + }) +}) + +describe('dispose', () => { + it('removes all listeners when the interceptor is disposed', async () => { + const interceptor = new Interceptor(symbol) + + interceptor.apply() + const listener = vi.fn() + interceptor.on('test', listener) + interceptor.dispose() + + // Even after emitting an event, the listener must not get called. + interceptor['emitter'].emit('test') + expect(listener).not.toHaveBeenCalled() + + // The listener must not be called on the next tick either. + await nextTickAsync(() => { + interceptor['emitter'].emit('test') + expect(listener).not.toHaveBeenCalled() + }) + }) +}) diff --git a/node_modules/@mswjs/interceptors/src/Interceptor.ts b/node_modules/@mswjs/interceptors/src/Interceptor.ts new file mode 100644 index 0000000000000000000000000000000000000000..b33e74fdfb29d523e63711dae56e056a12dd8864 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/Interceptor.ts @@ -0,0 +1,249 @@ +import { Logger } from '@open-draft/logger' +import { Emitter, Listener } from 'strict-event-emitter' + +export type InterceptorEventMap = Record +export type InterceptorSubscription = () => void + +/** + * Request header name to detect when a single request + * is being handled by nested interceptors (XHR -> ClientRequest). + * Obscure by design to prevent collisions with user-defined headers. + * Ideally, come up with the Interceptor-level mechanism for this. + * @see https://github.com/mswjs/interceptors/issues/378 + */ +export const INTERNAL_REQUEST_ID_HEADER_NAME = + 'x-interceptors-internal-request-id' + +export function getGlobalSymbol(symbol: Symbol): V | undefined { + return ( + // @ts-ignore https://github.com/Microsoft/TypeScript/issues/24587 + globalThis[symbol] || undefined + ) +} + +function setGlobalSymbol(symbol: Symbol, value: any): void { + // @ts-ignore + globalThis[symbol] = value +} + +export function deleteGlobalSymbol(symbol: Symbol): void { + // @ts-ignore + delete globalThis[symbol] +} + +export enum InterceptorReadyState { + INACTIVE = 'INACTIVE', + APPLYING = 'APPLYING', + APPLIED = 'APPLIED', + DISPOSING = 'DISPOSING', + DISPOSED = 'DISPOSED', +} + +export type ExtractEventNames> = + Events extends Record ? EventName : never + +export class Interceptor { + protected emitter: Emitter + protected subscriptions: Array + protected logger: Logger + + public readyState: InterceptorReadyState + + constructor(private readonly symbol: symbol) { + this.readyState = InterceptorReadyState.INACTIVE + + this.emitter = new Emitter() + this.subscriptions = [] + this.logger = new Logger(symbol.description!) + + // Do not limit the maximum number of listeners + // so not to limit the maximum amount of parallel events emitted. + this.emitter.setMaxListeners(0) + + this.logger.info('constructing the interceptor...') + } + + /** + * Determine if this interceptor can be applied + * in the current environment. + */ + protected checkEnvironment(): boolean { + return true + } + + /** + * Apply this interceptor to the current process. + * Returns an already running interceptor instance if it's present. + */ + public apply(): void { + const logger = this.logger.extend('apply') + logger.info('applying the interceptor...') + + if (this.readyState === InterceptorReadyState.APPLIED) { + logger.info('intercepted already applied!') + return + } + + const shouldApply = this.checkEnvironment() + + if (!shouldApply) { + logger.info('the interceptor cannot be applied in this environment!') + return + } + + this.readyState = InterceptorReadyState.APPLYING + + // Whenever applying a new interceptor, check if it hasn't been applied already. + // This enables to apply the same interceptor multiple times, for example from a different + // interceptor, only proxying events but keeping the stubs in a single place. + const runningInstance = this.getInstance() + + if (runningInstance) { + logger.info('found a running instance, reusing...') + + // Proxy any listeners you set on this instance to the running instance. + this.on = (event, listener) => { + logger.info('proxying the "%s" listener', event) + + // Add listeners to the running instance so they appear + // at the top of the event listeners list and are executed first. + runningInstance.emitter.addListener(event, listener) + + // Ensure that once this interceptor instance is disposed, + // it removes all listeners it has appended to the running interceptor instance. + this.subscriptions.push(() => { + runningInstance.emitter.removeListener(event, listener) + logger.info('removed proxied "%s" listener!', event) + }) + + return this + } + + this.readyState = InterceptorReadyState.APPLIED + + return + } + + logger.info('no running instance found, setting up a new instance...') + + // Setup the interceptor. + this.setup() + + // Store the newly applied interceptor instance globally. + this.setInstance() + + this.readyState = InterceptorReadyState.APPLIED + } + + /** + * Setup the module augments and stubs necessary for this interceptor. + * This method is not run if there's a running interceptor instance + * to prevent instantiating an interceptor multiple times. + */ + protected setup(): void {} + + /** + * Listen to the interceptor's public events. + */ + public on>( + event: EventName, + listener: Listener + ): this { + const logger = this.logger.extend('on') + + if ( + this.readyState === InterceptorReadyState.DISPOSING || + this.readyState === InterceptorReadyState.DISPOSED + ) { + logger.info('cannot listen to events, already disposed!') + return this + } + + logger.info('adding "%s" event listener:', event, listener) + + this.emitter.on(event, listener) + return this + } + + public once>( + event: EventName, + listener: Listener + ): this { + this.emitter.once(event, listener) + return this + } + + public off>( + event: EventName, + listener: Listener + ): this { + this.emitter.off(event, listener) + return this + } + + public removeAllListeners>( + event?: EventName + ): this { + this.emitter.removeAllListeners(event) + return this + } + + /** + * Disposes of any side-effects this interceptor has introduced. + */ + public dispose(): void { + const logger = this.logger.extend('dispose') + + if (this.readyState === InterceptorReadyState.DISPOSED) { + logger.info('cannot dispose, already disposed!') + return + } + + logger.info('disposing the interceptor...') + this.readyState = InterceptorReadyState.DISPOSING + + if (!this.getInstance()) { + logger.info('no interceptors running, skipping dispose...') + return + } + + // Delete the global symbol as soon as possible, + // indicating that the interceptor is no longer running. + this.clearInstance() + + logger.info('global symbol deleted:', getGlobalSymbol(this.symbol)) + + if (this.subscriptions.length > 0) { + logger.info('disposing of %d subscriptions...', this.subscriptions.length) + + for (const dispose of this.subscriptions) { + dispose() + } + + this.subscriptions = [] + + logger.info('disposed of all subscriptions!', this.subscriptions.length) + } + + this.emitter.removeAllListeners() + logger.info('destroyed the listener!') + + this.readyState = InterceptorReadyState.DISPOSED + } + + private getInstance(): this | undefined { + const instance = getGlobalSymbol(this.symbol) + this.logger.info('retrieved global instance:', instance?.constructor?.name) + return instance + } + + private setInstance(): void { + setGlobalSymbol(this.symbol, this) + this.logger.info('set global instance!', this.symbol.description) + } + + private clearInstance(): void { + deleteGlobalSymbol(this.symbol) + this.logger.info('cleared global instance!', this.symbol.description) + } +} diff --git a/node_modules/@mswjs/interceptors/src/RemoteHttpInterceptor.ts b/node_modules/@mswjs/interceptors/src/RemoteHttpInterceptor.ts new file mode 100644 index 0000000000000000000000000000000000000000..2e2485ad19ac06ac57c8703ef5674d9b6d7a1dd1 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/RemoteHttpInterceptor.ts @@ -0,0 +1,237 @@ +import { ChildProcess } from 'child_process' +import { HttpRequestEventMap } from './glossary' +import { Interceptor } from './Interceptor' +import { BatchInterceptor } from './BatchInterceptor' +import { ClientRequestInterceptor } from './interceptors/ClientRequest' +import { XMLHttpRequestInterceptor } from './interceptors/XMLHttpRequest' +import { toInteractiveRequest } from './utils/toInteractiveRequest' +import { emitAsync } from './utils/emitAsync' + +export interface SerializedRequest { + id: string + url: string + method: string + headers: Array<[string, string]> + credentials: RequestCredentials + body: string +} + +interface RevivedRequest extends Omit { + url: URL + headers: Headers +} + +export interface SerializedResponse { + status: number + statusText: string + headers: Array<[string, string]> + body: string +} + +export class RemoteHttpInterceptor extends BatchInterceptor< + [ClientRequestInterceptor, XMLHttpRequestInterceptor] +> { + constructor() { + super({ + name: 'remote-interceptor', + interceptors: [ + new ClientRequestInterceptor(), + new XMLHttpRequestInterceptor(), + ], + }) + } + + protected setup() { + super.setup() + + let handleParentMessage: NodeJS.MessageListener + + this.on('request', async ({ request, requestId }) => { + // Send the stringified intercepted request to + // the parent process where the remote resolver is established. + const serializedRequest = JSON.stringify({ + id: requestId, + method: request.method, + url: request.url, + headers: Array.from(request.headers.entries()), + credentials: request.credentials, + body: ['GET', 'HEAD'].includes(request.method) + ? null + : await request.text(), + } as SerializedRequest) + + this.logger.info( + 'sent serialized request to the child:', + serializedRequest + ) + process.send?.(`request:${serializedRequest}`) + + const responsePromise = new Promise((resolve) => { + handleParentMessage = (message) => { + if (typeof message !== 'string') { + return resolve() + } + + if (message.startsWith(`response:${requestId}`)) { + const [, serializedResponse] = + message.match(/^response:.+?:(.+)$/) || [] + + if (!serializedResponse) { + return resolve() + } + + const responseInit = JSON.parse( + serializedResponse + ) as SerializedResponse + + const mockedResponse = new Response(responseInit.body, { + status: responseInit.status, + statusText: responseInit.statusText, + headers: responseInit.headers, + }) + + request.respondWith(mockedResponse) + return resolve() + } + } + }) + + // Listen for the mocked response message from the parent. + this.logger.info( + 'add "message" listener to the parent process', + handleParentMessage + ) + process.addListener('message', handleParentMessage) + + return responsePromise + }) + + this.subscriptions.push(() => { + process.removeListener('message', handleParentMessage) + }) + } +} + +export function requestReviver(key: string, value: any) { + switch (key) { + case 'url': + return new URL(value) + + case 'headers': + return new Headers(value) + + default: + return value + } +} + +export interface RemoveResolverOptions { + process: ChildProcess +} + +export class RemoteHttpResolver extends Interceptor { + static symbol = Symbol('remote-resolver') + private process: ChildProcess + + constructor(options: RemoveResolverOptions) { + super(RemoteHttpResolver.symbol) + this.process = options.process + } + + protected setup() { + const logger = this.logger.extend('setup') + + const handleChildMessage: NodeJS.MessageListener = async (message) => { + logger.info('received message from child!', message) + + if (typeof message !== 'string' || !message.startsWith('request:')) { + logger.info('unknown message, ignoring...') + return + } + + const [, serializedRequest] = message.match(/^request:(.+)$/) || [] + if (!serializedRequest) { + return + } + + const requestJson = JSON.parse( + serializedRequest, + requestReviver + ) as RevivedRequest + logger.info('parsed intercepted request', requestJson) + + const capturedRequest = new Request(requestJson.url, { + method: requestJson.method, + headers: new Headers(requestJson.headers), + credentials: requestJson.credentials, + body: requestJson.body, + }) + + const { interactiveRequest, requestController } = + toInteractiveRequest(capturedRequest) + + this.emitter.once('request', () => { + if (requestController.responsePromise.state === 'pending') { + requestController.respondWith(undefined) + } + }) + + await emitAsync(this.emitter, 'request', { + request: interactiveRequest, + requestId: requestJson.id, + }) + + const mockedResponse = await requestController.responsePromise + + if (!mockedResponse) { + return + } + + logger.info('event.respondWith called with:', mockedResponse) + const responseClone = mockedResponse.clone() + const responseText = await mockedResponse.text() + + // Send the mocked response to the child process. + const serializedResponse = JSON.stringify({ + status: mockedResponse.status, + statusText: mockedResponse.statusText, + headers: Array.from(mockedResponse.headers.entries()), + body: responseText, + } as SerializedResponse) + + this.process.send( + `response:${requestJson.id}:${serializedResponse}`, + (error) => { + if (error) { + return + } + + // Emit an optimistic "response" event at this point, + // not to rely on the back-and-forth signaling for the sake of the event. + this.emitter.emit('response', { + response: responseClone, + isMockedResponse: true, + request: capturedRequest, + requestId: requestJson.id, + }) + } + ) + + logger.info( + 'sent serialized mocked response to the parent:', + serializedResponse + ) + } + + this.subscriptions.push(() => { + this.process.removeListener('message', handleChildMessage) + logger.info('removed the "message" listener from the child process!') + }) + + logger.info('adding a "message" listener to the child process') + this.process.addListener('message', handleChildMessage) + + this.process.once('error', () => this.dispose()) + this.process.once('exit', () => this.dispose()) + } +} diff --git a/node_modules/@mswjs/interceptors/src/createRequestId.test.ts b/node_modules/@mswjs/interceptors/src/createRequestId.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..a59b2c049f3b3dfe0bea0524c3ec27ed10e205b1 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/createRequestId.test.ts @@ -0,0 +1,7 @@ +import { it, expect } from 'vitest' +import { createRequestId } from './createRequestId' +import { REQUEST_ID_REGEXP } from '../test/helpers' + +it('returns a request ID', () => { + expect(createRequestId()).toMatch(REQUEST_ID_REGEXP) +}) diff --git a/node_modules/@mswjs/interceptors/src/createRequestId.ts b/node_modules/@mswjs/interceptors/src/createRequestId.ts new file mode 100644 index 0000000000000000000000000000000000000000..318d2eb954d8d4620e6b047d38a6feac8744121a --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/createRequestId.ts @@ -0,0 +1,9 @@ +/** + * Generate a random ID string to represent a request. + * @example + * createRequestId() + * // "f774b6c9c600f" + */ +export function createRequestId(): string { + return Math.random().toString(16).slice(2) +} diff --git a/node_modules/@mswjs/interceptors/src/glossary.ts b/node_modules/@mswjs/interceptors/src/glossary.ts new file mode 100644 index 0000000000000000000000000000000000000000..65c5d5b9d5d33b16689d973667a93bdb367ff5d0 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/glossary.ts @@ -0,0 +1,33 @@ +import type { InteractiveRequest } from './utils/toInteractiveRequest' + +export const IS_PATCHED_MODULE: unique symbol = Symbol('isPatchedModule') + +export type RequestCredentials = 'omit' | 'include' | 'same-origin' + +export type HttpRequestEventMap = { + request: [ + args: { + request: InteractiveRequest + requestId: string + } + ] + response: [ + args: { + response: Response + isMockedResponse: boolean + request: Request + requestId: string + } + ] + unhandledException: [ + args: { + error: unknown + request: Request + requestId: string + controller: { + respondWith(response: Response): void + errorWith(error?: Error): void + } + } + ] +} diff --git a/node_modules/@mswjs/interceptors/src/index.ts b/node_modules/@mswjs/interceptors/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..3be0e36b9de674730aa0693b6ee52ab708441076 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/index.ts @@ -0,0 +1,9 @@ +export * from './glossary' +export * from './Interceptor' +export * from './BatchInterceptor' + +/* Utils */ +export { createRequestId } from './createRequestId' +export { getCleanUrl } from './utils/getCleanUrl' +export { encodeBuffer, decodeBuffer } from './utils/bufferUtils' +export { isResponseWithoutBody } from './utils/responseUtils' diff --git a/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/NodeClientRequest.test.ts b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/NodeClientRequest.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..e835813366e78427d13651c712a36a81c4bb1c4f --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/NodeClientRequest.test.ts @@ -0,0 +1,206 @@ +import { vi, it, expect, beforeAll, afterAll } from 'vitest' +import express from 'express' +import { IncomingMessage } from 'http' +import { Emitter } from 'strict-event-emitter' +import { Logger } from '@open-draft/logger' +import { HttpServer } from '@open-draft/test-server/http' +import { DeferredPromise } from '@open-draft/deferred-promise' +import { NodeClientRequest } from './NodeClientRequest' +import { getIncomingMessageBody } from './utils/getIncomingMessageBody' +import { normalizeClientRequestArgs } from './utils/normalizeClientRequestArgs' +import { sleep } from '../../../test/helpers' +import { HttpRequestEventMap } from '../../glossary' + +const httpServer = new HttpServer((app) => { + app.post('/comment', (_req, res) => { + res.status(200).send('original-response') + }) + + app.post('/write', express.text(), (req, res) => { + res.status(200).send(req.body) + }) +}) + +const logger = new Logger('test') + +beforeAll(async () => { + await httpServer.listen() +}) + +afterAll(async () => { + await httpServer.close() +}) + +it('gracefully finishes the request when it has a mocked response', async () => { + const emitter = new Emitter() + const request = new NodeClientRequest( + normalizeClientRequestArgs('http:', 'http://any.thing', { + method: 'PUT', + }), + { + emitter, + logger, + } + ) + + emitter.on('request', ({ request }) => { + request.respondWith( + new Response('mocked-response', { + status: 301, + headers: { + 'x-custom-header': 'yes', + }, + }) + ) + }) + + request.end() + + const responseReceived = new DeferredPromise() + + request.on('response', async (response) => { + responseReceived.resolve(response) + }) + const response = await responseReceived + + // Request must be marked as finished as soon as it's sent. + expect(request.writableEnded).toBe(true) + expect(request.writableFinished).toBe(true) + expect(request.writableCorked).toBe(0) + + /** + * Consume the response body, which will handle the "data" and "end" + * events of the incoming message. After this point, the response is finished. + */ + const text = await getIncomingMessageBody(response) + + // Response must be marked as finished as soon as its done. + expect(request['response'].complete).toBe(true) + + expect(response.statusCode).toBe(301) + expect(response.headers).toHaveProperty('x-custom-header', 'yes') + expect(text).toBe('mocked-response') +}) + +it('responds with a mocked response when requesting an existing hostname', async () => { + const emitter = new Emitter() + const request = new NodeClientRequest( + normalizeClientRequestArgs('http:', httpServer.http.url('/comment')), + { + emitter, + logger, + } + ) + + emitter.on('request', ({ request }) => { + request.respondWith(new Response('mocked-response', { status: 201 })) + }) + + request.end() + + const responseReceived = new DeferredPromise() + request.on('response', async (response) => { + responseReceived.resolve(response) + }) + const response = await responseReceived + + expect(response.statusCode).toBe(201) + + const text = await getIncomingMessageBody(response) + expect(text).toBe('mocked-response') +}) + +it('performs the request as-is given resolver returned no mocked response', async () => { + const emitter = new Emitter() + const request = new NodeClientRequest( + normalizeClientRequestArgs('http:', httpServer.http.url('/comment'), { + method: 'POST', + }), + { + emitter, + logger, + } + ) + + request.end() + + const responseReceived = new DeferredPromise() + request.on('response', async (response) => { + responseReceived.resolve(response) + }) + const response = await responseReceived + + expect(request.finished).toBe(true) + expect(request.writableEnded).toBe(true) + + expect(response.statusCode).toBe(200) + expect(response.statusMessage).toBe('OK') + expect(response.headers).toHaveProperty('x-powered-by', 'Express') + + const text = await getIncomingMessageBody(response) + expect(text).toBe('original-response') +}) + +it('sends the request body to the server given no mocked response', async () => { + const emitter = new Emitter() + const request = new NodeClientRequest( + normalizeClientRequestArgs('http:', httpServer.http.url('/write'), { + method: 'POST', + headers: { + 'Content-Type': 'text/plain', + }, + }), + { + emitter, + logger, + } + ) + + request.write('one') + request.write('two') + request.end('three') + + const responseReceived = new DeferredPromise() + request.on('response', (response) => { + responseReceived.resolve(response) + }) + const response = await responseReceived + + expect(response.statusCode).toBe(200) + + const text = await getIncomingMessageBody(response) + expect(text).toBe('onetwothree') +}) + +it('does not send request body to the original server given mocked response', async () => { + const emitter = new Emitter() + const request = new NodeClientRequest( + normalizeClientRequestArgs('http:', httpServer.http.url('/write'), { + method: 'POST', + }), + { + emitter, + logger, + } + ) + + emitter.on('request', async ({ request }) => { + await sleep(200) + request.respondWith(new Response('mock created!', { status: 301 })) + }) + + request.write('one') + request.write('two') + request.end() + + const responseReceived = new DeferredPromise() + request.on('response', (response) => { + responseReceived.resolve(response) + }) + const response = await responseReceived + + expect(response.statusCode).toBe(301) + + const text = await getIncomingMessageBody(response) + expect(text).toBe('mock created!') +}) diff --git a/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/NodeClientRequest.ts b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/NodeClientRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..e07e87e9a274278eeb0b4f44c55eedcc1cde5f25 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/NodeClientRequest.ts @@ -0,0 +1,645 @@ +import { ClientRequest, IncomingMessage, STATUS_CODES } from 'node:http' +import type { Logger } from '@open-draft/logger' +import { until } from '@open-draft/until' +import { DeferredPromise } from '@open-draft/deferred-promise' +import type { ClientRequestEmitter } from '.' +import { + ClientRequestEndCallback, + ClientRequestEndChunk, + normalizeClientRequestEndArgs, +} from './utils/normalizeClientRequestEndArgs' +import { NormalizedClientRequestArgs } from './utils/normalizeClientRequestArgs' +import { + ClientRequestWriteArgs, + normalizeClientRequestWriteArgs, +} from './utils/normalizeClientRequestWriteArgs' +import { cloneIncomingMessage } from './utils/cloneIncomingMessage' +import { createResponse } from './utils/createResponse' +import { createRequest } from './utils/createRequest' +import { toInteractiveRequest } from '../../utils/toInteractiveRequest' +import { emitAsync } from '../../utils/emitAsync' +import { getRawFetchHeaders } from '../../utils/getRawFetchHeaders' +import { isNodeLikeError } from '../../utils/isNodeLikeError' +import { INTERNAL_REQUEST_ID_HEADER_NAME } from '../../Interceptor' +import { createRequestId } from '../../createRequestId' +import { + createServerErrorResponse, + isResponseError, +} from '../../utils/responseUtils' + +export type Protocol = 'http' | 'https' + +enum HttpClientInternalState { + // Have the concept of an idle request because different + // request methods can kick off request sending + // (e.g. ".end()" or ".flushHeaders()"). + Idle, + Sending, + Sent, + MockLookupStart, + MockLookupEnd, + ResponseReceived, +} + +export interface NodeClientOptions { + emitter: ClientRequestEmitter + logger: Logger +} + +export class NodeClientRequest extends ClientRequest { + /** + * The list of internal Node.js errors to suppress while + * using the "mock" response source. + */ + static suppressErrorCodes = [ + 'ENOTFOUND', + 'ECONNREFUSED', + 'ECONNRESET', + 'EAI_AGAIN', + 'ENETUNREACH', + 'EHOSTUNREACH', + ] + + /** + * Internal state of the request. + */ + private state: HttpClientInternalState + private responseType?: 'mock' | 'passthrough' + private response: IncomingMessage + private emitter: ClientRequestEmitter + private logger: Logger + private chunks: Array<{ + chunk?: string | Buffer + encoding?: BufferEncoding + }> = [] + private capturedError?: NodeJS.ErrnoException + + public url: URL + public requestBuffer: Buffer | null + + constructor( + [url, requestOptions, callback]: NormalizedClientRequestArgs, + options: NodeClientOptions + ) { + super(requestOptions, callback) + + this.logger = options.logger.extend( + `request ${requestOptions.method} ${url.href}` + ) + + this.logger.info('constructing ClientRequest using options:', { + url, + requestOptions, + callback, + }) + + this.state = HttpClientInternalState.Idle + this.url = url + this.emitter = options.emitter + + // Set request buffer to null by default so that GET/HEAD requests + // without a body wouldn't suddenly get one. + this.requestBuffer = null + + // Construct a mocked response message. + this.response = new IncomingMessage(this.socket!) + } + + private writeRequestBodyChunk( + chunk: string | Buffer | null, + encoding?: BufferEncoding + ): void { + if (chunk == null) { + return + } + + if (this.requestBuffer == null) { + this.requestBuffer = Buffer.from([]) + } + + const resolvedChunk = Buffer.isBuffer(chunk) + ? chunk + : Buffer.from(chunk, encoding) + + this.requestBuffer = Buffer.concat([this.requestBuffer, resolvedChunk]) + } + + write(...args: ClientRequestWriteArgs): boolean { + const [chunk, encoding, callback] = normalizeClientRequestWriteArgs(args) + this.logger.info('write:', { chunk, encoding, callback }) + this.chunks.push({ chunk, encoding }) + + // Write each request body chunk to the internal buffer. + this.writeRequestBodyChunk(chunk, encoding) + + this.logger.info( + 'chunk successfully stored!', + this.requestBuffer?.byteLength + ) + + /** + * Prevent invoking the callback if the written chunk is empty. + * @see https://nodejs.org/api/http.html#requestwritechunk-encoding-callback + */ + if (!chunk || chunk.length === 0) { + this.logger.info('written chunk is empty, skipping callback...') + } else { + callback?.() + } + + // Do not write the request body chunks to prevent + // the Socket from sending data to a potentially existing + // server when there is a mocked response defined. + return true + } + + end(...args: any): this { + this.logger.info('end', args) + + const requestId = createRequestId() + + const [chunk, encoding, callback] = normalizeClientRequestEndArgs(...args) + this.logger.info('normalized arguments:', { chunk, encoding, callback }) + + // Write the last request body chunk passed to the "end()" method. + this.writeRequestBodyChunk(chunk, encoding || undefined) + + /** + * @note Mark the request as sent immediately when invoking ".end()". + * In Node.js, calling ".end()" will flush the remaining request body + * and mark the request as "finished" immediately ("end" is synchronous) + * but we delegate that property update to: + * + * - respondWith(), in the case of mocked responses; + * - super.end(), in the case of bypassed responses. + * + * For that reason, we have to keep an internal flag for a finished request. + */ + this.state = HttpClientInternalState.Sent + + const capturedRequest = createRequest(this) + const { interactiveRequest, requestController } = + toInteractiveRequest(capturedRequest) + + /** + * @todo Remove this modification of the original request + * and expose the controller alongside it in the "request" + * listener argument. + */ + Object.defineProperty(capturedRequest, 'respondWith', { + value: requestController.respondWith.bind(requestController), + }) + + // Prevent handling this request if it has already been handled + // in another (parent) interceptor (like XMLHttpRequest -> ClientRequest). + // That means some interceptor up the chain has concluded that + // this request must be performed as-is. + if (this.hasHeader(INTERNAL_REQUEST_ID_HEADER_NAME)) { + this.removeHeader(INTERNAL_REQUEST_ID_HEADER_NAME) + return this.passthrough(chunk, encoding, callback) + } + + // Add the last "request" listener that always resolves + // the pending response Promise. This way if the consumer + // hasn't handled the request themselves, we will prevent + // the response Promise from pending indefinitely. + this.emitter.once('request', ({ requestId: pendingRequestId }) => { + /** + * @note Ignore request events emitted by irrelevant + * requests. This happens when response patching. + */ + if (pendingRequestId !== requestId) { + return + } + + if (requestController.responsePromise.state === 'pending') { + this.logger.info( + 'request has not been handled in listeners, executing fail-safe listener...' + ) + + requestController.responsePromise.resolve(undefined) + } + }) + + // Execute the resolver Promise like a side-effect. + // Node.js 16 forces "ClientRequest.end" to be synchronous and return "this". + until(async () => { + // Notify the interceptor about the request. + // This will call any "request" listeners the users have. + this.logger.info( + 'emitting the "request" event for %d listener(s)...', + this.emitter.listenerCount('request') + ) + + this.state = HttpClientInternalState.MockLookupStart + + await emitAsync(this.emitter, 'request', { + request: interactiveRequest, + requestId, + }) + + this.logger.info('all "request" listeners done!') + + const mockedResponse = await requestController.responsePromise + this.logger.info('event.respondWith called with:', mockedResponse) + + return mockedResponse + }).then((resolverResult) => { + this.logger.info('the listeners promise awaited!') + + this.state = HttpClientInternalState.MockLookupEnd + + /** + * @fixme We are in the "end()" method that still executes in parallel + * to our mocking logic here. This can be solved by migrating to the + * Proxy-based approach and deferring the passthrough "end()" properly. + * @see https://github.com/mswjs/interceptors/issues/346 + */ + if (!this.headersSent) { + // Forward any request headers that the "request" listener + // may have modified before proceeding with this request. + for (const [headerName, headerValue] of capturedRequest.headers) { + this.setHeader(headerName, headerValue) + } + } + + if (resolverResult.error) { + this.logger.info( + 'unhandled resolver exception, coercing to an error response...', + resolverResult.error + ) + + // Handle thrown Response instances. + if (resolverResult.error instanceof Response) { + // Treat thrown Response.error() as a request error. + if (isResponseError(resolverResult.error)) { + this.logger.info( + 'received network error response, erroring request...' + ) + + this.errorWith(new TypeError('Network error')) + } else { + // Handle a thrown Response as a mocked response. + this.respondWith(resolverResult.error) + } + + return + } + + // Allow throwing Node.js-like errors, like connection rejection errors. + // Treat them as request errors. + if (isNodeLikeError(resolverResult.error)) { + this.errorWith(resolverResult.error) + return this + } + + until(async () => { + if (this.emitter.listenerCount('unhandledException') > 0) { + // Emit the "unhandledException" event to allow the client + // to opt-out from the default handling of exceptions + // as 500 error responses. + await emitAsync(this.emitter, 'unhandledException', { + error: resolverResult.error, + request: capturedRequest, + requestId, + controller: { + respondWith: this.respondWith.bind(this), + errorWith: this.errorWith.bind(this), + }, + }) + + // If after the "unhandledException" listeners are done, + // the request is either not writable (was mocked) or + // destroyed (has errored), do nothing. + if (this.writableEnded || this.destroyed) { + return + } + } + + // Unhandled exceptions in the request listeners are + // synonymous to unhandled exceptions on the server. + // Those are represented as 500 error responses. + this.respondWith(createServerErrorResponse(resolverResult.error)) + }) + + return this + } + + const mockedResponse = resolverResult.data + + if (mockedResponse) { + this.logger.info( + 'received mocked response:', + mockedResponse.status, + mockedResponse.statusText + ) + + /** + * @note Ignore this request being destroyed by TLS in Node.js + * due to connection errors. + */ + this.destroyed = false + + // Handle mocked "Response.error" network error responses. + if (isResponseError(mockedResponse)) { + this.logger.info( + 'received network error response, erroring request...' + ) + + /** + * There is no standardized error format for network errors + * in Node.js. Instead, emit a generic TypeError. + */ + this.errorWith(new TypeError('Network error')) + + return this + } + + const responseClone = mockedResponse.clone() + + this.respondWith(mockedResponse) + this.logger.info( + mockedResponse.status, + mockedResponse.statusText, + '(MOCKED)' + ) + + callback?.() + + this.logger.info('emitting the custom "response" event...') + this.emitter.emit('response', { + response: responseClone, + isMockedResponse: true, + request: capturedRequest, + requestId, + }) + + this.logger.info('request (mock) is completed') + + return this + } + + this.logger.info('no mocked response received!') + + this.once('response-internal', (message: IncomingMessage) => { + this.logger.info(message.statusCode, message.statusMessage) + this.logger.info('original response headers:', message.headers) + + this.logger.info('emitting the custom "response" event...') + this.emitter.emit('response', { + response: createResponse(message), + isMockedResponse: false, + request: capturedRequest, + requestId, + }) + }) + + return this.passthrough(chunk, encoding, callback) + }) + + return this + } + + emit(event: string, ...data: any[]) { + this.logger.info('emit: %s', event) + + if (event === 'response') { + this.logger.info('found "response" event, cloning the response...') + + try { + /** + * Clone the response object when emitting the "response" event. + * This prevents the response body stream from locking + * and allows reading it twice: + * 1. Internal "response" event from the observer. + * 2. Any external response body listeners. + * @see https://github.com/mswjs/interceptors/issues/161 + */ + const response = data[0] as IncomingMessage + const firstClone = cloneIncomingMessage(response) + const secondClone = cloneIncomingMessage(response) + + this.emit('response-internal', secondClone) + + this.logger.info( + 'response successfully cloned, emitting "response" event...' + ) + return super.emit(event, firstClone, ...data.slice(1)) + } catch (error) { + this.logger.info('error when cloning response:', error) + return super.emit(event, ...data) + } + } + + if (event === 'error') { + const error = data[0] as NodeJS.ErrnoException + const errorCode = error.code || '' + + this.logger.info('error:\n', error) + + // Suppress only specific Node.js connection errors. + if (NodeClientRequest.suppressErrorCodes.includes(errorCode)) { + // Until we aren't sure whether the request will be + // passthrough, capture the first emitted connection + // error in case we have to replay it for this request. + if (this.state < HttpClientInternalState.MockLookupEnd) { + if (!this.capturedError) { + this.capturedError = error + this.logger.info('captured the first error:', this.capturedError) + } + return false + } + + // Ignore any connection errors once we know the request + // has been resolved with a mocked response. Don't capture + // them as they won't ever be replayed. + if ( + this.state === HttpClientInternalState.ResponseReceived && + this.responseType === 'mock' + ) { + return false + } + } + } + + return super.emit(event, ...data) + } + + /** + * Performs the intercepted request as-is. + * Replays the captured request body chunks, + * still emits the internal events, and wraps + * up the request with `super.end()`. + */ + private passthrough( + chunk: ClientRequestEndChunk | null, + encoding?: BufferEncoding | null, + callback?: ClientRequestEndCallback | null + ): this { + this.state = HttpClientInternalState.ResponseReceived + this.responseType = 'passthrough' + + // Propagate previously captured errors. + // For example, a ECONNREFUSED error when connecting to a non-existing host. + if (this.capturedError) { + this.emit('error', this.capturedError) + return this + } + + this.logger.info('writing request chunks...', this.chunks) + + // Write the request body chunks in the order of ".write()" calls. + // Note that no request body has been written prior to this point + // in order to prevent the Socket to communicate with a potentially + // existing server. + for (const { chunk, encoding } of this.chunks) { + if (encoding) { + super.write(chunk, encoding) + } else { + super.write(chunk) + } + } + + this.once('error', (error) => { + this.logger.info('original request error:', error) + }) + + this.once('abort', () => { + this.logger.info('original request aborted!') + }) + + this.once('response-internal', (message: IncomingMessage) => { + this.logger.info(message.statusCode, message.statusMessage) + this.logger.info('original response headers:', message.headers) + }) + + this.logger.info('performing original request...') + + // This call signature is way too dynamic. + return super.end(...[chunk, encoding as any, callback].filter(Boolean)) + } + + /** + * Responds to this request instance using a mocked response. + */ + private respondWith(mockedResponse: Response): void { + this.logger.info('responding with a mocked response...', mockedResponse) + + this.state = HttpClientInternalState.ResponseReceived + this.responseType = 'mock' + + /** + * Mark the request as finished right before streaming back the response. + * This is not entirely conventional but this will allow the consumer to + * modify the outoging request in the interceptor. + * + * The request is finished when its headers and bodies have been sent. + * @see https://nodejs.org/api/http.html#event-finish + */ + Object.defineProperties(this, { + writableFinished: { value: true }, + writableEnded: { value: true }, + }) + this.emit('finish') + + const { status, statusText, headers, body } = mockedResponse + this.response.statusCode = status + this.response.statusMessage = statusText || STATUS_CODES[status] + + // Try extracting the raw headers from the headers instance. + // If not possible, fallback to the headers instance as-is. + const rawHeaders = getRawFetchHeaders(headers) || headers + + if (rawHeaders) { + this.response.headers = {} + + rawHeaders.forEach((headerValue, headerName) => { + /** + * @note Make sure that multi-value headers are appended correctly. + */ + this.response.rawHeaders.push(headerName, headerValue) + + const insensitiveHeaderName = headerName.toLowerCase() + const prevHeaders = this.response.headers[insensitiveHeaderName] + this.response.headers[insensitiveHeaderName] = prevHeaders + ? Array.prototype.concat([], prevHeaders, headerValue) + : headerValue + }) + } + this.logger.info('mocked response headers ready:', headers) + + /** + * Set the internal "res" property to the mocked "OutgoingMessage" + * to make the "ClientRequest" instance think there's data received + * from the socket. + * @see https://github.com/nodejs/node/blob/9c405f2591f5833d0247ed0fafdcd68c5b14ce7a/lib/_http_client.js#L501 + * + * Set the response immediately so the interceptor could stream data + * chunks to the request client as they come in. + */ + // @ts-ignore + this.res = this.response + this.emit('response', this.response) + + const isResponseStreamFinished = new DeferredPromise() + + const finishResponseStream = () => { + this.logger.info('finished response stream!') + + // Push "null" to indicate that the response body is complete + // and shouldn't be written to anymore. + this.response.push(null) + this.response.complete = true + + isResponseStreamFinished.resolve() + } + + if (body) { + const bodyReader = body.getReader() + const readNextChunk = async (): Promise => { + const { done, value } = await bodyReader.read() + + if (done) { + finishResponseStream() + return + } + + this.response.emit('data', value) + + return readNextChunk() + } + + readNextChunk() + } else { + finishResponseStream() + } + + isResponseStreamFinished.then(() => { + this.logger.info('finalizing response...') + this.response.emit('end') + this.terminate() + + this.logger.info('request complete!') + }) + } + + private errorWith(error: Error): void { + this.destroyed = true + this.emit('error', error) + this.terminate() + } + + /** + * Terminates a pending request. + */ + private terminate(): void { + /** + * @note Some request clients (e.g. Octokit) create a ClientRequest + * in a way that it has no Agent set. Now, whether that's correct is + * debatable, but we should still handle this case gracefully. + * @see https://github.com/mswjs/interceptors/issues/304 + */ + // @ts-ignore + this.agent?.destroy() + } +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/http.get.ts b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/http.get.ts new file mode 100644 index 0000000000000000000000000000000000000000..b6f3d684a887c047f2d63376e8e2137a66bbb092 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/http.get.ts @@ -0,0 +1,30 @@ +import { ClientRequest } from 'node:http' +import { + NodeClientOptions, + NodeClientRequest, + Protocol, +} from './NodeClientRequest' +import { + ClientRequestArgs, + normalizeClientRequestArgs, +} from './utils/normalizeClientRequestArgs' + +export function get(protocol: Protocol, options: NodeClientOptions) { + return function interceptorsHttpGet( + ...args: ClientRequestArgs + ): ClientRequest { + const clientRequestArgs = normalizeClientRequestArgs( + `${protocol}:`, + ...args + ) + const request = new NodeClientRequest(clientRequestArgs, options) + + /** + * @note https://nodejs.org/api/http.html#httpgetoptions-callback + * "http.get" sets the method to "GET" and calls "req.end()" automatically. + */ + request.end() + + return request + } +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/http.request.ts b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/http.request.ts new file mode 100644 index 0000000000000000000000000000000000000000..4e581ee715d29d12189e53cc7f811b5c13d0b20b --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/http.request.ts @@ -0,0 +1,27 @@ +import { ClientRequest } from 'http' +import { Logger } from '@open-draft/logger' +import { + NodeClientOptions, + NodeClientRequest, + Protocol, +} from './NodeClientRequest' +import { + normalizeClientRequestArgs, + ClientRequestArgs, +} from './utils/normalizeClientRequestArgs' + +const logger = new Logger('http request') + +export function request(protocol: Protocol, options: NodeClientOptions) { + return function interceptorsHttpRequest( + ...args: ClientRequestArgs + ): ClientRequest { + logger.info('request call (protocol "%s"):', protocol, args) + + const clientRequestArgs = normalizeClientRequestArgs( + `${protocol}:`, + ...args + ) + return new NodeClientRequest(clientRequestArgs, options) + } +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/index.test.ts b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/index.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..935b73e0c0a544d81ac69f4cabb4fa135b579896 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/index.test.ts @@ -0,0 +1,84 @@ +import { it, expect, beforeAll, afterAll } from 'vitest' +import http from 'http' +import { HttpServer } from '@open-draft/test-server/http' +import { DeferredPromise } from '@open-draft/deferred-promise' +import { ClientRequestInterceptor } from '.' +import { sleep } from '../../../test/helpers' + +const httpServer = new HttpServer((app) => { + app.get('/', (_req, res) => { + res.status(200).send('/') + }) + app.get('/get', (_req, res) => { + res.status(200).send('/get') + }) +}) + +const interceptor = new ClientRequestInterceptor() + +beforeAll(async () => { + interceptor.apply() + await httpServer.listen() +}) + +afterAll(async () => { + interceptor.dispose() + await httpServer.close() +}) + +it('forbids calling "respondWith" multiple times for the same request', async () => { + const requestUrl = httpServer.http.url('/') + + interceptor.on('request', function firstRequestListener({ request }) { + request.respondWith(new Response()) + }) + + const secondRequestEmitted = new DeferredPromise() + interceptor.on('request', function secondRequestListener({ request }) { + expect(() => + request.respondWith(new Response(null, { status: 301 })) + ).toThrow( + `Failed to respond to "GET ${requestUrl}" request: the "request" event has already been responded to.` + ) + + secondRequestEmitted.resolve() + }) + + const request = http.get(requestUrl) + await secondRequestEmitted + + const responseReceived = new DeferredPromise() + request.on('response', (response) => { + responseReceived.resolve(response) + }) + + const response = await responseReceived + expect(response.statusCode).toBe(200) + expect(response.statusMessage).toBe('OK') +}) + +it('abort the request if the abort signal is emitted', async () => { + const requestUrl = httpServer.http.url('/') + + const requestEmitted = new DeferredPromise() + interceptor.on('request', async function delayedResponse({ request }) { + requestEmitted.resolve() + await sleep(10_000) + request.respondWith(new Response()) + }) + + const abortController = new AbortController() + const request = http.get(requestUrl, { signal: abortController.signal }) + + await requestEmitted + + abortController.abort() + + const requestAborted = new DeferredPromise() + request.on('error', function (err) { + expect(err.name).toEqual('AbortError') + requestAborted.resolve() + }) + + await requestAborted +}) diff --git a/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/index.ts b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..edc599cff3d4d276e91208f17a8d6cf03b7a0fa1 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/index.ts @@ -0,0 +1,61 @@ +import http from 'http' +import https from 'https' +import type { Emitter } from 'strict-event-emitter' +import { HttpRequestEventMap } from '../../glossary' +import { Interceptor } from '../../Interceptor' +import { get } from './http.get' +import { request } from './http.request' +import { NodeClientOptions, Protocol } from './NodeClientRequest' + +export type ClientRequestEmitter = Emitter + +export type ClientRequestModules = Map + +/** + * Intercept requests made via the `ClientRequest` class. + * Such requests include `http.get`, `https.request`, etc. + */ +export class ClientRequestInterceptor extends Interceptor { + static interceptorSymbol = Symbol('http') + private modules: ClientRequestModules + + constructor() { + super(ClientRequestInterceptor.interceptorSymbol) + + this.modules = new Map() + this.modules.set('http', http) + this.modules.set('https', https) + } + + protected setup(): void { + const logger = this.logger.extend('setup') + + for (const [protocol, requestModule] of this.modules) { + const { request: pureRequest, get: pureGet } = requestModule + + this.subscriptions.push(() => { + requestModule.request = pureRequest + requestModule.get = pureGet + + logger.info('native "%s" module restored!', protocol) + }) + + const options: NodeClientOptions = { + emitter: this.emitter, + logger: this.logger, + } + + // @ts-ignore + requestModule.request = + // Force a line break. + request(protocol, options) + + // @ts-ignore + requestModule.get = + // Force a line break. + get(protocol, options) + + logger.info('native "%s" module patched!', protocol) + } + } +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/cloneIncomingMessage.test.ts b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/cloneIncomingMessage.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..bfd473bc4fa9a2344edabc6ad2ce1f6f43c831c2 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/cloneIncomingMessage.test.ts @@ -0,0 +1,26 @@ +import { it, expect } from 'vitest' +import { Socket } from 'net' +import { IncomingMessage } from 'http' +import { Stream, Readable, EventEmitter } from 'stream' +import { cloneIncomingMessage, IS_CLONE } from './cloneIncomingMessage' + +it('clones a given IncomingMessage', () => { + const message = new IncomingMessage(new Socket()) + message.statusCode = 200 + message.statusMessage = 'OK' + message.headers = { 'x-powered-by': 'msw' } + const clone = cloneIncomingMessage(message) + + // Prototypes must be preserved. + expect(clone).toBeInstanceOf(IncomingMessage) + expect(clone).toBeInstanceOf(EventEmitter) + expect(clone).toBeInstanceOf(Stream) + expect(clone).toBeInstanceOf(Readable) + + expect(clone.statusCode).toEqual(200) + expect(clone.statusMessage).toEqual('OK') + expect(clone.headers).toHaveProperty('x-powered-by', 'msw') + + // Cloned IncomingMessage must be marked respectively. + expect(clone[IS_CLONE]).toEqual(true) +}) diff --git a/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/cloneIncomingMessage.ts b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/cloneIncomingMessage.ts new file mode 100644 index 0000000000000000000000000000000000000000..35b21acf7425b45782393274fb222a0fd87999e2 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/cloneIncomingMessage.ts @@ -0,0 +1,74 @@ +import { IncomingMessage } from 'http' +import { PassThrough } from 'stream' + +export const IS_CLONE = Symbol('isClone') + +export interface ClonedIncomingMessage extends IncomingMessage { + [IS_CLONE]: boolean +} + +/** + * Clones a given `http.IncomingMessage` instance. + */ +export function cloneIncomingMessage( + message: IncomingMessage +): ClonedIncomingMessage { + const clone = message.pipe(new PassThrough()) + + // Inherit all direct "IncomingMessage" properties. + inheritProperties(message, clone) + + // Deeply inherit the message prototypes (Readable, Stream, EventEmitter, etc.). + const clonedPrototype = Object.create(IncomingMessage.prototype) + getPrototypes(clone).forEach((prototype) => { + inheritProperties(prototype, clonedPrototype) + }) + Object.setPrototypeOf(clone, clonedPrototype) + + Object.defineProperty(clone, IS_CLONE, { + enumerable: true, + value: true, + }) + + return clone as unknown as ClonedIncomingMessage +} + +/** + * Returns a list of all prototypes the given object extends. + */ +function getPrototypes(source: object): object[] { + const prototypes: object[] = [] + let current = source + + while ((current = Object.getPrototypeOf(current))) { + prototypes.push(current) + } + + return prototypes +} + +/** + * Inherits a given target object properties and symbols + * onto the given source object. + * @param source Object which should acquire properties. + * @param target Object to inherit the properties from. + */ +function inheritProperties(source: object, target: object): void { + const properties = [ + ...Object.getOwnPropertyNames(source), + ...Object.getOwnPropertySymbols(source), + ] + + for (const property of properties) { + if (target.hasOwnProperty(property)) { + continue + } + + const descriptor = Object.getOwnPropertyDescriptor(source, property) + if (!descriptor) { + continue + } + + Object.defineProperty(target, property, descriptor) + } +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/createRequest.test.ts b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/createRequest.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..452112760a121f8283c8ee5f17234b3fd2e0b1bf --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/createRequest.test.ts @@ -0,0 +1,144 @@ +import { it, expect } from 'vitest' +import { Logger } from '@open-draft/logger' +import { HttpRequestEventMap } from '../../..' +import { NodeClientRequest } from '../NodeClientRequest' +import { createRequest } from './createRequest' +import { Emitter } from 'strict-event-emitter' + +const emitter = new Emitter() +const logger = new Logger('test') + +it('creates a fetch Request with a JSON body', async () => { + const clientRequest = new NodeClientRequest( + [ + new URL('https://api.github.com'), + { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + }, + () => {}, + ], + { + emitter, + logger, + } + ) + clientRequest.write(JSON.stringify({ firstName: 'John' })) + + const request = createRequest(clientRequest) + + expect(request.method).toBe('POST') + expect(request.url).toBe('https://api.github.com/') + expect(request.headers.get('Content-Type')).toBe('application/json') + expect(await request.json()).toEqual({ firstName: 'John' }) +}) + +it('creates a fetch Request with an empty body', async () => { + const clientRequest = new NodeClientRequest( + [ + new URL('https://api.github.com'), + { + method: 'GET', + headers: { + Accept: 'application/json', + }, + }, + () => {}, + ], + { + emitter, + logger, + } + ) + + const request = createRequest(clientRequest) + + expect(request.method).toBe('GET') + expect(request.url).toBe('https://api.github.com/') + expect(request.headers.get('Accept')).toBe('application/json') + expect(request.body).toBe(null) +}) + +it('creates a fetch Request with an empty string body', async () => { + const clientRequest = new NodeClientRequest( + [ + new URL('https://api.github.com'), + { + method: 'HEAD', + }, + () => {}, + ], + { + emitter, + logger, + } + ) + clientRequest.write('') + + const request = createRequest(clientRequest) + + expect(request.method).toBe('HEAD') + expect(request.url).toBe('https://api.github.com/') + expect(request.body).toBe(null) +}) + +it('creates a fetch Request with an empty password', async () => { + const clientRequest = new NodeClientRequest( + [ + new URL('https://api.github.com'), + { auth: 'username:' }, + () => {}, + ], + { + emitter, + logger, + } + ) + clientRequest.write('') + + const request = createRequest(clientRequest) + + expect(request.headers.get('Authorization')).toBe(`Basic ${btoa('username:')}`) + expect(request.url).toBe('https://api.github.com/') +}) + +it('creates a fetch Request with an empty username', async () => { + const clientRequest = new NodeClientRequest( + [ + new URL('https://api.github.com'), + { auth: ':password' }, + () => {}, + ], + { + emitter, + logger, + } + ) + clientRequest.write('') + + const request = createRequest(clientRequest) + + expect(request.headers.get('Authorization')).toBe(`Basic ${btoa(':password')}`) + expect(request.url).toBe('https://api.github.com/') +}) + +it('creates a fetch Request with falsy headers', async () => { + const clientRequest = new NodeClientRequest( + [ + new URL('https://api.github.com'), + { headers: { 'foo': 0, 'empty': '' }} + ], + { + emitter, + logger, + } + ) + clientRequest.write('') + + const request = createRequest(clientRequest) + + expect(request.headers.get('foo')).toBe('0') + expect(request.headers.get('empty')).toBe('') +}) \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/createRequest.ts b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/createRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..1312ed9cea7f24a01944830fca8e8a604485aeb3 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/createRequest.ts @@ -0,0 +1,51 @@ +import type { NodeClientRequest } from '../NodeClientRequest' + +/** + * Creates a Fetch API `Request` instance from the given `http.ClientRequest`. + */ +export function createRequest(clientRequest: NodeClientRequest): Request { + const headers = new Headers() + + const outgoingHeaders = clientRequest.getHeaders() + for (const headerName in outgoingHeaders) { + const headerValue = outgoingHeaders[headerName] + + if (typeof headerValue === 'undefined') { + continue + } + + const valuesList = Array.prototype.concat([], headerValue) + for (const value of valuesList) { + headers.append(headerName, value.toString()) + } + } + + /** + * Translate the authentication from the request URL to + * the request "Authorization" header. + * @see https://github.com/mswjs/interceptors/issues/438 + */ + if (clientRequest.url.username || clientRequest.url.password) { + const username = decodeURIComponent(clientRequest.url.username || '') + const password = decodeURIComponent(clientRequest.url.password || '') + const auth = `${username}:${password}` + headers.set('Authorization', `Basic ${btoa(auth)}`) + + // Remove the credentials from the URL since you cannot + // construct a Request instance with such a URL. + clientRequest.url.username = '' + clientRequest.url.password = '' + } + + const method = clientRequest.method || 'GET' + + return new Request(clientRequest.url, { + method, + headers, + credentials: 'same-origin', + body: + method === 'HEAD' || method === 'GET' + ? null + : clientRequest.requestBuffer, + }) +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/createResponse.test.ts b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/createResponse.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..13bc8cfaf1444490919e2b7a645ee86102c37f2f --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/createResponse.test.ts @@ -0,0 +1,53 @@ +import { it, expect } from 'vitest' +import { Socket } from 'net' +import * as http from 'http' +import { createResponse } from './createResponse' +import { RESPONSE_STATUS_CODES_WITHOUT_BODY } from '../../../utils/responseUtils' + +it('creates a fetch api response from http incoming message', async () => { + const message = new http.IncomingMessage(new Socket()) + message.statusCode = 201 + message.statusMessage = 'Created' + message.headers['content-type'] = 'application/json' + + const response = createResponse(message) + + message.emit('data', Buffer.from('{"firstName":')) + message.emit('data', Buffer.from('"John"}')) + message.emit('end') + + expect(response.status).toBe(201) + expect(response.statusText).toBe('Created') + expect(response.headers.get('content-type')).toBe('application/json') + expect(await response.json()).toEqual({ firstName: 'John' }) +}) + +/** + * @note Ignore 1xx response status code because those cannot + * be used as the init to the "Response" constructor. + */ +const CONSTRUCTABLE_RESPONSE_STATUS_CODES = Array.from( + RESPONSE_STATUS_CODES_WITHOUT_BODY +).filter((status) => status >= 200) + +it.each(CONSTRUCTABLE_RESPONSE_STATUS_CODES)( + 'ignores message body for %i response status', + (responseStatus) => { + const message = new http.IncomingMessage(new Socket()) + message.statusCode = responseStatus + + const response = createResponse(message) + + // These chunks will be ignored: this response + // cannot have body. We don't forward this error to + // the consumer because it's us who converts the + // internal stream to a Fetch API Response instance. + // Consumers will rely on the Response API when constructing + // mocked responses. + message.emit('data', Buffer.from('hello')) + message.emit('end') + + expect(response.status).toBe(responseStatus) + expect(response.body).toBe(null) + } +) diff --git a/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/createResponse.ts b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/createResponse.ts new file mode 100644 index 0000000000000000000000000000000000000000..cf55b3c617c0e5dd3dc9fd5c5f33487a5c2c45d9 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/createResponse.ts @@ -0,0 +1,55 @@ +import type { IncomingHttpHeaders, IncomingMessage } from 'http' +import { isResponseWithoutBody } from '../../../utils/responseUtils' + +/** + * Creates a Fetch API `Response` instance from the given + * `http.IncomingMessage` instance. + */ +export function createResponse(message: IncomingMessage): Response { + const responseBodyOrNull = isResponseWithoutBody(message.statusCode || 200) + ? null + : new ReadableStream({ + start(controller) { + message.on('data', (chunk) => controller.enqueue(chunk)) + message.on('end', () => controller.close()) + + /** + * @todo Should also listen to the "error" on the message + * and forward it to the controller. Otherwise the stream + * will pend indefinitely. + */ + }, + }) + + return new Response(responseBodyOrNull, { + status: message.statusCode, + statusText: message.statusMessage, + headers: createHeadersFromIncomingHttpHeaders(message.headers), + }) +} + +function createHeadersFromIncomingHttpHeaders( + httpHeaders: IncomingHttpHeaders +): Headers { + const headers = new Headers() + + for (const headerName in httpHeaders) { + const headerValues = httpHeaders[headerName] + + if (typeof headerValues === 'undefined') { + continue + } + + if (Array.isArray(headerValues)) { + headerValues.forEach((headerValue) => { + headers.append(headerName, headerValue) + }) + + continue + } + + headers.set(headerName, headerValues) + } + + return headers +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/getIncomingMessageBody.test.ts b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/getIncomingMessageBody.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..314120c3261c418fcce24a8ac5a43c00704479a8 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/getIncomingMessageBody.test.ts @@ -0,0 +1,54 @@ +import { it, expect } from 'vitest' +import { IncomingMessage } from 'http' +import { Socket } from 'net' +import * as zlib from 'zlib' +import { getIncomingMessageBody } from './getIncomingMessageBody' + +it('returns utf8 string given a utf8 response body', async () => { + const utfBuffer = Buffer.from('one') + const message = new IncomingMessage(new Socket()) + + const pendingResponseBody = getIncomingMessageBody(message) + message.emit('data', utfBuffer) + message.emit('end') + + expect(await pendingResponseBody).toEqual('one') +}) + +it('returns utf8 string given a gzipped response body', async () => { + const utfBuffer = zlib.gzipSync(Buffer.from('two')) + const message = new IncomingMessage(new Socket()) + message.headers = { + 'content-encoding': 'gzip', + } + + const pendingResponseBody = getIncomingMessageBody(message) + message.emit('data', utfBuffer) + message.emit('end') + + expect(await pendingResponseBody).toEqual('two') +}) + +it('returns utf8 string given a gzipped response body with incorrect "content-lenght"', async () => { + const utfBuffer = zlib.gzipSync(Buffer.from('three')) + const message = new IncomingMessage(new Socket()) + message.headers = { + 'content-encoding': 'gzip', + 'content-length': '500', + } + + const pendingResponseBody = getIncomingMessageBody(message) + message.emit('data', utfBuffer) + message.emit('end') + + expect(await pendingResponseBody).toEqual('three') +}) + +it('returns empty string given an empty body', async () => { + const message = new IncomingMessage(new Socket()) + + const pendingResponseBody = getIncomingMessageBody(message) + message.emit('end') + + expect(await pendingResponseBody).toEqual('') +}) diff --git a/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/getIncomingMessageBody.ts b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/getIncomingMessageBody.ts new file mode 100644 index 0000000000000000000000000000000000000000..563e55259706b93213f1232e8e1165256cb58ca3 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/getIncomingMessageBody.ts @@ -0,0 +1,45 @@ +import { IncomingMessage } from 'http' +import { PassThrough } from 'stream' +import * as zlib from 'zlib' +import { Logger } from '@open-draft/logger' + +const logger = new Logger('http getIncomingMessageBody') + +export function getIncomingMessageBody( + response: IncomingMessage +): Promise { + return new Promise((resolve, reject) => { + logger.info('cloning the original response...') + + // Pipe the original response to support non-clone + // "response" input. No need to clone the response, + // as we always have access to the full "response" input, + // either a clone or an original one (in tests). + const responseClone = response.pipe(new PassThrough()) + const stream = + response.headers['content-encoding'] === 'gzip' + ? responseClone.pipe(zlib.createGunzip()) + : responseClone + + const encoding = response.readableEncoding || 'utf8' + stream.setEncoding(encoding) + logger.info('using encoding:', encoding) + + let body = '' + + stream.on('data', (responseBody) => { + logger.info('response body read:', responseBody) + body += responseBody + }) + + stream.once('end', () => { + logger.info('response body end') + resolve(body) + }) + + stream.once('error', (error) => { + logger.info('error while reading response body:', error) + reject(error) + }) + }) +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.test.ts b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..c5bef850cdde9fcaaea178f899f661737816e8d6 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.test.ts @@ -0,0 +1,469 @@ +import { it, expect } from 'vitest' +import { parse } from 'url' +import { globalAgent as httpGlobalAgent, RequestOptions } from 'http' +import { Agent as HttpsAgent, globalAgent as httpsGlobalAgent } from 'https' +import { getUrlByRequestOptions } from '../../../utils/getUrlByRequestOptions' +import { normalizeClientRequestArgs } from './normalizeClientRequestArgs' + +it('handles [string, callback] input', () => { + const [url, options, callback] = normalizeClientRequestArgs( + 'https:', + 'https://mswjs.io/resource', + function cb() {} + ) + + // URL string must be converted to a URL instance. + expect(url.href).toEqual('https://mswjs.io/resource') + + // Request options must be derived from the URL instance. + expect(options).toHaveProperty('method', 'GET') + expect(options).toHaveProperty('protocol', 'https:') + expect(options).toHaveProperty('hostname', 'mswjs.io') + expect(options).toHaveProperty('path', '/resource') + + // Callback must be preserved. + expect(callback?.name).toEqual('cb') +}) + +it('handles [string, RequestOptions, callback] input', () => { + const initialOptions = { + headers: { + 'Content-Type': 'text/plain', + }, + } + const [url, options, callback] = normalizeClientRequestArgs( + 'https:', + 'https://mswjs.io/resource', + initialOptions, + function cb() {} + ) + + // URL must be created from the string. + expect(url.href).toEqual('https://mswjs.io/resource') + + // Request options must be preserved. + expect(options).toHaveProperty('headers', initialOptions.headers) + + // Callback must be preserved. + expect(callback?.name).toEqual('cb') +}) + +it('handles [URL, callback] input', () => { + const [url, options, callback] = normalizeClientRequestArgs( + 'https:', + new URL('https://mswjs.io/resource'), + function cb() {} + ) + + // URL must be preserved. + expect(url.href).toEqual('https://mswjs.io/resource') + + // Request options must be derived from the URL instance. + expect(options.method).toEqual('GET') + expect(options.protocol).toEqual('https:') + expect(options.hostname).toEqual('mswjs.io') + expect(options.path).toEqual('/resource') + + // Callback must be preserved. + expect(callback?.name).toEqual('cb') +}) + +it('handles [Absolute Legacy URL, callback] input', () => { + const [url, options, callback] = normalizeClientRequestArgs( + 'https:', + parse('https://cherry:durian@mswjs.io:12345/resource?apple=banana'), + function cb() {} + ) + + // URL must be preserved. + expect(url.toJSON()).toEqual( + new URL( + 'https://cherry:durian@mswjs.io:12345/resource?apple=banana' + ).toJSON() + ) + + // Request options must be derived from the URL instance. + expect(options.method).toEqual('GET') + expect(options.protocol).toEqual('https:') + expect(options.hostname).toEqual('mswjs.io') + expect(options.path).toEqual('/resource?apple=banana') + expect(options.port).toEqual(12345) + expect(options.auth).toEqual('cherry:durian') + + // Callback must be preserved. + expect(callback?.name).toEqual('cb') +}) + +it('handles [Relative Legacy URL, RequestOptions without path set, callback] input', () => { + const [url, options, callback] = normalizeClientRequestArgs( + 'http:', + parse('/resource?apple=banana'), + { host: 'mswjs.io' }, + function cb() {} + ) + + // Correct WHATWG URL generated. + expect(url.toJSON()).toEqual( + new URL('http://mswjs.io/resource?apple=banana').toJSON() + ) + + // No path in request options, so legacy url path is copied-in. + expect(options.protocol).toEqual('http:') + expect(options.host).toEqual('mswjs.io') + expect(options.path).toEqual('/resource?apple=banana') + + // Callback must be preserved. + expect(callback?.name).toEqual('cb') +}) + +it('handles [Relative Legacy URL, RequestOptions with path set, callback] input', () => { + const [url, options, callback] = normalizeClientRequestArgs( + 'http:', + parse('/resource?apple=banana'), + { host: 'mswjs.io', path: '/other?cherry=durian' }, + function cb() {} + ) + + // Correct WHATWG URL generated. + expect(url.toJSON()).toEqual( + new URL('http://mswjs.io/other?cherry=durian').toJSON() + ) + + // Path in request options, so that path is preferred. + expect(options.protocol).toEqual('http:') + expect(options.host).toEqual('mswjs.io') + expect(options.path).toEqual('/other?cherry=durian') + + // Callback must be preserved. + expect(callback?.name).toEqual('cb') +}) + +it('handles [Relative Legacy URL, callback] input', () => { + const [url, options, callback] = normalizeClientRequestArgs( + 'http:', + parse('/resource?apple=banana'), + function cb() {} + ) + + // Correct WHATWG URL generated. + expect(url.toJSON()).toMatch( + getUrlByRequestOptions({ path: '/resource?apple=banana' }).toJSON() + ) + + // Check path is in options. + expect(options.protocol).toEqual('http:') + expect(options.path).toEqual('/resource?apple=banana') + + // Callback must be preserved. + expect(callback?.name).toEqual('cb') +}) + +it('handles [Relative Legacy URL] input', () => { + const [url, options, callback] = normalizeClientRequestArgs( + 'http:', + parse('/resource?apple=banana') + ) + + // Correct WHATWG URL generated. + expect(url.toJSON()).toMatch( + getUrlByRequestOptions({ path: '/resource?apple=banana' }).toJSON() + ) + + // Check path is in options. + expect(options.protocol).toEqual('http:') + expect(options.path).toEqual('/resource?apple=banana') + + // Callback must be preserved. + expect(callback).toBeUndefined() +}) + +it('handles [URL, RequestOptions, callback] input', () => { + const [url, options, callback] = normalizeClientRequestArgs( + 'https:', + new URL('https://mswjs.io/resource'), + { + agent: false, + headers: { + 'Content-Type': 'text/plain', + }, + }, + function cb() {} + ) + + // URL must be preserved. + expect(url.href).toEqual('https://mswjs.io/resource') + + // Options must be preserved. + expect(options).toEqual({ + agent: false, + _defaultAgent: httpsGlobalAgent, + protocol: url.protocol, + method: 'GET', + headers: { + 'Content-Type': 'text/plain', + }, + + host: url.host, + hostname: url.hostname, + path: url.pathname, + }) + + // Callback must be preserved. + expect(callback?.name).toEqual('cb') +}) + +it('handles [URL, RequestOptions] where options have custom "hostname"', () => { + const [url, options] = normalizeClientRequestArgs( + 'http:', + new URL('http://example.com/path-from-url'), + { + hostname: 'host-from-options.com', + } + ) + expect(url.href).toBe('http://host-from-options.com/path-from-url') + expect(options).toMatchObject({ + host: 'host-from-options.com', + path: '/path-from-url', + }) +}) + +it('handles [URL, RequestOptions] where options contain "host" and "path" and "port"', () => { + const [url, options] = normalizeClientRequestArgs( + 'http:', + new URL('http://example.com/path-from-url?a=b&c=d'), + { + hostname: 'host-from-options.com', + path: '/path-from-options', + port: 1234, + } + ) + // Must remove the query string since it's not specified in "options.path" + expect(url.href).toBe('http://host-from-options.com:1234/path-from-options') + expect(options).toMatchObject({ + host: 'host-from-options.com:1234', + path: '/path-from-options', + port: 1234, + }) +}) + +it('handles [URL, RequestOptions] where options contain "path" with query string', () => { + const [url, options] = normalizeClientRequestArgs( + 'http:', + new URL('http://example.com/path-from-url?a=b&c=d'), + { + path: '/path-from-options?foo=bar&baz=xyz', + } + ) + expect(url.href).toBe('http://example.com/path-from-options?foo=bar&baz=xyz') + expect(options).toMatchObject({ + host: 'example.com', + path: '/path-from-options?foo=bar&baz=xyz', + }) +}) + +it('handles [RequestOptions, callback] input', () => { + const initialOptions = { + method: 'POST', + protocol: 'https:', + host: 'mswjs.io', + /** + * @see https://github.com/mswjs/msw/issues/705 + */ + origin: 'https://mswjs.io', + path: '/resource', + headers: { + 'Content-Type': 'text/plain', + }, + } + const [url, options, callback] = normalizeClientRequestArgs( + 'https:', + initialOptions, + function cb() {} + ) + + // URL must be derived from request options. + expect(url.href).toEqual('https://mswjs.io/resource') + + // Request options must be preserved. + expect(options).toEqual(initialOptions) + + // Callback must be preserved. + expect(callback?.name).toEqual('cb') +}) + +it('handles [Empty RequestOptions, callback] input', () => { + const [_, options, callback] = normalizeClientRequestArgs( + 'https:', + {}, + function cb() {} + ) + + expect(options.protocol).toEqual('https:') + + // Callback must be preserved + expect(callback?.name).toEqual('cb') +}) + +/** + * @see https://github.com/mswjs/interceptors/issues/19 + */ +it('handles [PartialRequestOptions, callback] input', () => { + const initialOptions = { + method: 'GET', + port: '50176', + path: '/resource', + host: '127.0.0.1', + ca: undefined, + key: undefined, + pfx: undefined, + cert: undefined, + passphrase: undefined, + agent: false, + } + const [url, options, callback] = normalizeClientRequestArgs( + 'https:', + initialOptions, + function cb() {} + ) + + // URL must be derived from request options. + expect(url.toJSON()).toEqual( + new URL('https://127.0.0.1:50176/resource').toJSON() + ) + + // Request options must be preserved. + expect(options).toEqual(initialOptions) + + // Options protocol must be inferred from the request issuing module. + expect(options.protocol).toEqual('https:') + + // Callback must be preserved. + expect(callback?.name).toEqual('cb') +}) + +it('sets fallback Agent based on the URL protocol', () => { + const [url, options] = normalizeClientRequestArgs( + 'https:', + 'https://github.com' + ) + const agent = options.agent as HttpsAgent + + expect(agent).toBeInstanceOf(HttpsAgent) + expect(agent).toHaveProperty('defaultPort', 443) + expect(agent).toHaveProperty('protocol', url.protocol) +}) + +it('does not set any fallback Agent given "agent: false" option', () => { + const [, options] = normalizeClientRequestArgs( + 'https:', + 'https://github.com', + { agent: false } + ) + + expect(options.agent).toEqual(false) +}) + +it('sets the default Agent for HTTP request', () => { + const [, options] = normalizeClientRequestArgs( + 'http:', + 'http://github.com', + {} + ) + + expect(options._defaultAgent).toEqual(httpGlobalAgent) +}) + +it('sets the default Agent for HTTPS request', () => { + const [, options] = normalizeClientRequestArgs( + 'https:', + 'https://github.com', + {} + ) + + expect(options._defaultAgent).toEqual(httpsGlobalAgent) +}) + +it('preserves a custom default Agent when set', () => { + const [, options] = normalizeClientRequestArgs( + 'https:', + 'https://github.com', + { + /** + * @note Intentionally incorrect Agent for HTTPS request. + */ + _defaultAgent: httpGlobalAgent, + } + ) + + expect(options._defaultAgent).toEqual(httpGlobalAgent) +}) + +it('merges URL-based RequestOptions with the custom RequestOptions', () => { + const [url, options] = normalizeClientRequestArgs( + 'https:', + 'https://github.com/graphql', + { + method: 'GET', + pfx: 'PFX_KEY', + } + ) + + expect(url.href).toEqual('https://github.com/graphql') + + // Original request options must be preserved. + expect(options.method).toEqual('GET') + expect(options.pfx).toEqual('PFX_KEY') + + // Other options must be inferred from the URL. + expect(options.protocol).toEqual(url.protocol) + expect(options.host).toEqual(url.host) + expect(options.hostname).toEqual(url.hostname) + expect(options.path).toEqual(url.pathname) +}) + +it('respects custom "options.path" over URL path', () => { + const [url, options] = normalizeClientRequestArgs( + 'http:', + new URL('http://example.com/path-from-url'), + { + path: '/path-from-options', + } + ) + + expect(url.href).toBe('http://example.com/path-from-options') + expect(options.protocol).toBe('http:') + expect(options.host).toBe('example.com') + expect(options.hostname).toBe('example.com') + expect(options.path).toBe('/path-from-options') +}) + +it('respects custom "options.path" over URL path with query string', () => { + const [url, options] = normalizeClientRequestArgs( + 'http:', + new URL('http://example.com/path-from-url?a=b&c=d'), + { + path: '/path-from-options', + } + ) + + // Must replace both the path and the query string. + expect(url.href).toBe('http://example.com/path-from-options') + expect(options.protocol).toBe('http:') + expect(options.host).toBe('example.com') + expect(options.hostname).toBe('example.com') + expect(options.path).toBe('/path-from-options') +}) + +it('preserves URL query string', () => { + const [url, options] = normalizeClientRequestArgs( + 'http:', + new URL('http://example.com/resource?a=b&c=d') + ) + + expect(url.href).toBe('http://example.com/resource?a=b&c=d') + expect(options.protocol).toBe('http:') + expect(options.host).toBe('example.com') + expect(options.hostname).toBe('example.com') + // Query string is a part of the options path. + expect(options.path).toBe('/resource?a=b&c=d') +}) diff --git a/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.ts b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.ts new file mode 100644 index 0000000000000000000000000000000000000000..cba58ebe452b89d34648f02698e8bc1c3c479b1a --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.ts @@ -0,0 +1,270 @@ +import { + Agent as HttpAgent, + globalAgent as httpGlobalAgent, + IncomingMessage, +} from 'http' +import { + RequestOptions, + Agent as HttpsAgent, + globalAgent as httpsGlobalAgent, +} from 'https' +import { Url as LegacyURL, parse as parseUrl } from 'url' +import { Logger } from '@open-draft/logger' +import { getRequestOptionsByUrl } from '../../../utils/getRequestOptionsByUrl' +import { + ResolvedRequestOptions, + getUrlByRequestOptions, +} from '../../../utils/getUrlByRequestOptions' +import { cloneObject } from '../../../utils/cloneObject' +import { isObject } from '../../../utils/isObject' + +const logger = new Logger('http normalizeClientRequestArgs') + +export type HttpRequestCallback = (response: IncomingMessage) => void + +export type ClientRequestArgs = + // Request without any arguments is also possible. + | [] + | [string | URL | LegacyURL, HttpRequestCallback?] + | [string | URL | LegacyURL, RequestOptions, HttpRequestCallback?] + | [RequestOptions, HttpRequestCallback?] + +function resolveRequestOptions( + args: ClientRequestArgs, + url: URL +): RequestOptions { + // Calling `fetch` provides only URL to `ClientRequest` + // without any `RequestOptions` or callback. + if (typeof args[1] === 'undefined' || typeof args[1] === 'function') { + logger.info('request options not provided, deriving from the url', url) + return getRequestOptionsByUrl(url) + } + + if (args[1]) { + logger.info('has custom RequestOptions!', args[1]) + const requestOptionsFromUrl = getRequestOptionsByUrl(url) + + logger.info('derived RequestOptions from the URL:', requestOptionsFromUrl) + + /** + * Clone the request options to lock their state + * at the moment they are provided to `ClientRequest`. + * @see https://github.com/mswjs/interceptors/issues/86 + */ + logger.info('cloning RequestOptions...') + const clonedRequestOptions = cloneObject(args[1]) + logger.info('successfully cloned RequestOptions!', clonedRequestOptions) + + return { + ...requestOptionsFromUrl, + ...clonedRequestOptions, + } + } + + logger.info('using an empty object as request options') + return {} as RequestOptions +} + +/** + * Overrides the given `URL` instance with the explicit properties provided + * on the `RequestOptions` object. The options object takes precedence, + * and will replace URL properties like "host", "path", and "port", if specified. + */ +function overrideUrlByRequestOptions(url: URL, options: RequestOptions): URL { + url.host = options.host || url.host + url.hostname = options.hostname || url.hostname + url.port = options.port ? options.port.toString() : url.port + + if (options.path) { + const parsedOptionsPath = parseUrl(options.path, false) + url.pathname = parsedOptionsPath.pathname || '' + url.search = parsedOptionsPath.search || '' + } + + return url +} + +function resolveCallback( + args: ClientRequestArgs +): HttpRequestCallback | undefined { + return typeof args[1] === 'function' ? args[1] : args[2] +} + +export type NormalizedClientRequestArgs = [ + url: URL, + options: ResolvedRequestOptions, + callback?: HttpRequestCallback +] + +/** + * Normalizes parameters given to a `http.request` call + * so it always has a `URL` and `RequestOptions`. + */ +export function normalizeClientRequestArgs( + defaultProtocol: string, + ...args: ClientRequestArgs +): NormalizedClientRequestArgs { + let url: URL + let options: ResolvedRequestOptions + let callback: HttpRequestCallback | undefined + + logger.info('arguments', args) + logger.info('using default protocol:', defaultProtocol) + + // Support "http.request()" calls without any arguments. + // That call results in a "GET http://localhost" request. + if (args.length === 0) { + const url = new URL('http://localhost') + const options = resolveRequestOptions(args, url) + return [url, options] + } + + // Convert a url string into a URL instance + // and derive request options from it. + if (typeof args[0] === 'string') { + logger.info('first argument is a location string:', args[0]) + + url = new URL(args[0]) + logger.info('created a url:', url) + + const requestOptionsFromUrl = getRequestOptionsByUrl(url) + logger.info('request options from url:', requestOptionsFromUrl) + + options = resolveRequestOptions(args, url) + logger.info('resolved request options:', options) + + callback = resolveCallback(args) + } + // Handle a given URL instance as-is + // and derive request options from it. + else if (args[0] instanceof URL) { + url = args[0] + logger.info('first argument is a URL:', url) + + // Check if the second provided argument is RequestOptions. + // If it is, check if "options.path" was set and rewrite it + // on the input URL. + // Do this before resolving options from the URL below + // to prevent query string from being duplicated in the path. + if (typeof args[1] !== 'undefined' && isObject(args[1])) { + url = overrideUrlByRequestOptions(url, args[1]) + } + + options = resolveRequestOptions(args, url) + logger.info('derived request options:', options) + + callback = resolveCallback(args) + } + // Handle a legacy URL instance and re-normalize from either a RequestOptions object + // or a WHATWG URL. + else if ('hash' in args[0] && !('method' in args[0])) { + const [legacyUrl] = args + logger.info('first argument is a legacy URL:', legacyUrl) + + if (legacyUrl.hostname === null) { + /** + * We are dealing with a relative url, so use the path as an "option" and + * merge in any existing options, giving priority to exising options -- i.e. a path in any + * existing options will take precedence over the one contained in the url. This is consistent + * with the behaviour in ClientRequest. + * @see https://github.com/nodejs/node/blob/d84f1312915fe45fe0febe888db692c74894c382/lib/_http_client.js#L122 + */ + logger.info('given legacy URL is relative (no hostname)') + + return isObject(args[1]) + ? normalizeClientRequestArgs( + defaultProtocol, + { path: legacyUrl.path, ...args[1] }, + args[2] + ) + : normalizeClientRequestArgs( + defaultProtocol, + { path: legacyUrl.path }, + args[1] as HttpRequestCallback + ) + } + + logger.info('given legacy url is absolute') + + // We are dealing with an absolute URL, so convert to WHATWG and try again. + const resolvedUrl = new URL(legacyUrl.href) + + return args[1] === undefined + ? normalizeClientRequestArgs(defaultProtocol, resolvedUrl) + : typeof args[1] === 'function' + ? normalizeClientRequestArgs(defaultProtocol, resolvedUrl, args[1]) + : normalizeClientRequestArgs( + defaultProtocol, + resolvedUrl, + args[1], + args[2] + ) + } + // Handle a given "RequestOptions" object as-is + // and derive the URL instance from it. + else if (isObject(args[0])) { + options = args[0] as any + logger.info('first argument is RequestOptions:', options) + + // When handling a "RequestOptions" object without an explicit "protocol", + // infer the protocol from the request issuing module (http/https). + options.protocol = options.protocol || defaultProtocol + logger.info('normalized request options:', options) + + url = getUrlByRequestOptions(options) + logger.info('created a URL from RequestOptions:', url.href) + + callback = resolveCallback(args) + } else { + throw new Error( + `Failed to construct ClientRequest with these parameters: ${args}` + ) + } + + options.protocol = options.protocol || url.protocol + options.method = options.method || 'GET' + + /** + * Infer a fallback agent from the URL protocol. + * The interception is done on the "ClientRequest" level ("NodeClientRequest") + * and it may miss the correct agent. Always align the agent + * with the URL protocol, if not provided. + * + * @note Respect the "agent: false" value. + */ + if (typeof options.agent === 'undefined') { + const agent = + options.protocol === 'https:' + ? new HttpsAgent({ + rejectUnauthorized: options.rejectUnauthorized, + }) + : new HttpAgent() + + options.agent = agent + logger.info('resolved fallback agent:', agent) + } + + /** + * Ensure that the default Agent is always set. + * This prevents the protocol mismatch for requests with { agent: false }, + * where the global Agent is inferred. + * @see https://github.com/mswjs/msw/issues/1150 + * @see https://github.com/nodejs/node/blob/418ff70b810f0e7112d48baaa72932a56cfa213b/lib/_http_client.js#L130 + * @see https://github.com/nodejs/node/blob/418ff70b810f0e7112d48baaa72932a56cfa213b/lib/_http_client.js#L157-L159 + */ + if (!options._defaultAgent) { + logger.info( + 'has no default agent, setting the default agent for "%s"', + options.protocol + ) + + options._defaultAgent = + options.protocol === 'https:' ? httpsGlobalAgent : httpGlobalAgent + } + + logger.info('successfully resolved url:', url.href) + logger.info('successfully resolved options:', options) + logger.info('successfully resolved callback:', callback) + + return [url, options, callback] +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/normalizeClientRequestEndArgs.test.ts b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/normalizeClientRequestEndArgs.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..63f0bb5614e8c13f79b5eae56a01c56da80b796c --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/normalizeClientRequestEndArgs.test.ts @@ -0,0 +1,41 @@ +import { it, expect } from 'vitest' +import { normalizeClientRequestEndArgs } from './normalizeClientRequestEndArgs' + +it('returns [null, null, cb] given only the callback', () => { + const callback = () => {} + expect(normalizeClientRequestEndArgs(callback)).toEqual([ + null, + null, + callback, + ]) +}) + +it('returns [chunk, null, null] given only the chunk', () => { + expect(normalizeClientRequestEndArgs('chunk')).toEqual(['chunk', null, null]) +}) + +it('returns [chunk, cb] given the chunk and the callback', () => { + const callback = () => {} + expect(normalizeClientRequestEndArgs('chunk', callback)).toEqual([ + 'chunk', + null, + callback, + ]) +}) + +it('returns [chunk, encoding] given the chunk with the encoding', () => { + expect(normalizeClientRequestEndArgs('chunk', 'utf8')).toEqual([ + 'chunk', + 'utf8', + null, + ]) +}) + +it('returns [chunk, encoding, cb] given all three arguments', () => { + const callback = () => {} + expect(normalizeClientRequestEndArgs('chunk', 'utf8', callback)).toEqual([ + 'chunk', + 'utf8', + callback, + ]) +}) diff --git a/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/normalizeClientRequestEndArgs.ts b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/normalizeClientRequestEndArgs.ts new file mode 100644 index 0000000000000000000000000000000000000000..137b15d5ad94b09d3b3c9bfc2a4aac084f65e3a8 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/normalizeClientRequestEndArgs.ts @@ -0,0 +1,53 @@ +import { Logger } from '@open-draft/logger' + +const logger = new Logger('utils getUrlByRequestOptions') + +export type ClientRequestEndChunk = string | Buffer +export type ClientRequestEndCallback = () => void + +type HttpRequestEndArgs = + | [] + | [ClientRequestEndCallback] + | [ClientRequestEndChunk, ClientRequestEndCallback?] + | [ClientRequestEndChunk, BufferEncoding, ClientRequestEndCallback?] + +type NormalizedHttpRequestEndParams = [ + ClientRequestEndChunk | null, + BufferEncoding | null, + ClientRequestEndCallback | null +] + +/** + * Normalizes a list of arguments given to the `ClientRequest.end()` + * method to always include `chunk`, `encoding`, and `callback`. + */ +export function normalizeClientRequestEndArgs( + ...args: HttpRequestEndArgs +): NormalizedHttpRequestEndParams { + logger.info('arguments', args) + const normalizedArgs = new Array(3) + .fill(null) + .map((value, index) => args[index] || value) + + normalizedArgs.sort((a, b) => { + // If first element is a function, move it rightwards. + if (typeof a === 'function') { + return 1 + } + + // If second element is a function, move the first leftwards. + if (typeof b === 'function') { + return -1 + } + + // If both elements are strings, preserve their original index. + if (typeof a === 'string' && typeof b === 'string') { + return normalizedArgs.indexOf(a) - normalizedArgs.indexOf(b) + } + + return 0 + }) + + logger.info('normalized args', normalizedArgs) + return normalizedArgs as NormalizedHttpRequestEndParams +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/normalizeClientRequestWriteArgs.test.ts b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/normalizeClientRequestWriteArgs.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..00e7cd3db6ddbf469abee7d02fdfd632cb42c58a --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/normalizeClientRequestWriteArgs.test.ts @@ -0,0 +1,36 @@ +import { it, expect } from 'vitest' +import { normalizeClientRequestWriteArgs } from './normalizeClientRequestWriteArgs' + +it('returns a triplet of null given no chunk, encoding, or callback', () => { + expect( + normalizeClientRequestWriteArgs([ + // @ts-ignore + undefined, + undefined, + undefined, + ]) + ).toEqual([undefined, undefined, undefined]) +}) + +it('returns [chunk, null, null] given only a chunk', () => { + expect(normalizeClientRequestWriteArgs(['chunk', undefined])).toEqual([ + 'chunk', + undefined, + undefined, + ]) +}) + +it('returns [chunk, encoding] given only chunk and encoding', () => { + expect(normalizeClientRequestWriteArgs(['chunk', 'utf8'])).toEqual([ + 'chunk', + 'utf8', + undefined, + ]) +}) + +it('returns [chunk, encoding, cb] given all three arguments', () => { + const callbackFn = () => {} + expect( + normalizeClientRequestWriteArgs(['chunk', 'utf8', callbackFn]) + ).toEqual(['chunk', 'utf8', callbackFn]) +}) diff --git a/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/normalizeClientRequestWriteArgs.ts b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/normalizeClientRequestWriteArgs.ts new file mode 100644 index 0000000000000000000000000000000000000000..0fee9aaa09996dffb232e2cf0fb534e5eebeb5a9 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/normalizeClientRequestWriteArgs.ts @@ -0,0 +1,39 @@ +import { Logger } from '@open-draft/logger' + +const logger = new Logger('http normalizeWriteArgs') + +export type ClientRequestWriteCallback = (error?: Error | null) => void +export type ClientRequestWriteArgs = [ + chunk: string | Buffer, + encoding?: BufferEncoding | ClientRequestWriteCallback, + callback?: ClientRequestWriteCallback +] + +export type NormalizedClientRequestWriteArgs = [ + chunk: string | Buffer, + encoding?: BufferEncoding, + callback?: ClientRequestWriteCallback +] + +export function normalizeClientRequestWriteArgs( + args: ClientRequestWriteArgs +): NormalizedClientRequestWriteArgs { + logger.info('normalizing ClientRequest.write arguments...', args) + + const chunk = args[0] + const encoding = + typeof args[1] === 'string' ? (args[1] as BufferEncoding) : undefined + const callback = typeof args[1] === 'function' ? args[1] : args[2] + + const writeArgs: NormalizedClientRequestWriteArgs = [ + chunk, + encoding, + callback, + ] + logger.info( + 'successfully normalized ClientRequest.write arguments:', + writeArgs + ) + + return writeArgs +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketClassTransport.ts b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketClassTransport.ts new file mode 100644 index 0000000000000000000000000000000000000000..a0b3b196c9a5dd622fc85ecd4c476c7e398f9d44 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketClassTransport.ts @@ -0,0 +1,95 @@ +import { bindEvent } from './utils/bindEvent' +import { + StrictEventListenerOrEventListenerObject, + WebSocketData, + WebSocketTransport, + WebSocketTransportEventMap, +} from './WebSocketTransport' +import { kOnSend, kClose, WebSocketOverride } from './WebSocketOverride' +import { CancelableMessageEvent, CloseEvent } from './utils/events' + +/** + * Abstraction over the given mock `WebSocket` instance that allows + * for controlling that instance (e.g. sending and receiving messages). + */ +export class WebSocketClassTransport + extends EventTarget + implements WebSocketTransport +{ + constructor(protected readonly socket: WebSocketOverride) { + super() + + // Emit the "close" event on the transport if the close + // originates from the WebSocket client. E.g. the application + // calls "ws.close()", not the interceptor. + this.socket.addEventListener('close', (event) => { + this.dispatchEvent(bindEvent(this.socket, new CloseEvent('close', event))) + }) + + /** + * Emit the "outgoing" event on the transport + * whenever the WebSocket client sends data ("ws.send()"). + */ + this.socket[kOnSend] = (data) => { + this.dispatchEvent( + bindEvent( + this.socket, + // Dispatch this as cancelable because "client" connection + // re-creates this message event (cannot dispatch the same event). + new CancelableMessageEvent('outgoing', { + data, + origin: this.socket.url, + cancelable: true, + }) + ) + ) + } + } + + public addEventListener( + type: EventType, + callback: StrictEventListenerOrEventListenerObject< + WebSocketTransportEventMap[EventType] + > | null, + options?: boolean | AddEventListenerOptions + ): void { + return super.addEventListener(type, callback as EventListener, options) + } + + public dispatchEvent( + event: WebSocketTransportEventMap[EventType] + ): boolean { + return super.dispatchEvent(event) + } + + public send(data: WebSocketData): void { + queueMicrotask(() => { + this.socket.dispatchEvent( + bindEvent( + /** + * @note Setting this event's "target" to the + * WebSocket override instance is important. + * This way it can tell apart original incoming events + * (must be forwarded to the transport) from the + * mocked message events like the one below + * (must be dispatched on the client instance). + */ + this.socket, + new MessageEvent('message', { + data, + origin: this.socket.url, + }) + ) + ) + }) + } + + public close(code: number, reason?: string): void { + /** + * @note Call the internal close method directly + * to allow closing the connection with the status codes + * that are non-configurable by the user (> 1000 <= 1015). + */ + this.socket[kClose](code, reason) + } +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketClientConnection.ts b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketClientConnection.ts new file mode 100644 index 0000000000000000000000000000000000000000..3f5e4b6148f845fdc74814e6544dd2c9d6c39ef3 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketClientConnection.ts @@ -0,0 +1,135 @@ +import type { WebSocketData, WebSocketTransport } from './WebSocketTransport' +import type { WebSocketEventListener } from './WebSocketOverride' +import { bindEvent } from './utils/bindEvent' +import { CancelableMessageEvent, CloseEvent } from './utils/events' +import { createRequestId } from '../../createRequestId' + +const kEmitter = Symbol('kEmitter') +const kBoundListener = Symbol('kBoundListener') + +interface WebSocketClientEventMap { + message: MessageEvent + close: CloseEvent +} + +export interface WebSocketClientConnectionProtocol { + id: string + url: URL + send(data: WebSocketData): void + close(code?: number, reason?: string): void +} + +/** + * The WebSocket client instance represents an incoming + * client connection. The user can control the connection, + * send and receive events. + */ +export class WebSocketClientConnection + implements WebSocketClientConnectionProtocol +{ + public readonly id: string + public readonly url: URL + + private [kEmitter]: EventTarget + + constructor( + public readonly socket: WebSocket, + private readonly transport: WebSocketTransport + ) { + this.id = createRequestId() + this.url = new URL(socket.url) + this[kEmitter] = new EventTarget() + + // Emit outgoing client data ("ws.send()") as "message" + // events on the "client" connection. + this.transport.addEventListener('outgoing', (event) => { + const message = bindEvent( + this.socket, + new CancelableMessageEvent('message', { + data: event.data, + origin: event.origin, + cancelable: true, + }) + ) + + this[kEmitter].dispatchEvent(message) + + // This is a bit silly but forward the cancellation state + // of the "client" message event to the "outgoing" transport event. + // This way, other agens (like "server" connection) can know + // whether the client listener has pervented the default. + if (message.defaultPrevented) { + event.preventDefault() + } + }) + + /** + * Emit the "close" event on the "client" connection + * whenever the underlying transport is closed. + * @note "client.close()" does NOT dispatch the "close" + * event on the WebSocket because it uses non-configurable + * close status code. Thus, we listen to the transport + * instead of the WebSocket's "close" event. + */ + this.transport.addEventListener('close', (event) => { + this[kEmitter].dispatchEvent( + bindEvent(this.socket, new CloseEvent('close', event)) + ) + }) + } + + /** + * Listen for the outgoing events from the connected WebSocket client. + */ + public addEventListener( + type: EventType, + listener: WebSocketEventListener, + options?: AddEventListenerOptions | boolean + ): void { + const boundListener = listener.bind(this.socket) + + // Store the bound listener on the original listener + // so the exact bound function can be accessed in "removeEventListener()". + Object.defineProperty(listener, kBoundListener, { + value: boundListener, + enumerable: false, + }) + + this[kEmitter].addEventListener( + type, + boundListener as EventListener, + options + ) + } + + /** + * Removes the listener for the given event. + */ + public removeEventListener( + event: EventType, + listener: WebSocketEventListener, + options?: EventListenerOptions | boolean + ): void { + this[kEmitter].removeEventListener( + event, + Reflect.get(listener, kBoundListener) as EventListener, + options + ) + } + + /** + * Send data to the connected client. + */ + public send(data: WebSocketData): void { + this.transport.send(data) + } + + /** + * Close the WebSocket connection. + * @param {number} code A status code (see https://www.rfc-editor.org/rfc/rfc6455#section-7.4.1). + * @param {string} reason A custom connection close reason. + */ + public close(code?: number, reason?: string): void { + this.transport.close(code, reason) + } +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketOverride.ts b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketOverride.ts new file mode 100644 index 0000000000000000000000000000000000000000..56871a6cce1164fc250f785907d13d1d32893750 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketOverride.ts @@ -0,0 +1,229 @@ +import { invariant } from 'outvariant' +import type { WebSocketData } from './WebSocketTransport' +import { bindEvent } from './utils/bindEvent' +import { CloseEvent } from './utils/events' + +export type WebSocketEventListener< + EventType extends WebSocketEventMap[keyof WebSocketEventMap] = Event +> = (this: WebSocket, event: EventType) => void + +const WEBSOCKET_CLOSE_CODE_RANGE_ERROR = + 'InvalidAccessError: close code out of user configurable range' + +export const kOnSend = Symbol('kOnSend') +export const kClose = Symbol('kClose') + +export class WebSocketOverride extends EventTarget implements WebSocket { + static readonly CONNECTING = 0 + static readonly OPEN = 1 + static readonly CLOSING = 2 + static readonly CLOSED = 3 + readonly CONNECTING = 0 + readonly OPEN = 1 + readonly CLOSING = 2 + readonly CLOSED = 3 + + public url: string + public protocol: string + public extensions: string + public binaryType: BinaryType + public readyState: number + public bufferedAmount: number + + private _onopen: WebSocketEventListener | null = null + private _onmessage: WebSocketEventListener< + MessageEvent + > | null = null + private _onerror: WebSocketEventListener | null = null + private _onclose: WebSocketEventListener | null = null + + private [kOnSend]?: (data: WebSocketData) => void + + constructor(url: string | URL, protocols?: string | Array) { + super() + this.url = url.toString() + this.protocol = '' + this.extensions = '' + this.binaryType = 'blob' + this.readyState = this.CONNECTING + this.bufferedAmount = 0 + + Reflect.set(this, 'readyState', this.CONNECTING) + queueMicrotask(() => { + Reflect.set(this, 'readyState', this.OPEN) + this.protocol = protocols ? protocols[0] : 'ws' + + this.dispatchEvent(bindEvent(this, new Event('open'))) + }) + } + + set onopen(listener: WebSocketEventListener | null) { + this.removeEventListener('open', this._onopen) + this._onopen = listener + if (listener !== null) { + this.addEventListener('open', listener) + } + } + get onopen(): WebSocketEventListener | null { + return this._onopen + } + + set onmessage( + listener: WebSocketEventListener> | null + ) { + this.removeEventListener( + 'message', + this._onmessage as WebSocketEventListener + ) + this._onmessage = listener + if (listener !== null) { + this.addEventListener('message', listener) + } + } + get onmessage(): WebSocketEventListener> | null { + return this._onmessage + } + + set onerror(listener: WebSocketEventListener | null) { + this.removeEventListener('error', this._onerror) + this._onerror = listener + if (listener !== null) { + this.addEventListener('error', listener) + } + } + get onerror(): WebSocketEventListener | null { + return this._onerror + } + + set onclose(listener: WebSocketEventListener | null) { + this.removeEventListener('close', this._onclose as WebSocketEventListener) + this._onclose = listener + if (listener !== null) { + this.addEventListener('close', listener) + } + } + get onclose(): WebSocketEventListener | null { + return this._onclose + } + + /** + * @see https://websockets.spec.whatwg.org/#ref-for-dom-websocket-send%E2%91%A0 + */ + public send(data: WebSocketData): void { + if (this.readyState === this.CONNECTING) { + this.close() + throw new DOMException('InvalidStateError') + } + + // Sending when the socket is about to close + // discards the sent data. + if (this.readyState === this.CLOSING || this.readyState === this.CLOSED) { + return + } + + // Buffer the data to send in this even loop + // but send it in the next. + this.bufferedAmount += getDataSize(data) + + queueMicrotask(() => { + // This is a bit optimistic but since no actual data transfer + // is involved, all the data will be "sent" on the next tick. + this.bufferedAmount = 0 + + /** + * @note Notify the parent about outgoing data. + * This notifies the transport and the connection + * listens to the outgoing data to emit the "message" event. + */ + this[kOnSend]?.(data) + }) + } + + public close(code: number = 1000, reason?: string): void { + invariant(code, WEBSOCKET_CLOSE_CODE_RANGE_ERROR) + invariant( + code === 1000 || (code >= 3000 && code <= 4999), + WEBSOCKET_CLOSE_CODE_RANGE_ERROR + ) + + if (this.readyState === this.CLOSING || this.readyState === this.CLOSED) { + return + } + + this[kClose](code, reason) + } + + private [kClose](code: number = 1000, reason?: string): void { + this.readyState = this.CLOSING + + queueMicrotask(() => { + this.readyState = this.CLOSED + + // Non-user-configurable close status codes + // represent connection termination and must + // emit the "error" event before closing. + if (code > 1000 && code <= 1015) { + this.dispatchEvent(bindEvent(this, new Event('error'))) + } + + this.dispatchEvent( + bindEvent( + this, + new CloseEvent('close', { + code, + reason, + wasClean: code === 1000, + }) + ) + ) + + // Remove all event listeners once the socket is closed. + this._onopen = null + this._onmessage = null + this._onerror = null + this._onclose = null + }) + } + + public addEventListener( + type: K, + listener: (this: WebSocket, event: WebSocketEventMap[K]) => void, + options?: boolean | AddEventListenerOptions + ): void + public addEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions + ): void + public addEventListener( + type: unknown, + listener: unknown, + options?: unknown + ): void { + return super.addEventListener( + type as string, + listener as EventListener, + options as AddEventListenerOptions + ) + } + + removeEventListener( + type: K, + callback: EventListenerOrEventListenerObject | null, + options?: boolean | EventListenerOptions + ): void { + return super.removeEventListener(type, callback, options) + } +} + +function getDataSize(data: WebSocketData): number { + if (typeof data === 'string') { + return data.length + } + + if (data instanceof Blob) { + return data.size + } + + return data.byteLength +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketServerConnection.ts b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketServerConnection.ts new file mode 100644 index 0000000000000000000000000000000000000000..789a227ad3d9a2f7a57d996b99fbca98f60727ae --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketServerConnection.ts @@ -0,0 +1,339 @@ +import { invariant } from 'outvariant' +import { + kClose, + WebSocketEventListener, + WebSocketOverride, +} from './WebSocketOverride' +import type { WebSocketData } from './WebSocketTransport' +import type { WebSocketClassTransport } from './WebSocketClassTransport' +import { bindEvent } from './utils/bindEvent' +import { CancelableMessageEvent, CloseEvent } from './utils/events' + +const kEmitter = Symbol('kEmitter') +const kBoundListener = Symbol('kBoundListener') + +interface WebSocketServerEventMap { + open: Event + message: MessageEvent + error: Event + close: CloseEvent +} + +/** + * The WebSocket server instance represents the actual production + * WebSocket server connection. It's idle by default but you can + * establish it by calling `server.connect()`. + */ +export class WebSocketServerConnection { + /** + * A WebSocket instance connected to the original server. + */ + private realWebSocket?: WebSocket + private mockCloseController: AbortController + private [kEmitter]: EventTarget + + constructor( + private readonly socket: WebSocketOverride, + private readonly transport: WebSocketClassTransport, + private readonly createConnection: () => WebSocket + ) { + this[kEmitter] = new EventTarget() + this.mockCloseController = new AbortController() + + // Automatically forward outgoing client events + // to the actual server unless the outgoing message event + // has been prevented. The "outgoing" transport event it + // dispatched by the "client" connection. + this.transport.addEventListener('outgoing', (event) => { + // Ignore client messages if the server connection + // hasn't been established yet. Nowhere to forward. + if (this.readyState === -1) { + return + } + + // Every outgoing client message can prevent this forwarding + // by preventing the default of the outgoing message event. + // This listener will be added before user-defined listeners, + // so execute the logic on the next tick. + queueMicrotask(() => { + if (!event.defaultPrevented) { + this.send(event.data) + } + }) + }) + + this.transport.addEventListener( + 'incoming', + this.handleIncomingMessage.bind(this) + ) + } + + /** + * Server ready state. + * Proxies the ready state of the original WebSocket instance, + * if set. If the original connection hasn't been established, + * defaults to `-1`. + */ + public get readyState(): number { + if (this.realWebSocket) { + return this.realWebSocket.readyState + } + + return -1 + } + + /** + * Open connection to the original WebSocket server. + */ + public connect(): void { + invariant( + !this.realWebSocket || this.realWebSocket.readyState !== WebSocket.OPEN, + 'Failed to call "connect()" on the original WebSocket instance: the connection already open' + ) + + const realWebSocket = this.createConnection() + + // Inherit the binary type from the mock WebSocket client. + realWebSocket.binaryType = this.socket.binaryType + + // Allow the interceptor to listen to when the server connection + // has been established. This isn't necessary to operate with the connection + // but may be beneficial in some cases (like conditionally adding logging). + realWebSocket.addEventListener( + 'open', + (event) => { + this[kEmitter].dispatchEvent( + bindEvent(this.realWebSocket!, new Event('open', event)) + ) + }, + { once: true } + ) + + realWebSocket.addEventListener('message', (event) => { + // Dispatch the "incoming" transport event instead of + // invoking the internal handler directly. This way, + // anyone can listen to the "incoming" event but this + // class is the one resulting in it. + this.transport.dispatchEvent( + bindEvent( + this.realWebSocket!, + new MessageEvent('incoming', { + data: event.data, + origin: event.origin, + }) + ) + ) + }) + + // Close the original connection when the mock client closes. + // E.g. "client.close()" was called. + this.socket.addEventListener('close', this.handleMockClose.bind(this), { + signal: this.mockCloseController.signal, + }) + + // Forward the "close" event to let the interceptor handle + // closures initiated by the original server. + realWebSocket.addEventListener('close', this.handleRealClose.bind(this)) + + // Forward server errors to the WebSocket client as-is. + // We may consider exposing them to the interceptor in the future. + realWebSocket.addEventListener('error', () => { + this.socket.dispatchEvent(bindEvent(this.socket, new Event('error'))) + }) + + this.realWebSocket = realWebSocket + } + + /** + * Listen for the incoming events from the original WebSocket server. + */ + public addEventListener( + event: EventType, + listener: WebSocketEventListener, + options?: AddEventListenerOptions | boolean + ): void { + const boundListener = listener.bind(this.socket) + + // Store the bound listener on the original listener + // so the exact bound function can be accessed in "removeEventListener()". + Object.defineProperty(listener, kBoundListener, { + value: boundListener, + enumerable: false, + }) + + this[kEmitter].addEventListener( + event, + boundListener as EventListener, + options + ) + } + + /** + * Remove the listener for the given event. + */ + public removeEventListener( + event: EventType, + listener: WebSocketEventListener, + options?: EventListenerOptions | boolean + ): void { + this[kEmitter].removeEventListener( + event, + Reflect.get(listener, kBoundListener) as EventListener, + options + ) + } + + /** + * Send data to the original WebSocket server. + * @example + * server.send('hello') + * server.send(new Blob(['hello'])) + * server.send(new TextEncoder().encode('hello')) + */ + public send(data: WebSocketData): void { + const { realWebSocket } = this + + invariant( + realWebSocket, + 'Failed to call "server.send()" for "%s": the connection is not open. Did you forget to call "server.connect()"?', + this.socket.url + ) + + // Silently ignore writes on the closed original WebSocket. + if ( + realWebSocket.readyState === WebSocket.CLOSING || + realWebSocket.readyState === WebSocket.CLOSED + ) { + return + } + + // Delegate the send to when the original connection is open. + // Unlike the mock, connecting to the original server may take time + // so we cannot call this on the next tick. + if (realWebSocket.readyState === WebSocket.CONNECTING) { + realWebSocket.addEventListener( + 'open', + () => { + realWebSocket.send(data) + }, + { once: true } + ) + return + } + + // Send the data to the original WebSocket server. + realWebSocket.send(data) + } + + /** + * Close the actual server connection. + */ + public close(): void { + const { realWebSocket } = this + + invariant( + realWebSocket, + 'Failed to close server connection for "%s": the connection is not open. Did you forget to call "server.connect()"?', + this.socket.url + ) + + // Remove the "close" event listener from the server + // so it doesn't close the underlying WebSocket client + // when you call "server.close()". + realWebSocket.removeEventListener('close', this.handleRealClose) + + if ( + realWebSocket.readyState === WebSocket.CLOSING || + realWebSocket.readyState === WebSocket.CLOSED + ) { + return + } + + realWebSocket.close() + + // Dispatch the "close" event on the server connection. + queueMicrotask(() => { + this[kEmitter].dispatchEvent( + bindEvent(this.realWebSocket, new CloseEvent('close')) + ) + }) + } + + private handleIncomingMessage(event: MessageEvent): void { + // Clone the event to dispatch it on this class + // once again and prevent the "already being dispatched" + // exception. Clone it here so we can observe this event + // being prevented in the "server.on()" listeners. + const messageEvent = bindEvent( + event.target, + new CancelableMessageEvent('message', { + data: event.data, + origin: event.origin, + cancelable: true, + }) + ) + + /** + * @note Emit "message" event on the server connection + * instance to let the interceptor know about these + * incoming events from the original server. In that listener, + * the interceptor can modify or skip the event forwarding + * to the mock WebSocket instance. + */ + this[kEmitter].dispatchEvent(messageEvent) + + /** + * @note Forward the incoming server events to the client. + * Preventing the default on the message event stops this. + */ + if (!messageEvent.defaultPrevented) { + this.socket.dispatchEvent( + bindEvent( + /** + * @note Bind the forwarded original server events + * to the mock WebSocket instance so it would + * dispatch them straight away. + */ + this.socket, + // Clone the message event again to prevent + // the "already being dispatched" exception. + new MessageEvent('message', { + data: event.data, + origin: event.origin, + }) + ) + ) + } + } + + private handleMockClose(_event: Event): void { + // Close the original connection if the mock client closes. + if (this.realWebSocket) { + this.realWebSocket.close() + } + } + + private handleRealClose(event: CloseEvent): void { + // For closures originating from the original server, + // remove the "close" listener from the mock client. + // original close -> (?) client[kClose]() --X-> "close" (again). + this.mockCloseController.abort() + + const closeEvent = bindEvent( + this.realWebSocket, + new CloseEvent('close', event) + ) + + this[kEmitter].dispatchEvent(closeEvent) + + // If the close event from the server hasn't been prevented, + // forward the closure to the mock client. + if (!closeEvent.defaultPrevented) { + // Close the intercepted client forcefully to + // allow non-configurable status codes from the server. + // If the socket has been closed by now, no harm calling + // this again—it will have no effect. + this.socket[kClose](event.code, event.reason) + } + } +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketTransport.ts b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketTransport.ts new file mode 100644 index 0000000000000000000000000000000000000000..973f511ed983d3dc81ad895a317d66d24460ffe1 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketTransport.ts @@ -0,0 +1,39 @@ +import { CloseEvent } from './utils/events' + +export type WebSocketData = string | ArrayBufferLike | Blob | ArrayBufferView + +export type WebSocketTransportEventMap = { + incoming: MessageEvent + outgoing: MessageEvent + close: CloseEvent +} + +export type StrictEventListenerOrEventListenerObject = + | ((this: WebSocket, event: EventType) => void) + | { + handleEvent(this: WebSocket, event: EventType): void + } + +export interface WebSocketTransport { + addEventListener( + event: EventType, + listener: StrictEventListenerOrEventListenerObject< + WebSocketTransportEventMap[EventType] + > | null, + options?: boolean | AddEventListenerOptions + ): void + + dispatchEvent( + event: WebSocketTransportEventMap[EventType] + ): boolean + + /** + * Send the data from the server to this client. + */ + send(data: WebSocketData): void + + /** + * Close the client connection. + */ + close(code?: number, reason?: string): void +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/index.ts b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..5950c1a46bf142e38ad2bb911a66cb6522768f99 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/index.ts @@ -0,0 +1,98 @@ +import { Interceptor } from '../../Interceptor' +import { + type WebSocketClientConnectionProtocol, + WebSocketClientConnection, +} from './WebSocketClientConnection' +import { WebSocketServerConnection } from './WebSocketServerConnection' +import { WebSocketClassTransport } from './WebSocketClassTransport' +import { WebSocketOverride } from './WebSocketOverride' + +export { type WebSocketData, WebSocketTransport } from './WebSocketTransport' +export { + WebSocketClientConnection, + WebSocketClientConnectionProtocol, + WebSocketServerConnection, +} + +export type WebSocketEventMap = { + connection: [args: WebSocketConnectionData] +} + +export type WebSocketConnectionData = { + /** + * The incoming WebSocket client connection. + */ + client: WebSocketClientConnection + + /** + * The original WebSocket server connection. + */ + server: WebSocketServerConnection +} + +/** + * Intercept the outgoing WebSocket connections created using + * the global `WebSocket` class. + */ +export class WebSocketInterceptor extends Interceptor { + static symbol = Symbol('websocket') + + constructor() { + super(WebSocketInterceptor.symbol) + } + + protected checkEnvironment(): boolean { + // Enable this interceptor in any environment + // that has a global WebSocket API. + return typeof globalThis.WebSocket !== 'undefined' + } + + protected setup(): void { + const originalWebSocket = globalThis.WebSocket + + const webSocketProxy = new Proxy(globalThis.WebSocket, { + construct: ( + target, + args: ConstructorParameters, + newTarget + ) => { + const [url, protocols] = args + + const createConnection = (): WebSocket => { + return Reflect.construct(target, args, newTarget) + } + + // All WebSocket instances are mocked and don't forward + // any events to the original server (no connection established). + // To forward the events, the user must use the "server.send()" API. + const socket = new WebSocketOverride(url, protocols) + const transport = new WebSocketClassTransport(socket) + + // Emit the "connection" event to the interceptor on the next tick + // so the client can modify WebSocket options, like "binaryType" + // while the connection is already pending. + queueMicrotask(() => { + // The "globalThis.WebSocket" class stands for + // the client-side connection. Assume it's established + // as soon as the WebSocket instance is constructed. + this.emitter.emit('connection', { + client: new WebSocketClientConnection(socket, transport), + server: new WebSocketServerConnection( + socket, + transport, + createConnection + ), + }) + }) + + return socket + }, + }) + + globalThis.WebSocket = webSocketProxy + + this.subscriptions.push(() => { + globalThis.WebSocket = originalWebSocket + }) + } +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/utils/bindEvent.test.ts b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/utils/bindEvent.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..7871961f0f24e4665cbddfdd5d2bfe91ee9b7741 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/utils/bindEvent.test.ts @@ -0,0 +1,27 @@ +/** + * @vitest-environment node + */ +import { it, expect } from 'vitest' +import { bindEvent } from './bindEvent' + +it('sets the "target" on the given event', () => { + class Target {} + const target = new Target() + const event = new Event('open') + bindEvent(target, event) + + expect(event.type).toBe('open') + expect(event.target).toEqual(target) +}) + +it('overrides existing "target" on the given event', () => { + class Target {} + const oldTarget = new Target() + const newTarget = new Target() + const event = new Event('open') + bindEvent(oldTarget, event) + bindEvent(newTarget, event) + + expect(event.type).toBe('open') + expect(event.target).toEqual(newTarget) +}) diff --git a/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/utils/bindEvent.ts b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/utils/bindEvent.ts new file mode 100644 index 0000000000000000000000000000000000000000..8efa6820263a83eb6ff9d892ad92c19ca2074626 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/utils/bindEvent.ts @@ -0,0 +1,21 @@ +type EventWithTarget = E & { target: T } + +export function bindEvent( + target: T, + event: E +): EventWithTarget { + Object.defineProperties(event, { + target: { + value: target, + enumerable: true, + writable: true, + }, + currentTarget: { + value: target, + enumerable: true, + writable: true, + }, + }) + + return event as EventWithTarget +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/utils/events.test.ts b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/utils/events.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..cf83cafcc56a1d3959b0d3f2ee4dae8c7bb40ee0 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/utils/events.test.ts @@ -0,0 +1,101 @@ +/** + * @vitest-environment node + */ +import { describe, it, expect } from 'vitest' +import { CancelableMessageEvent, CloseEvent } from './events' + +describe(CancelableMessageEvent, () => { + it('initiates with the right defaults', () => { + const event = new CancelableMessageEvent('message', { + data: 'hello', + }) + + expect(event).toBeInstanceOf(MessageEvent) + expect(event.type).toBe('message') + expect(event.data).toBe('hello') + expect(event.cancelable).toBe(false) + expect(event.defaultPrevented).toBe(false) + }) + + it('initiates a canceaable event', () => { + const event = new CancelableMessageEvent('message', { + data: 'hello', + cancelable: true, + }) + + expect(event).toBeInstanceOf(MessageEvent) + expect(event.type).toBe('message') + expect(event.data).toBe('hello') + expect(event.cancelable).toBe(true) + expect(event.defaultPrevented).toBe(false) + }) + + it('cancels a cancelable event when calling "preventDefault()"', () => { + const event = new CancelableMessageEvent('message', { + data: 'hello', + cancelable: true, + }) + + expect(event.defaultPrevented).toBe(false) + event.preventDefault() + expect(event.defaultPrevented).toBe(true) + }) + + it('does nothing when calling "preventDefault()" on a non-cancelable event', () => { + const event = new CancelableMessageEvent('message', { + data: 'hello', + }) + + expect(event.defaultPrevented).toBe(false) + event.preventDefault() + expect(event.defaultPrevented).toBe(false) + }) + + it('supports setting the "cancelable" value directly', () => { + const event = new CancelableMessageEvent('message', {}) + /** + * @note HappyDOM sets the "cancelable" and "preventDefault" + * event properties directly. That's no-op as far as I know + * but they do it and we have to account for that. + */ + event.cancelable = true + expect(event.cancelable).toBe(true) + }) + + it('supports setting the "defaultPrevented" value directly', () => { + const event = new CancelableMessageEvent('message', {}) + /** + * @note HappyDOM sets the "cancelable" and "preventDefault" + * event properties directly. That's no-op as far as I know + * but they do it and we have to account for that. + */ + event.defaultPrevented = true + expect(event.defaultPrevented).toBe(true) + }) +}) + +describe(CloseEvent, () => { + it('initiates with the right defaults', () => { + const event = new CloseEvent('close') + + expect(event).toBeInstanceOf(Event) + expect(event.type).toBe('close') + expect(event.code).toBe(0) + expect(event.reason).toBe('') + expect(event.wasClean).toBe(false) + }) + + it('initiates with custom values', () => { + const event = new CloseEvent('close', { + code: 1003, + reason: 'close reason', + wasClean: true, + }) + + expect(event).toBeInstanceOf(Event) + expect(event.type).toBe('close') + expect(event.code).toBe(1003) + expect(event.reason).toBe('close reason') + expect(event.wasClean).toBe(true) + }) +}) diff --git a/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/utils/events.ts b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/utils/events.ts new file mode 100644 index 0000000000000000000000000000000000000000..5914cb7e28bc9a4514b370700ce247677c4eff88 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/utils/events.ts @@ -0,0 +1,61 @@ +const kCancelable = Symbol('kCancelable') +const kDefaultPrevented = Symbol('kDefaultPrevented') + +/** + * A `MessageEvent` superset that supports event cancellation + * in Node.js. It's rather non-intrusive so it can be safely + * used in the browser as well. + * + * @see https://github.com/nodejs/node/issues/51767 + */ +export class CancelableMessageEvent extends MessageEvent { + [kCancelable]: boolean; + [kDefaultPrevented]: boolean + + constructor(type: string, init: MessageEventInit) { + super(type, init) + this[kCancelable] = !!init.cancelable + this[kDefaultPrevented] = false + } + + get cancelable() { + return this[kCancelable] + } + + set cancelable(nextCancelable) { + this[kCancelable] = nextCancelable + } + + get defaultPrevented() { + return this[kDefaultPrevented] + } + + set defaultPrevented(nextDefaultPrevented) { + this[kDefaultPrevented] = nextDefaultPrevented + } + + public preventDefault(): void { + if (this.cancelable && !this[kDefaultPrevented]) { + this[kDefaultPrevented] = true + } + } +} + +interface CloseEventInit extends EventInit { + code?: number + reason?: string + wasClean?: boolean +} + +export class CloseEvent extends Event { + public code: number + public reason: string + public wasClean: boolean + + constructor(type: string, init: CloseEventInit = {}) { + super(type, init) + this.code = init.code === undefined ? 0 : init.code + this.reason = init.reason === undefined ? '' : init.reason + this.wasClean = init.wasClean === undefined ? false : init.wasClean + } +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts new file mode 100644 index 0000000000000000000000000000000000000000..984ae3f080c4f819211f95f7190bd30defa405eb --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts @@ -0,0 +1,628 @@ +import { invariant } from 'outvariant' +import { isNodeProcess } from 'is-node-process' +import type { Logger } from '@open-draft/logger' +import { concatArrayBuffer } from './utils/concatArrayBuffer' +import { createEvent } from './utils/createEvent' +import { + decodeBuffer, + encodeBuffer, + toArrayBuffer, +} from '../../utils/bufferUtils' +import { createProxy } from '../../utils/createProxy' +import { isDomParserSupportedType } from './utils/isDomParserSupportedType' +import { parseJson } from '../../utils/parseJson' +import { createResponse } from './utils/createResponse' +import { INTERNAL_REQUEST_ID_HEADER_NAME } from '../../Interceptor' +import { createRequestId } from '../../createRequestId' + +const IS_MOCKED_RESPONSE = Symbol('isMockedResponse') +const IS_NODE = isNodeProcess() + +/** + * An `XMLHttpRequest` instance controller that allows us + * to handle any given request instance (e.g. responding to it). + */ +export class XMLHttpRequestController { + public request: XMLHttpRequest + public requestId: string + public onRequest?: ( + this: XMLHttpRequestController, + args: { + request: Request + requestId: string + } + ) => Promise + public onResponse?: ( + this: XMLHttpRequestController, + args: { + response: Response + isMockedResponse: boolean + request: Request + requestId: string + } + ) => void + + private method: string = 'GET' + private url: URL = null as any + private requestHeaders: Headers + private requestBody?: XMLHttpRequestBodyInit | Document | null + private responseBuffer: Uint8Array + private events: Map> + + constructor(readonly initialRequest: XMLHttpRequest, public logger: Logger) { + this.events = new Map() + this.requestId = createRequestId() + this.requestHeaders = new Headers() + this.responseBuffer = new Uint8Array() + + this.request = createProxy(initialRequest, { + setProperty: ([propertyName, nextValue], invoke) => { + switch (propertyName) { + case 'ontimeout': { + const eventName = propertyName.slice( + 2 + ) as keyof XMLHttpRequestEventTargetEventMap + + /** + * @note Proxy callbacks to event listeners because JSDOM has trouble + * translating these properties to callbacks. It seemed to be operating + * on events exclusively. + */ + this.request.addEventListener(eventName, nextValue as any) + + return invoke() + } + + default: { + return invoke() + } + } + }, + methodCall: ([methodName, args], invoke) => { + switch (methodName) { + case 'open': { + const [method, url] = args as [string, string | undefined] + + if (typeof url === 'undefined') { + this.method = 'GET' + this.url = toAbsoluteUrl(method) + } else { + this.method = method + this.url = toAbsoluteUrl(url) + } + + this.logger = this.logger.extend(`${this.method} ${this.url.href}`) + this.logger.info('open', this.method, this.url.href) + + return invoke() + } + + case 'addEventListener': { + const [eventName, listener] = args as [ + keyof XMLHttpRequestEventTargetEventMap, + Function + ] + + this.registerEvent(eventName, listener) + this.logger.info('addEventListener', eventName, listener) + + return invoke() + } + + case 'setRequestHeader': { + const [name, value] = args as [string, string] + this.requestHeaders.set(name, value) + + this.logger.info('setRequestHeader', name, value) + + return invoke() + } + + case 'send': { + const [body] = args as [ + body?: XMLHttpRequestBodyInit | Document | null + ] + + if (body != null) { + this.requestBody = + typeof body === 'string' ? encodeBuffer(body) : body + } + + this.request.addEventListener('load', () => { + if (typeof this.onResponse !== 'undefined') { + // Create a Fetch API Response representation of whichever + // response this XMLHttpRequest received. Note those may + // be either a mocked and the original response. + const fetchResponse = createResponse( + this.request, + /** + * The `response` property is the right way to read + * the ambiguous response body, as the request's "responseType" may differ. + * @see https://xhr.spec.whatwg.org/#the-response-attribute + */ + this.request.response + ) + + // Notify the consumer about the response. + this.onResponse.call(this, { + response: fetchResponse, + isMockedResponse: IS_MOCKED_RESPONSE in this.request, + request: fetchRequest, + requestId: this.requestId!, + }) + } + }) + + // Delegate request handling to the consumer. + const fetchRequest = this.toFetchApiRequest() + const onceRequestSettled = + this.onRequest?.call(this, { + request: fetchRequest, + requestId: this.requestId!, + }) || Promise.resolve() + + onceRequestSettled.finally(() => { + // If the consumer didn't handle the request perform it as-is. + // Note that the request may not yet be DONE and may, in fact, + // be LOADING while the "respondWith" method does its magic. + if (this.request.readyState < this.request.LOADING) { + this.logger.info( + 'request callback settled but request has not been handled (readystate %d), performing as-is...', + this.request.readyState + ) + + /** + * @note Set the intercepted request ID on the original request in Node.js + * so that if it triggers any other interceptors, they don't attempt + * to process it once again. + * + * For instance, XMLHttpRequest is often implemented via "http.ClientRequest" + * and we don't want for both XHR and ClientRequest interceptors to + * handle the same request at the same time (e.g. emit the "response" event twice). + */ + if (IS_NODE) { + this.request.setRequestHeader( + INTERNAL_REQUEST_ID_HEADER_NAME, + this.requestId! + ) + } + + return invoke() + } + }) + + break + } + + default: { + return invoke() + } + } + }, + }) + } + + private registerEvent( + eventName: keyof XMLHttpRequestEventTargetEventMap, + listener: Function + ): void { + const prevEvents = this.events.get(eventName) || [] + const nextEvents = prevEvents.concat(listener) + this.events.set(eventName, nextEvents) + + this.logger.info('registered event "%s"', eventName, listener) + } + + /** + * Responds to the current request with the given + * Fetch API `Response` instance. + */ + public respondWith(response: Response): void { + this.logger.info( + 'responding with a mocked response: %d %s', + response.status, + response.statusText + ) + + /** + * @note Since `XMLHttpRequestController` delegates the handling of the responses + * to the "load" event listener that doesn't distinguish between the mocked and original + * responses, mark the request that had a mocked response with a corresponding symbol. + */ + define(this.request, IS_MOCKED_RESPONSE, true) + + define(this.request, 'status', response.status) + define(this.request, 'statusText', response.statusText) + define(this.request, 'responseURL', this.url.href) + + this.request.getResponseHeader = new Proxy(this.request.getResponseHeader, { + apply: (_, __, args: [name: string]) => { + this.logger.info('getResponseHeader', args[0]) + + if (this.request.readyState < this.request.HEADERS_RECEIVED) { + this.logger.info('headers not received yet, returning null') + + // Headers not received yet, nothing to return. + return null + } + + const headerValue = response.headers.get(args[0]) + this.logger.info( + 'resolved response header "%s" to', + args[0], + headerValue + ) + + return headerValue + }, + }) + + this.request.getAllResponseHeaders = new Proxy( + this.request.getAllResponseHeaders, + { + apply: () => { + this.logger.info('getAllResponseHeaders') + + if (this.request.readyState < this.request.HEADERS_RECEIVED) { + this.logger.info('headers not received yet, returning empty string') + + // Headers not received yet, nothing to return. + return '' + } + + const headersList = Array.from(response.headers.entries()) + const allHeaders = headersList + .map(([headerName, headerValue]) => { + return `${headerName}: ${headerValue}` + }) + .join('\r\n') + + this.logger.info('resolved all response headers to', allHeaders) + + return allHeaders + }, + } + ) + + // Update the response getters to resolve against the mocked response. + Object.defineProperties(this.request, { + response: { + enumerable: true, + configurable: false, + get: () => this.response, + }, + responseText: { + enumerable: true, + configurable: false, + get: () => this.responseText, + }, + responseXML: { + enumerable: true, + configurable: false, + get: () => this.responseXML, + }, + }) + + const totalResponseBodyLength = response.headers.has('Content-Length') + ? Number(response.headers.get('Content-Length')) + : /** + * @todo Infer the response body length from the response body. + */ + undefined + + this.logger.info('calculated response body length', totalResponseBodyLength) + + this.trigger('loadstart', { + loaded: 0, + total: totalResponseBodyLength, + }) + + this.setReadyState(this.request.HEADERS_RECEIVED) + this.setReadyState(this.request.LOADING) + + const finalizeResponse = () => { + this.logger.info('finalizing the mocked response...') + + this.setReadyState(this.request.DONE) + + this.trigger('load', { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength, + }) + + this.trigger('loadend', { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength, + }) + } + + if (response.body) { + this.logger.info('mocked response has body, streaming...') + + const reader = response.body.getReader() + + const readNextResponseBodyChunk = async () => { + const { value, done } = await reader.read() + + if (done) { + this.logger.info('response body stream done!') + finalizeResponse() + return + } + + if (value) { + this.logger.info('read response body chunk:', value) + this.responseBuffer = concatArrayBuffer(this.responseBuffer, value) + + this.trigger('progress', { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength, + }) + } + + readNextResponseBodyChunk() + } + + readNextResponseBodyChunk() + } else { + finalizeResponse() + } + } + + private responseBufferToText(): string { + return decodeBuffer(this.responseBuffer) + } + + get response(): unknown { + this.logger.info( + 'getResponse (responseType: %s)', + this.request.responseType + ) + + if (this.request.readyState !== this.request.DONE) { + return null + } + + switch (this.request.responseType) { + case 'json': { + const responseJson = parseJson(this.responseBufferToText()) + this.logger.info('resolved response JSON', responseJson) + + return responseJson + } + + case 'arraybuffer': { + const arrayBuffer = toArrayBuffer(this.responseBuffer) + this.logger.info('resolved response ArrayBuffer', arrayBuffer) + + return arrayBuffer + } + + case 'blob': { + const mimeType = + this.request.getResponseHeader('Content-Type') || 'text/plain' + const responseBlob = new Blob([this.responseBufferToText()], { + type: mimeType, + }) + + this.logger.info( + 'resolved response Blob (mime type: %s)', + responseBlob, + mimeType + ) + + return responseBlob + } + + default: { + const responseText = this.responseBufferToText() + this.logger.info( + 'resolving "%s" response type as text', + this.request.responseType, + responseText + ) + + return responseText + } + } + } + + get responseText(): string { + /** + * Throw when trying to read the response body as text when the + * "responseType" doesn't expect text. This just respects the spec better. + * @see https://xhr.spec.whatwg.org/#the-responsetext-attribute + */ + invariant( + this.request.responseType === '' || this.request.responseType === 'text', + 'InvalidStateError: The object is in invalid state.' + ) + + if ( + this.request.readyState !== this.request.LOADING && + this.request.readyState !== this.request.DONE + ) { + return '' + } + + const responseText = this.responseBufferToText() + this.logger.info('getResponseText: "%s"', responseText) + + return responseText + } + + get responseXML(): Document | null { + invariant( + this.request.responseType === '' || + this.request.responseType === 'document', + 'InvalidStateError: The object is in invalid state.' + ) + + if (this.request.readyState !== this.request.DONE) { + return null + } + + const contentType = this.request.getResponseHeader('Content-Type') || '' + + if (typeof DOMParser === 'undefined') { + console.warn( + 'Cannot retrieve XMLHttpRequest response body as XML: DOMParser is not defined. You are likely using an environment that is not browser or does not polyfill browser globals correctly.' + ) + return null + } + + if (isDomParserSupportedType(contentType)) { + return new DOMParser().parseFromString( + this.responseBufferToText(), + contentType + ) + } + + return null + } + + public errorWith(error: Error): void { + this.logger.info('responding with an error') + + this.setReadyState(this.request.DONE) + this.trigger('error') + this.trigger('loadend') + } + + /** + * Transitions this request's `readyState` to the given one. + */ + private setReadyState(nextReadyState: number): void { + this.logger.info( + 'setReadyState: %d -> %d', + this.request.readyState, + nextReadyState + ) + + if (this.request.readyState === nextReadyState) { + this.logger.info('ready state identical, skipping transition...') + return + } + + define(this.request, 'readyState', nextReadyState) + + this.logger.info('set readyState to: %d', nextReadyState) + + if (nextReadyState !== this.request.UNSENT) { + this.logger.info('triggerring "readystatechange" event...') + + this.trigger('readystatechange') + } + } + + /** + * Triggers given event on the `XMLHttpRequest` instance. + */ + private trigger< + EventName extends keyof (XMLHttpRequestEventTargetEventMap & { + readystatechange: ProgressEvent + }) + >(eventName: EventName, options?: ProgressEventInit): void { + const callback = this.request[`on${eventName}`] + const event = createEvent(this.request, eventName, options) + + this.logger.info('trigger "%s"', eventName, options || '') + + // Invoke direct callbacks. + if (typeof callback === 'function') { + this.logger.info('found a direct "%s" callback, calling...', eventName) + callback.call(this.request, event) + } + + // Invoke event listeners. + for (const [registeredEventName, listeners] of this.events) { + if (registeredEventName === eventName) { + this.logger.info( + 'found %d listener(s) for "%s" event, calling...', + listeners.length, + eventName + ) + + listeners.forEach((listener) => listener.call(this.request, event)) + } + } + } + + /** + * Converts this `XMLHttpRequest` instance into a Fetch API `Request` instance. + */ + public toFetchApiRequest(): Request { + this.logger.info('converting request to a Fetch API Request...') + + const fetchRequest = new Request(this.url.href, { + method: this.method, + headers: this.requestHeaders, + /** + * @see https://xhr.spec.whatwg.org/#cross-origin-credentials + */ + credentials: this.request.withCredentials ? 'include' : 'same-origin', + body: ['GET', 'HEAD'].includes(this.method) + ? null + : (this.requestBody as BodyInit), + }) + + const proxyHeaders = createProxy(fetchRequest.headers, { + methodCall: ([methodName, args], invoke) => { + // Forward the latest state of the internal request headers + // because the interceptor might have modified them + // without responding to the request. + switch (methodName) { + case 'append': + case 'set': { + const [headerName, headerValue] = args as [string, string] + this.request.setRequestHeader(headerName, headerValue) + break + } + + case 'delete': { + const [headerName] = args as [string] + console.warn( + `XMLHttpRequest: Cannot remove a "${headerName}" header from the Fetch API representation of the "${fetchRequest.method} ${fetchRequest.url}" request. XMLHttpRequest headers cannot be removed.` + ) + break + } + } + + return invoke() + }, + }) + define(fetchRequest, 'headers', proxyHeaders) + + this.logger.info('converted request to a Fetch API Request!', fetchRequest) + + return fetchRequest + } +} + +function toAbsoluteUrl(url: string | URL): URL { + /** + * @note XMLHttpRequest interceptor may run in environments + * that implement XMLHttpRequest but don't implement "location" + * (for example, React Native). If that's the case, return the + * input URL as-is (nothing to be relative to). + * @see https://github.com/mswjs/msw/issues/1777 + */ + if (typeof location === 'undefined') { + return new URL(url) + } + + return new URL(url.toString(), location.href) +} + +function define( + target: object, + property: string | symbol, + value: unknown +): void { + Reflect.defineProperty(target, property, { + // Ensure writable properties to allow redefining readonly properties. + writable: true, + enumerable: true, + value, + }) +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/XMLHttpRequestProxy.ts b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/XMLHttpRequestProxy.ts new file mode 100644 index 0000000000000000000000000000000000000000..3a6d6ab995f6094c64cfc4bccdce0d3307fa681d --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/XMLHttpRequestProxy.ts @@ -0,0 +1,199 @@ +import { until } from '@open-draft/until' +import type { Logger } from '@open-draft/logger' +import { XMLHttpRequestEmitter } from '.' +import { toInteractiveRequest } from '../../utils/toInteractiveRequest' +import { emitAsync } from '../../utils/emitAsync' +import { XMLHttpRequestController } from './XMLHttpRequestController' +import { + createServerErrorResponse, + isResponseError, +} from '../../utils/responseUtils' + +export interface XMLHttpRequestProxyOptions { + emitter: XMLHttpRequestEmitter + logger: Logger +} + +/** + * Create a proxied `XMLHttpRequest` class. + * The proxied class establishes spies on certain methods, + * allowing us to intercept requests and respond to them. + */ +export function createXMLHttpRequestProxy({ + emitter, + logger, +}: XMLHttpRequestProxyOptions) { + const XMLHttpRequestProxy = new Proxy(globalThis.XMLHttpRequest, { + construct(target, args, newTarget) { + logger.info('constructed new XMLHttpRequest') + + const originalRequest = Reflect.construct( + target, + args, + newTarget + ) as XMLHttpRequest + + /** + * @note Forward prototype descriptors onto the proxied object. + * XMLHttpRequest is implemented in JSDOM in a way that assigns + * a bunch of descriptors, like "set responseType()" on the prototype. + * With this propagation, we make sure that those descriptors trigger + * when the user operates with the proxied request instance. + */ + const prototypeDescriptors = Object.getOwnPropertyDescriptors( + target.prototype + ) + for (const propertyName in prototypeDescriptors) { + Reflect.defineProperty( + originalRequest, + propertyName, + prototypeDescriptors[propertyName] + ) + } + + const xhrRequestController = new XMLHttpRequestController( + originalRequest, + logger + ) + + xhrRequestController.onRequest = async function ({ request, requestId }) { + const { interactiveRequest, requestController } = + toInteractiveRequest(request) + + this.logger.info('awaiting mocked response...') + + emitter.once('request', ({ requestId: pendingRequestId }) => { + if (pendingRequestId !== requestId) { + return + } + + if (requestController.responsePromise.state === 'pending') { + requestController.respondWith(undefined) + } + }) + + const resolverResult = await until(async () => { + this.logger.info( + 'emitting the "request" event for %s listener(s)...', + emitter.listenerCount('request') + ) + + await emitAsync(emitter, 'request', { + request: interactiveRequest, + requestId, + }) + + this.logger.info('all "request" listeners settled!') + + const mockedResponse = await requestController.responsePromise + + this.logger.info('event.respondWith called with:', mockedResponse) + + return mockedResponse + }) + + if (resolverResult.error) { + this.logger.info( + 'request listener threw an exception, aborting request...', + resolverResult.error + ) + + // Treat thrown Responses as mocked responses. + if (resolverResult.error instanceof Response) { + if (isResponseError(resolverResult.error)) { + xhrRequestController.errorWith(new TypeError('Network error')) + } else { + this.respondWith(resolverResult.error) + } + + return + } + + if (emitter.listenerCount('unhandledException') > 0) { + // Emit the "unhandledException" event so the client can opt-out + // from the default exception handling (producing 500 error responses). + await emitAsync(emitter, 'unhandledException', { + error: resolverResult.error, + request, + requestId, + controller: { + respondWith: + xhrRequestController.respondWith.bind(xhrRequestController), + errorWith: + xhrRequestController.errorWith.bind(xhrRequestController), + }, + }) + + // If any of the "unhandledException" listeners handled the request, + // do nothing. Note that mocked responses will dispatch + // HEADERS_RECEIVED (2), then LOADING (3), and DONE (4) can take + // time as the mocked response body finishes streaming. + if (originalRequest.readyState > XMLHttpRequest.OPENED) { + return + } + } + + // Unhandled exceptions in the request listeners are + // synonymous to unhandled exceptions on the server. + // Those are represented as 500 error responses. + xhrRequestController.respondWith( + createServerErrorResponse(resolverResult.error) + ) + + return + } + + const mockedResponse = resolverResult.data + + if (typeof mockedResponse !== 'undefined') { + this.logger.info( + 'received mocked response: %d %s', + mockedResponse.status, + mockedResponse.statusText + ) + + if (isResponseError(mockedResponse)) { + this.logger.info( + 'received a network error response, rejecting the request promise...' + ) + + xhrRequestController.errorWith(new TypeError('Network error')) + return + } + + return xhrRequestController.respondWith(mockedResponse) + } + + this.logger.info( + 'no mocked response received, performing request as-is...' + ) + } + + xhrRequestController.onResponse = async function ({ + response, + isMockedResponse, + request, + requestId, + }) { + this.logger.info( + 'emitting the "response" event for %s listener(s)...', + emitter.listenerCount('response') + ) + + emitter.emit('response', { + response, + isMockedResponse, + request, + requestId, + }) + } + + // Return the proxied request from the controller + // so that the controller can react to the consumer's interactions + // with this request (opening/sending/etc). + return xhrRequestController.request + }, + }) + + return XMLHttpRequestProxy +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/index.ts b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..daf89530522679a88f17566fcad7451b38a8221c --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/index.ts @@ -0,0 +1,66 @@ +import { invariant } from 'outvariant' +import { Emitter } from 'strict-event-emitter' +import { HttpRequestEventMap, IS_PATCHED_MODULE } from '../../glossary' +import { InteractiveRequest } from '../../utils/toInteractiveRequest' +import { Interceptor } from '../../Interceptor' +import { createXMLHttpRequestProxy } from './XMLHttpRequestProxy' + +export type XMLHttpRequestEventListener = (args: { + request: InteractiveRequest + requestId: string +}) => Promise | void + +export type XMLHttpRequestEmitter = Emitter + +export class XMLHttpRequestInterceptor extends Interceptor { + static interceptorSymbol = Symbol('xhr') + + constructor() { + super(XMLHttpRequestInterceptor.interceptorSymbol) + } + + protected checkEnvironment() { + return typeof globalThis.XMLHttpRequest !== 'undefined' + } + + protected setup() { + const logger = this.logger.extend('setup') + + logger.info('patching "XMLHttpRequest" module...') + + const PureXMLHttpRequest = globalThis.XMLHttpRequest + + invariant( + !(PureXMLHttpRequest as any)[IS_PATCHED_MODULE], + 'Failed to patch the "XMLHttpRequest" module: already patched.' + ) + + globalThis.XMLHttpRequest = createXMLHttpRequestProxy({ + emitter: this.emitter, + logger: this.logger, + }) + + logger.info( + 'native "XMLHttpRequest" module patched!', + globalThis.XMLHttpRequest.name + ) + + Object.defineProperty(globalThis.XMLHttpRequest, IS_PATCHED_MODULE, { + enumerable: true, + configurable: true, + value: true, + }) + + this.subscriptions.push(() => { + Object.defineProperty(globalThis.XMLHttpRequest, IS_PATCHED_MODULE, { + value: undefined, + }) + + globalThis.XMLHttpRequest = PureXMLHttpRequest + logger.info( + 'native "XMLHttpRequest" module restored!', + globalThis.XMLHttpRequest.name + ) + }) + } +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/polyfills/EventPolyfill.ts b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/polyfills/EventPolyfill.ts new file mode 100644 index 0000000000000000000000000000000000000000..b02c2cd6f342d13714399a7961840f32e0252297 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/polyfills/EventPolyfill.ts @@ -0,0 +1,51 @@ +export class EventPolyfill implements Event { + readonly AT_TARGET: number = 0 + readonly BUBBLING_PHASE: number = 0 + readonly CAPTURING_PHASE: number = 0 + readonly NONE: number = 0 + + public type: string = '' + public srcElement: EventTarget | null = null + public target: EventTarget | null + public currentTarget: EventTarget | null = null + public eventPhase: number = 0 + public timeStamp: number + public isTrusted: boolean = true + public composed: boolean = false + public cancelable: boolean = true + public defaultPrevented: boolean = false + public bubbles: boolean = true + public lengthComputable: boolean = true + public loaded: number = 0 + public total: number = 0 + + cancelBubble: boolean = false + returnValue: boolean = true + + constructor( + type: string, + options?: { target: EventTarget; currentTarget: EventTarget } + ) { + this.type = type + this.target = options?.target || null + this.currentTarget = options?.currentTarget || null + this.timeStamp = Date.now() + } + + public composedPath(): EventTarget[] { + return [] + } + + public initEvent(type: string, bubbles?: boolean, cancelable?: boolean) { + this.type = type + this.bubbles = !!bubbles + this.cancelable = !!cancelable + } + + public preventDefault() { + this.defaultPrevented = true + } + + public stopPropagation() {} + public stopImmediatePropagation() {} +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/polyfills/ProgressEventPolyfill.ts b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/polyfills/ProgressEventPolyfill.ts new file mode 100644 index 0000000000000000000000000000000000000000..20a318816ab8c5f7976e6f3ab9aa237511bd8d00 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/polyfills/ProgressEventPolyfill.ts @@ -0,0 +1,17 @@ +import { EventPolyfill } from './EventPolyfill' + +export class ProgressEventPolyfill extends EventPolyfill { + readonly lengthComputable: boolean + readonly composed: boolean + readonly loaded: number + readonly total: number + + constructor(type: string, init?: ProgressEventInit) { + super(type) + + this.lengthComputable = init?.lengthComputable || false + this.composed = init?.composed || false + this.loaded = init?.loaded || 0 + this.total = init?.total || 0 + } +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/concatArrayBuffer.ts b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/concatArrayBuffer.ts new file mode 100644 index 0000000000000000000000000000000000000000..e8b9fb46606a36ebf169aaf45b9e0a3864010bb3 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/concatArrayBuffer.ts @@ -0,0 +1,12 @@ +/** + * Concatenate two `Uint8Array` buffers. + */ +export function concatArrayBuffer( + left: Uint8Array, + right: Uint8Array +): Uint8Array { + const result = new Uint8Array(left.byteLength + right.byteLength) + result.set(left, 0) + result.set(right, left.byteLength) + return result +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/concateArrayBuffer.test.ts b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/concateArrayBuffer.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..fab59abd6225d4c8e6671a1a2c208fff88ceba07 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/concateArrayBuffer.test.ts @@ -0,0 +1,12 @@ +import { it, expect } from 'vitest' +import { concatArrayBuffer } from './concatArrayBuffer' + +const encoder = new TextEncoder() + +it('concatenates two Uint8Array buffers', () => { + const result = concatArrayBuffer( + encoder.encode('hello'), + encoder.encode('world') + ) + expect(result).toEqual(encoder.encode('helloworld')) +}) diff --git a/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/createEvent.test.ts b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/createEvent.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..0b23216913ebdc16e6c5749e007da19201aba589 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/createEvent.test.ts @@ -0,0 +1,26 @@ +// @vitest-environment jsdom +import { it, expect } from 'vitest' +import { createEvent } from './createEvent' +import { EventPolyfill } from '../polyfills/EventPolyfill' + +const request = new XMLHttpRequest() +request.open('POST', '/user') + +it('returns an EventPolyfill instance with the given target set', () => { + const event = createEvent(request, 'my-event') + const target = event.target as XMLHttpRequest + + expect(event).toBeInstanceOf(EventPolyfill) + expect(target).toBeInstanceOf(XMLHttpRequest) +}) + +it('returns the ProgressEvent instance', () => { + const event = createEvent(request, 'load', { + loaded: 100, + total: 500, + }) + + expect(event).toBeInstanceOf(ProgressEvent) + expect(event.loaded).toBe(100) + expect(event.total).toBe(500) +}) diff --git a/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/createEvent.ts b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/createEvent.ts new file mode 100644 index 0000000000000000000000000000000000000000..93358c9cf8da74802075213cf4737fe69125e4f7 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/createEvent.ts @@ -0,0 +1,41 @@ +import { EventPolyfill } from '../polyfills/EventPolyfill' +import { ProgressEventPolyfill } from '../polyfills/ProgressEventPolyfill' + +const SUPPORTS_PROGRESS_EVENT = typeof ProgressEvent !== 'undefined' + +export function createEvent( + target: XMLHttpRequest, + type: string, + init?: ProgressEventInit +): EventPolyfill { + const progressEvents = [ + 'error', + 'progress', + 'loadstart', + 'loadend', + 'load', + 'timeout', + 'abort', + ] + + /** + * `ProgressEvent` is not supported in React Native. + * @see https://github.com/mswjs/interceptors/issues/40 + */ + const ProgressEventClass = SUPPORTS_PROGRESS_EVENT + ? ProgressEvent + : ProgressEventPolyfill + + const event = progressEvents.includes(type) + ? new ProgressEventClass(type, { + lengthComputable: true, + loaded: init?.loaded || 0, + total: init?.total || 0, + }) + : new EventPolyfill(type, { + target, + currentTarget: target, + }) + + return event +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/createResponse.ts b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/createResponse.ts new file mode 100644 index 0000000000000000000000000000000000000000..9859c44f26f69aa7d6c88be89f4fce832a7907fb --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/createResponse.ts @@ -0,0 +1,46 @@ +import { isResponseWithoutBody } from '../../../utils/responseUtils' + +/** + * Creates a Fetch API `Response` instance from the given + * `XMLHttpRequest` instance and a response body. + */ +export function createResponse( + request: XMLHttpRequest, + body: BodyInit | null +): Response { + /** + * Handle XMLHttpRequest responses that must have null as the + * response body when represented using Fetch API Response. + * XMLHttpRequest response will always have an empty string + * as the "request.response" in those cases, resulting in an error + * when constructing a Response instance. + * @see https://github.com/mswjs/interceptors/issues/379 + */ + const responseBodyOrNull = isResponseWithoutBody(request.status) ? null : body + + return new Response(responseBodyOrNull, { + status: request.status, + statusText: request.statusText, + headers: createHeadersFromXMLHttpReqestHeaders( + request.getAllResponseHeaders() + ), + }) +} + +function createHeadersFromXMLHttpReqestHeaders(headersString: string): Headers { + const headers = new Headers() + + const lines = headersString.split(/[\r\n]+/) + for (const line of lines) { + if (line.trim() === '') { + continue + } + + const [name, ...parts] = line.split(': ') + const value = parts.join(': ') + + headers.append(name, value) + } + + return headers +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/isDomParserSupportedType.ts b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/isDomParserSupportedType.ts new file mode 100644 index 0000000000000000000000000000000000000000..3cf18b04002ed477d343e4a5a058a66766eebb3c --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/isDomParserSupportedType.ts @@ -0,0 +1,14 @@ +export function isDomParserSupportedType( + type: string +): type is DOMParserSupportedType { + const supportedTypes: Array = [ + 'application/xhtml+xml', + 'application/xml', + 'image/svg+xml', + 'text/html', + 'text/xml', + ] + return supportedTypes.some((supportedType) => { + return type.startsWith(supportedType) + }) +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/fetch/index.ts b/node_modules/@mswjs/interceptors/src/interceptors/fetch/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..efd91e017935dfadd0a00a3858b013fd560879d7 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/fetch/index.ts @@ -0,0 +1,279 @@ +import { invariant } from 'outvariant' +import { DeferredPromise } from '@open-draft/deferred-promise' +import { until } from '@open-draft/until' +import { HttpRequestEventMap, IS_PATCHED_MODULE } from '../../glossary' +import { Interceptor } from '../../Interceptor' +import { toInteractiveRequest } from '../../utils/toInteractiveRequest' +import { emitAsync } from '../../utils/emitAsync' +import { canParseUrl } from '../../utils/canParseUrl' +import { createRequestId } from '../../createRequestId' +import { + createServerErrorResponse, + isResponseError, +} from '../../utils/responseUtils' + +export class FetchInterceptor extends Interceptor { + static symbol = Symbol('fetch') + + constructor() { + super(FetchInterceptor.symbol) + } + + protected checkEnvironment() { + return ( + typeof globalThis !== 'undefined' && + typeof globalThis.fetch !== 'undefined' + ) + } + + protected async setup() { + const pureFetch = globalThis.fetch + + invariant( + !(pureFetch as any)[IS_PATCHED_MODULE], + 'Failed to patch the "fetch" module: already patched.' + ) + + globalThis.fetch = async (input, init) => { + const requestId = createRequestId() + + /** + * @note Resolve potentially relative request URL + * against the present `location`. This is mainly + * for native `fetch` in JSDOM. + * @see https://github.com/mswjs/msw/issues/1625 + */ + const resolvedInput = + typeof input === 'string' && + typeof location !== 'undefined' && + !canParseUrl(input) + ? new URL(input, location.origin) + : input + + const request = new Request(resolvedInput, init) + + this.logger.info('[%s] %s', request.method, request.url) + + const { interactiveRequest, requestController } = + toInteractiveRequest(request) + + this.logger.info( + 'emitting the "request" event for %d listener(s)...', + this.emitter.listenerCount('request') + ) + + this.emitter.once('request', ({ requestId: pendingRequestId }) => { + if (pendingRequestId !== requestId) { + return + } + + if (requestController.responsePromise.state === 'pending') { + requestController.responsePromise.resolve(undefined) + } + }) + + this.logger.info('awaiting for the mocked response...') + + const signal = interactiveRequest.signal + const requestAborted = new DeferredPromise() + + // Signal isn't always defined in react-native. + if (signal) { + signal.addEventListener( + 'abort', + () => { + requestAborted.reject(signal.reason) + }, + { once: true } + ) + } + + const responsePromise = new DeferredPromise() + + const respondWith = (response: Response): void => { + this.logger.info('responding with a mock response:', response) + + if (this.emitter.listenerCount('response') > 0) { + this.logger.info('emitting the "response" event...') + + // Clone the mocked response for the "response" event listener. + // This way, the listener can read the response and not lock its body + // for the actual fetch consumer. + const responseClone = response.clone() + + this.emitter.emit('response', { + response: responseClone, + isMockedResponse: true, + request: interactiveRequest, + requestId, + }) + } + + // Set the "response.url" property to equal the intercepted request URL. + Object.defineProperty(response, 'url', { + writable: false, + enumerable: true, + configurable: false, + value: request.url, + }) + + responsePromise.resolve(response) + } + + const errorWith = (reason: unknown): void => { + responsePromise.reject(reason) + } + + const resolverResult = await until( + async () => { + const listenersFinished = emitAsync(this.emitter, 'request', { + request: interactiveRequest, + requestId, + }) + + await Promise.race([ + requestAborted, + // Put the listeners invocation Promise in the same race condition + // with the request abort Promise because otherwise awaiting the listeners + // would always yield some response (or undefined). + listenersFinished, + requestController.responsePromise, + ]) + + this.logger.info('all request listeners have been resolved!') + + const mockedResponse = await requestController.responsePromise + this.logger.info('event.respondWith called with:', mockedResponse) + + return mockedResponse + } + ) + + if (requestAborted.state === 'rejected') { + this.logger.info( + 'request has been aborted:', + requestAborted.rejectionReason + ) + + responsePromise.reject(requestAborted.rejectionReason) + return responsePromise + } + + if (resolverResult.error) { + this.logger.info( + 'request listerner threw an error:', + resolverResult.error + ) + + // Treat thrown Responses as mocked responses. + if (resolverResult.error instanceof Response) { + // Treat thrown Response.error() as a request error. + if (isResponseError(resolverResult.error)) { + errorWith(createNetworkError(resolverResult.error)) + } else { + // Treat the rest of thrown Responses as mocked responses. + respondWith(resolverResult.error) + } + } + + // Emit the "unhandledException" interceptor event so the client + // can opt-out from exceptions translating to 500 error responses. + + if (this.emitter.listenerCount('unhandledException') > 0) { + await emitAsync(this.emitter, 'unhandledException', { + error: resolverResult.error, + request, + requestId, + controller: { + respondWith, + errorWith, + }, + }) + + if (responsePromise.state !== 'pending') { + return responsePromise + } + } + + // Unhandled exceptions in the request listeners are + // synonymous to unhandled exceptions on the server. + // Those are represented as 500 error responses. + respondWith(createServerErrorResponse(resolverResult.error)) + return responsePromise + } + + const mockedResponse = resolverResult.data + + if (mockedResponse && !request.signal?.aborted) { + this.logger.info('received mocked response:', mockedResponse) + + // Reject the request Promise on mocked "Response.error" responses. + if (isResponseError(mockedResponse)) { + this.logger.info( + 'received a network error response, rejecting the request promise...' + ) + + /** + * Set the cause of the request promise rejection to the + * network error Response instance. This differs from Undici. + * Undici will forward the "response.error" custom property + * as the rejection reason but for "Response.error()" static method + * "response.error" will equal to undefined, making "cause" an empty Error. + * @see https://github.com/nodejs/undici/blob/83cb522ae0157a19d149d72c7d03d46e34510d0a/lib/fetch/response.js#L344 + */ + errorWith(createNetworkError(mockedResponse)) + } else { + respondWith(mockedResponse) + } + + return responsePromise + } + + this.logger.info('no mocked response received!') + + return pureFetch(request).then((response) => { + this.logger.info('original fetch performed', response) + + if (this.emitter.listenerCount('response') > 0) { + this.logger.info('emitting the "response" event...') + + const responseClone = response.clone() + + this.emitter.emit('response', { + response: responseClone, + isMockedResponse: false, + request: interactiveRequest, + requestId, + }) + } + + return response + }) + } + + Object.defineProperty(globalThis.fetch, IS_PATCHED_MODULE, { + enumerable: true, + configurable: true, + value: true, + }) + + this.subscriptions.push(() => { + Object.defineProperty(globalThis.fetch, IS_PATCHED_MODULE, { + value: undefined, + }) + + globalThis.fetch = pureFetch + + this.logger.info( + 'restored native "globalThis.fetch"!', + globalThis.fetch.name + ) + }) + } +} + +function createNetworkError(cause: unknown) { + return Object.assign(new TypeError('Failed to fetch'), { + cause, + }) +} diff --git a/node_modules/@mswjs/interceptors/src/presets/browser.ts b/node_modules/@mswjs/interceptors/src/presets/browser.ts new file mode 100644 index 0000000000000000000000000000000000000000..c609adc5e7dca8993d68109684d12455f468a456 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/presets/browser.ts @@ -0,0 +1,11 @@ +import { FetchInterceptor } from '../interceptors/fetch' +import { XMLHttpRequestInterceptor } from '../interceptors/XMLHttpRequest' + +/** + * The default preset provisions the interception of requests + * regardless of their type (fetch/XMLHttpRequest). + */ +export default [ + new FetchInterceptor(), + new XMLHttpRequestInterceptor(), +] as const diff --git a/node_modules/@mswjs/interceptors/src/presets/node.ts b/node_modules/@mswjs/interceptors/src/presets/node.ts new file mode 100644 index 0000000000000000000000000000000000000000..53317f1b3700e97c5d0bcdefdf558c3f2c9147b2 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/presets/node.ts @@ -0,0 +1,11 @@ +import { ClientRequestInterceptor } from '../interceptors/ClientRequest' +import { XMLHttpRequestInterceptor } from '../interceptors/XMLHttpRequest' + +/** + * The default preset provisions the interception of requests + * regardless of their type (http/https/XMLHttpRequest). + */ +export default [ + new ClientRequestInterceptor(), + new XMLHttpRequestInterceptor(), +] as const diff --git a/node_modules/@mswjs/interceptors/src/utils/RequestController.ts b/node_modules/@mswjs/interceptors/src/utils/RequestController.ts new file mode 100644 index 0000000000000000000000000000000000000000..d93e70b3d5e43604f65d3ca8ecb22ef6f396e094 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/RequestController.ts @@ -0,0 +1,21 @@ +import { invariant } from 'outvariant' +import { DeferredPromise } from '@open-draft/deferred-promise' + +export class RequestController { + public responsePromise: DeferredPromise + + constructor(protected request: Request) { + this.responsePromise = new DeferredPromise() + } + + public respondWith(response?: Response): void { + invariant( + this.responsePromise.state === 'pending', + 'Failed to respond to "%s %s" request: the "request" event has already been responded to.', + this.request.method, + this.request.url + ) + + this.responsePromise.resolve(response) + } +} diff --git a/node_modules/@mswjs/interceptors/src/utils/bufferUtils.test.ts b/node_modules/@mswjs/interceptors/src/utils/bufferUtils.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..7c554556164da88a34dfced42ee641e1a8ed590c --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/bufferUtils.test.ts @@ -0,0 +1,21 @@ +import { it, expect } from 'vitest' +import { decodeBuffer, encodeBuffer } from './bufferUtils' + +it('encodes utf-8 string', () => { + const encoded = encodeBuffer('😁') + expect(new Uint8Array(encoded)).toEqual(new Uint8Array([240, 159, 152, 129])) +}) + +it('decodes utf-8 string', () => { + const array = new Uint8Array([240, 159, 152, 129]) + const decoded = decodeBuffer(array.buffer) + expect(decoded).toEqual('😁') +}) + +it('decodes string with custom encoding', () => { + const array = new Uint8Array([ + 207, 240, 232, 226, 229, 242, 44, 32, 236, 232, 240, 33, + ]) + const decoded = decodeBuffer(array.buffer, 'windows-1251') + expect(decoded).toEqual('Привет, мир!') +}) diff --git a/node_modules/@mswjs/interceptors/src/utils/bufferUtils.ts b/node_modules/@mswjs/interceptors/src/utils/bufferUtils.ts new file mode 100644 index 0000000000000000000000000000000000000000..b4b1c3784d2859669e6e209234d974bb0a2d3784 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/bufferUtils.ts @@ -0,0 +1,22 @@ +const encoder = new TextEncoder() + +export function encodeBuffer(text: string): Uint8Array { + return encoder.encode(text) +} + +export function decodeBuffer(buffer: ArrayBuffer, encoding?: string): string { + const decoder = new TextDecoder(encoding) + return decoder.decode(buffer) +} + +/** + * Create an `ArrayBuffer` from the given `Uint8Array`. + * Takes the byte offset into account to produce the right buffer + * in the case when the buffer is bigger than the data view. + */ +export function toArrayBuffer(array: Uint8Array): ArrayBuffer { + return array.buffer.slice( + array.byteOffset, + array.byteOffset + array.byteLength + ) +} diff --git a/node_modules/@mswjs/interceptors/src/utils/canParseUrl.ts b/node_modules/@mswjs/interceptors/src/utils/canParseUrl.ts new file mode 100644 index 0000000000000000000000000000000000000000..7f814cd5269c9779271770971bba049e7304dd04 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/canParseUrl.ts @@ -0,0 +1,13 @@ +/** + * Returns a boolean indicating whether the given URL string + * can be parsed into a `URL` instance. + * A substitute for `URL.canParse()` for Node.js 18. + */ +export function canParseUrl(url: string): boolean { + try { + new URL(url) + return true + } catch (_error) { + return false + } +} diff --git a/node_modules/@mswjs/interceptors/src/utils/cloneObject.test.ts b/node_modules/@mswjs/interceptors/src/utils/cloneObject.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..85a1dbbb3f32f70005390ab883a93f5553136a5c --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/cloneObject.test.ts @@ -0,0 +1,94 @@ +import { it, expect } from 'vitest' +import { cloneObject } from './cloneObject' + +it('clones a shallow object', () => { + const original = { a: 1, b: 2, c: [1, 2, 3] } + const clone = cloneObject(original) + + expect(clone).toEqual(original) + + clone.a = 5 + clone.b = 6 + clone.c = [5, 6, 7] + + expect(clone).toHaveProperty('a', 5) + expect(clone).toHaveProperty('b', 6) + expect(clone).toHaveProperty('c', [5, 6, 7]) + expect(original).toHaveProperty('a', 1) + expect(original).toHaveProperty('b', 2) + expect(original).toHaveProperty('c', [1, 2, 3]) +}) + +it('clones a nested object', () => { + const original = { a: { b: 1 }, c: { d: { e: 2 } } } + const clone = cloneObject(original) + + expect(clone).toEqual(original) + + clone.a.b = 10 + clone.c.d.e = 20 + + expect(clone).toHaveProperty(['a', 'b'], 10) + expect(clone).toHaveProperty(['c', 'd', 'e'], 20) + expect(original).toHaveProperty(['a', 'b'], 1) + expect(original).toHaveProperty(['c', 'd', 'e'], 2) +}) + +it('clones a class instance', () => { + class Car { + public manufacturer: string + constructor() { + this.manufacturer = 'Audi' + } + getManufacturer() { + return this.manufacturer + } + } + + const car = new Car() + const clone = cloneObject(car) + + expect(clone).toHaveProperty('manufacturer', 'Audi') + expect(clone).toHaveProperty('getManufacturer') + expect(clone.getManufacturer).toBeInstanceOf(Function) + expect(clone.getManufacturer()).toEqual('Audi') +}) + +it('ignores nested class instances', () => { + class Car { + name: string + constructor(name: string) { + this.name = name + } + getName() { + return this.name + } + } + const original = { + a: 1, + car: new Car('Audi'), + } + const clone = cloneObject(original) + + expect(clone).toEqual(original) + expect(clone.car).toBeInstanceOf(Car) + expect(clone.car.getName()).toEqual('Audi') + + clone.car = new Car('BMW') + + expect(clone.car).toBeInstanceOf(Car) + expect(clone.car.getName()).toEqual('BMW') + expect(original.car).toBeInstanceOf(Car) + expect(original.car.getName()).toEqual('Audi') +}) + +it('clones an object with null prototype', () => { + const original = { + key: Object.create(null), + } + const clone = cloneObject(original) + + expect(clone).toEqual({ + key: {}, + }) +}) diff --git a/node_modules/@mswjs/interceptors/src/utils/cloneObject.ts b/node_modules/@mswjs/interceptors/src/utils/cloneObject.ts new file mode 100644 index 0000000000000000000000000000000000000000..521f2ea0032dfae61a1254ce734254303dc1ba89 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/cloneObject.ts @@ -0,0 +1,36 @@ +import { Logger } from '@open-draft/logger' + +const logger = new Logger('cloneObject') + +function isPlainObject(obj?: Record): boolean { + logger.info('is plain object?', obj) + + if (obj == null || !obj.constructor?.name) { + logger.info('given object is undefined, not a plain object...') + return false + } + + logger.info('checking the object constructor:', obj.constructor.name) + return obj.constructor.name === 'Object' +} + +export function cloneObject>( + obj: ObjectType +): ObjectType { + logger.info('cloning object:', obj) + + const enumerableProperties = Object.entries(obj).reduce>( + (acc, [key, value]) => { + logger.info('analyzing key-value pair:', key, value) + + // Recursively clone only plain objects, omitting class instances. + acc[key] = isPlainObject(value) ? cloneObject(value) : value + return acc + }, + {} + ) + + return isPlainObject(obj) + ? enumerableProperties + : Object.assign(Object.getPrototypeOf(obj), enumerableProperties) +} diff --git a/node_modules/@mswjs/interceptors/src/utils/createProxy.test.ts b/node_modules/@mswjs/interceptors/src/utils/createProxy.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..0688aacc3bb64a15d45a61348a1f20a21e12383d --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/createProxy.test.ts @@ -0,0 +1,162 @@ +import { vi, it, expect } from 'vitest' +import { createProxy } from './createProxy' + +it('does not interfere with default constructors', () => { + const ProxyClass = createProxy( + class { + constructor(public name: string) {} + }, + {} + ) + + const instance = new ProxyClass('John') + expect(instance.name).toBe('John') +}) + +it('does not interfere with default getters', () => { + const proxy = createProxy({ foo: 'initial' }, {}) + expect(proxy.foo).toBe('initial') +}) + +it('does not interfere with default setters', () => { + const proxy = createProxy({ foo: 'initial' }, {}) + proxy.foo = 'next' + + expect(proxy.foo).toBe('next') +}) + +it('does not interfere with default methods', () => { + const proxy = createProxy({ getValue: () => 'initial' }, {}) + expect(proxy.getValue()).toBe('initial') +}) + +it('does not interfere with existing descriptors', () => { + const target = {} as { foo: string; bar: number } + let internalBar = 0 + + Object.defineProperties(target, { + foo: { + get: () => 'initial', + }, + bar: { + set: (value) => { + internalBar = value + 10 + }, + }, + }) + + const proxy = createProxy(target, { + getProperty(data, next) { + return next() + }, + }) + expect(proxy.foo).toBe('initial') + + proxy.bar = 5 + expect(proxy.bar).toBeUndefined() + expect(internalBar).toBe(15) +}) + +it('infer prototype descriptors', () => { + class Child { + ok: boolean + + set status(nextStatus: number) { + this.ok = nextStatus >= 200 && nextStatus < 300 + } + } + + Object.defineProperties(Child.prototype, { + status: { enumerable: true }, + }) + + const scope = {} as { child: typeof Child } + + Object.defineProperty(scope, 'child', { + enumerable: true, + value: Child, + }) + + const ProxyClass = createProxy(scope.child, {}) + const instance = new ProxyClass() + + instance.status = 201 + expect(instance.ok).toBe(true) +}) + +it('spies on the constructor', () => { + const OriginalClass = class { + constructor(public name: string, public age: number) {} + } + + const constructorCall = vi.fn< + [ConstructorParameters, Function], + typeof OriginalClass + >((args, next) => next()) + + const ProxyClass = createProxy(OriginalClass, { + constructorCall, + }) + + new ProxyClass('John', 32) + + expect(constructorCall).toHaveBeenCalledTimes(1) + expect(constructorCall).toHaveBeenCalledWith( + ['John', 32], + expect.any(Function) + ) +}) + +it('spies on property getters', () => { + const getProperty = vi.fn((args, next) => next()) + const proxy = createProxy({ foo: 'initial' }, { getProperty }) + + proxy.foo + + expect(getProperty).toHaveBeenCalledTimes(1) + expect(getProperty).toHaveBeenCalledWith(['foo', proxy], expect.any(Function)) +}) + +it('spies on property setters', () => { + const setProperty = vi.fn((args, next) => next()) + const proxy = createProxy({ foo: 'initial' }, { setProperty }) + + proxy.foo = 'next' + + expect(setProperty).toHaveBeenCalledTimes(1) + expect(setProperty).toHaveBeenCalledWith( + ['foo', 'next'], + expect.any(Function) + ) +}) + +it('spies on method calls', () => { + const methodCall = vi.fn((args, next) => next()) + const proxy = createProxy( + { + greet: (name: string) => `hello ${name}`, + }, + { methodCall } + ) + + proxy.greet('Clair') + + expect(methodCall).toHaveBeenCalledTimes(1) + expect(methodCall).toHaveBeenCalledWith( + ['greet', ['Clair']], + expect.any(Function) + ) +}) + +it('proxies properties on the prototype level', () => { + const method = vi.fn() + const prototype = { method } + + const proxy = createProxy(Object.create(prototype), {}) + const proxyMethod = vi.fn() + proxy.method = proxyMethod + + prototype.method() + expect(method).toHaveBeenCalledTimes(0) + expect(proxyMethod).toHaveBeenCalledTimes(1) +}) diff --git a/node_modules/@mswjs/interceptors/src/utils/createProxy.ts b/node_modules/@mswjs/interceptors/src/utils/createProxy.ts new file mode 100644 index 0000000000000000000000000000000000000000..054e752437f1059fa43804fb354beaad68393977 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/createProxy.ts @@ -0,0 +1,104 @@ +import { findPropertySource } from './findPropertySource' + +export interface ProxyOptions> { + constructorCall?(args: Array, next: NextFunction): Target + + methodCall?( + this: Target, + data: [methodName: F, args: Array], + next: NextFunction + ): void + + setProperty?( + data: [propertyName: string | symbol, nextValue: unknown], + next: NextFunction + ): boolean + + getProperty?( + data: [propertyName: string | symbol, receiver: Target], + next: NextFunction + ): void +} + +export type NextFunction = () => ReturnType + +export function createProxy( + target: Target, + options: ProxyOptions +): Target { + const proxy = new Proxy(target, optionsToProxyHandler(options)) + + return proxy +} + +function optionsToProxyHandler>( + options: ProxyOptions +): ProxyHandler { + const { constructorCall, methodCall, getProperty, setProperty } = options + const handler: ProxyHandler = {} + + if (typeof constructorCall !== 'undefined') { + handler.construct = function (target, args, newTarget) { + const next = Reflect.construct.bind(null, target as any, args, newTarget) + return constructorCall.call(newTarget, args, next) + } + } + + handler.set = function (target, propertyName, nextValue) { + const next = () => { + const propertySource = findPropertySource(target, propertyName) || target + const ownDescriptors = Reflect.getOwnPropertyDescriptor( + propertySource, + propertyName + ) + + // Respect any custom setters present for this property. + if (typeof ownDescriptors?.set !== 'undefined') { + ownDescriptors.set.apply(target, [nextValue]) + return true + } + + // Otherwise, set the property on the source. + return Reflect.defineProperty(propertySource, propertyName, { + writable: true, + enumerable: true, + configurable: true, + value: nextValue, + }) + } + + if (typeof setProperty !== 'undefined') { + return setProperty.call(target, [propertyName, nextValue], next) + } + + return next() + } + + handler.get = function (target, propertyName, receiver) { + /** + * @note Using `Reflect.get()` here causes "TypeError: Illegal invocation". + */ + const next = () => target[propertyName as any] + + const value = + typeof getProperty !== 'undefined' + ? getProperty.call(target, [propertyName, receiver], next) + : next() + + if (typeof value === 'function') { + return (...args: Array) => { + const next = value.bind(target, ...args) + + if (typeof methodCall !== 'undefined') { + return methodCall.call(target, [propertyName as any, args], next) + } + + return next() + } + } + + return value + } + + return handler +} diff --git a/node_modules/@mswjs/interceptors/src/utils/emitAsync.ts b/node_modules/@mswjs/interceptors/src/utils/emitAsync.ts new file mode 100644 index 0000000000000000000000000000000000000000..09b43fcbee12f0a63580d13b6e4c2353be5656e8 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/emitAsync.ts @@ -0,0 +1,25 @@ +import { Emitter, EventMap } from 'strict-event-emitter' + +/** + * Emits an event on the given emitter but executes + * the listeners sequentially. This accounts for asynchronous + * listeners (e.g. those having "sleep" and handling the request). + */ +export async function emitAsync< + Events extends EventMap, + EventName extends keyof Events +>( + emitter: Emitter, + eventName: EventName, + ...data: Events[EventName] +): Promise { + const listners = emitter.listeners(eventName) + + if (listners.length === 0) { + return + } + + for (const listener of listners) { + await listener.apply(emitter, data) + } +} diff --git a/node_modules/@mswjs/interceptors/src/utils/findPropertySource.test.ts b/node_modules/@mswjs/interceptors/src/utils/findPropertySource.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..cce02ca9eb099feda1cdde43b0f29e82f715323c --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/findPropertySource.test.ts @@ -0,0 +1,27 @@ +import { it, expect } from 'vitest' +import { findPropertySource } from './findPropertySource' + +it('returns the source for objects without prototypes', () => { + const obj = Object.create(null) + obj.test = undefined + const source = findPropertySource(obj, 'test') + expect(source).toBe(obj) +}) + +it('returns the source for objects with prototypes', () => { + const prototype = Object.create(null) + prototype.test = undefined + + const obj = Object.create(prototype) + + const source = findPropertySource(obj, 'test') + expect(source).toBe(prototype) +}) + +it('returns null if the prototype chain does not contain the property', () => { + const prototype = Object.create(null) + const obj = Object.create(prototype) + + const source = findPropertySource(obj, 'test') + expect(source).toBeNull() +}) diff --git a/node_modules/@mswjs/interceptors/src/utils/findPropertySource.ts b/node_modules/@mswjs/interceptors/src/utils/findPropertySource.ts new file mode 100644 index 0000000000000000000000000000000000000000..26ca44af82e00e5feb046e5ee8dab2339d5fc35d --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/findPropertySource.ts @@ -0,0 +1,20 @@ +/** + * Returns the source object of the given property on the target object + * (the target itself, any parent in its prototype, or null). + */ +export function findPropertySource( + target: object, + propertyName: string | symbol +): object | null { + if (!(propertyName in target)) { + return null + } + + const hasProperty = Object.prototype.hasOwnProperty.call(target, propertyName) + if (hasProperty) { + return target + } + + const prototype = Reflect.getPrototypeOf(target) + return prototype ? findPropertySource(prototype, propertyName) : null +} diff --git a/node_modules/@mswjs/interceptors/src/utils/getCleanUrl.test.ts b/node_modules/@mswjs/interceptors/src/utils/getCleanUrl.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..9f70ca81d5e08954b9e7c6cf3499a9862170fb67 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/getCleanUrl.test.ts @@ -0,0 +1,32 @@ +import { describe, it, expect } from 'vitest' +import { getCleanUrl } from './getCleanUrl' + +describe('getCleanUrl', () => { + describe('given a URL without query parameters', () => { + it('should return url href as-is', () => { + const url = new URL('https://github.com') + expect(getCleanUrl(url)).toEqual('https://github.com/') + }) + }) + + describe('given a URL with query parameters', () => { + it('should return url without parameters', () => { + const url = new URL('https://github.com/mswjs/?userId=abc-123') + expect(getCleanUrl(url)).toEqual('https://github.com/mswjs/') + }) + }) + + describe('given a URL with a hash', () => { + it('should return a url without hash', () => { + const url = new URL('https://github.com/mswjs/#hello-world') + expect(getCleanUrl(url)).toEqual('https://github.com/mswjs/') + }) + }) + + describe('given an absolute URL ', () => { + it('should return a clean relative URL', () => { + const url = new URL('/login?query=value', 'https://github.com') + expect(getCleanUrl(url, false)).toEqual('/login') + }) + }) +}) diff --git a/node_modules/@mswjs/interceptors/src/utils/getCleanUrl.ts b/node_modules/@mswjs/interceptors/src/utils/getCleanUrl.ts new file mode 100644 index 0000000000000000000000000000000000000000..14165674a3dc626a1445e7d117edc639b05e839a --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/getCleanUrl.ts @@ -0,0 +1,6 @@ +/** + * Removes query parameters and hashes from a given URL. + */ +export function getCleanUrl(url: URL, isAbsolute: boolean = true): string { + return [isAbsolute && url.origin, url.pathname].filter(Boolean).join('') +} diff --git a/node_modules/@mswjs/interceptors/src/utils/getRawFetchHeaders.test.ts b/node_modules/@mswjs/interceptors/src/utils/getRawFetchHeaders.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..d86026534105e3f3d09c78e8afd6dcbaeee55b0a --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/getRawFetchHeaders.test.ts @@ -0,0 +1,50 @@ +import { it, expect } from 'vitest' +import { getRawFetchHeaders } from './getRawFetchHeaders' + +it('returns undefined given a non-Headers object', () => { + expect(getRawFetchHeaders({} as Headers)).toBeUndefined() +}) + +it('returns an empty Map given an empty Headers instance', () => { + expect(getRawFetchHeaders(new Headers())).toEqual(new Map()) +}) + +it('returns undefined for headers map on older Node.js versions', () => { + // Emulate the Headers symbol structure on older + // versions of Node.js (e.g. 18.8.0). + const headers = { + [Symbol('headers list')]: { + [Symbol('headers map')]: new Map([['header-name', 'header-value']]), + }, + } + expect(getRawFetchHeaders(headers as unknown as Headers)).toBeUndefined() +}) + +it('returns raw headers from the given Headers instance', () => { + expect( + getRawFetchHeaders( + new Headers([ + ['lowercase-header', 'one'], + ['UPPERCASE-HEADER', 'TWO'], + ['MiXeD-cAsE-hEaDeR', 'ThReE'], + ]) + ) + ).toEqual( + new Map([ + ['lowercase-header', 'one'], + ['UPPERCASE-HEADER', 'TWO'], + ['MiXeD-cAsE-hEaDeR', 'ThReE'], + ]) + ) +}) + +it('returns raw headers for a header with multiple values', () => { + expect( + getRawFetchHeaders( + new Headers([ + ['Set-CookiE', 'a=b'], + ['Set-CookiE', 'c=d'], + ]) + ) + ).toEqual(new Map([['Set-CookiE', 'a=b, c=d']])) +}) diff --git a/node_modules/@mswjs/interceptors/src/utils/getRawFetchHeaders.ts b/node_modules/@mswjs/interceptors/src/utils/getRawFetchHeaders.ts new file mode 100644 index 0000000000000000000000000000000000000000..4870b6c3700d7d917b11974fafd9d09643826b06 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/getRawFetchHeaders.ts @@ -0,0 +1,56 @@ +import { getValueBySymbol } from './getValueBySymbol' +import { isObject } from './isObject' + +type RawHeadersMap = Map +type HeadersMapHeader = { name: string; value: string } + +/** + * Returns raw headers from the given `Headers` instance. + * @example + * const headers = new Headers([ + * ['X-HeadeR-NamE', 'Value'] + * ]) + * getRawFetchHeaders(headers) + * // { 'X-HeadeR-NamE': 'Value' } + */ +export function getRawFetchHeaders( + headers: Headers +): RawHeadersMap | undefined { + const headersList = getValueBySymbol('headers list', headers) + + if (!headersList) { + return + } + + const headersMap = getValueBySymbol< + Map | Map + >('headers map', headersList) + + /** + * @note Older versions of Node.js (e.g. 18.8.0) keep headers map + * as Map without any means to tap + * into raw header values. Detect that and return undefined. + */ + if (!headersMap || !isHeadersMapWithRawHeaderNames(headersMap)) { + return + } + + // Raw headers is a map of { rawHeaderName: rawHeaderValue } + const rawHeaders: RawHeadersMap = new Map() + + headersMap.forEach(({ name, value }) => { + rawHeaders.set(name, value) + }) + + return rawHeaders +} + +function isHeadersMapWithRawHeaderNames( + headersMap: Map | Map +): headersMap is Map { + return Array.from( + headersMap.values() as Iterable + ).every((value) => { + return isObject(value) && 'name' in value + }) +} diff --git a/node_modules/@mswjs/interceptors/src/utils/getRequestOptionsByUrl.ts b/node_modules/@mswjs/interceptors/src/utils/getRequestOptionsByUrl.ts new file mode 100644 index 0000000000000000000000000000000000000000..33eeeacaf8f060c744c9d057ec0956ebf30a71d9 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/getRequestOptionsByUrl.ts @@ -0,0 +1,29 @@ +import { RequestOptions } from 'http' + +/** + * Converts a URL instance into the RequestOptions object expected by + * the `ClientRequest` class. + * @see https://github.com/nodejs/node/blob/908292cf1f551c614a733d858528ffb13fb3a524/lib/internal/url.js#L1257 + */ +export function getRequestOptionsByUrl(url: URL): RequestOptions { + const options: RequestOptions = { + method: 'GET', + protocol: url.protocol, + hostname: + typeof url.hostname === 'string' && url.hostname.startsWith('[') + ? url.hostname.slice(1, -1) + : url.hostname, + host: url.host, + path: `${url.pathname}${url.search || ''}`, + } + + if (!!url.port) { + options.port = Number(url.port) + } + + if (url.username || url.password) { + options.auth = `${url.username}:${url.password}` + } + + return options +} diff --git a/node_modules/@mswjs/interceptors/src/utils/getUrlByRequestOptions.test.ts b/node_modules/@mswjs/interceptors/src/utils/getUrlByRequestOptions.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..cc9423609d32be0399fb0ace18f5891f461c1f67 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/getUrlByRequestOptions.test.ts @@ -0,0 +1,163 @@ +import { it, expect } from 'vitest' +import { Agent as HttpAgent } from 'http' +import { RequestOptions, Agent as HttpsAgent } from 'https' +import { getUrlByRequestOptions } from './getUrlByRequestOptions' + +it('returns a URL based on the basic RequestOptions', () => { + expect( + getUrlByRequestOptions({ + protocol: 'https:', + host: '127.0.0.1', + path: '/resource', + }).href + ).toBe('https://127.0.0.1/resource') +}) + +it('inherits protocol and port from http.Agent, if set', () => { + expect( + getUrlByRequestOptions({ + host: '127.0.0.1', + path: '/', + agent: new HttpAgent(), + }).href + ).toBe('http://127.0.0.1/') +}) + +it('inherits protocol and port from https.Agent, if set', () => { + expect( + getUrlByRequestOptions({ + host: '127.0.0.1', + path: '/', + agent: new HttpsAgent({ + port: 3080, + }), + }).href + ).toBe('https://127.0.0.1:3080/') +}) + +it('resolves protocol to "http" given no explicit protocol and no certificate', () => { + expect( + getUrlByRequestOptions({ + host: '127.0.0.1', + path: '/', + }).href + ).toBe('http://127.0.0.1/') +}) + +it('resolves protocol to "https" given no explicit protocol, but certificate', () => { + expect( + getUrlByRequestOptions({ + host: '127.0.0.1', + path: '/secure', + cert: '', + }).href + ).toBe('https://127.0.0.1/secure') +}) + +it('resolves protocol to "https" given no explicit protocol, but port is 443', () => { + expect( + getUrlByRequestOptions({ + host: '127.0.0.1', + port: 443, + path: '/resource', + }).href + ).toBe('https://127.0.0.1/resource') +}) + +it('resolves protocol to "https" given no explicit protocol, but agent port is 443', () => { + expect( + getUrlByRequestOptions({ + host: '127.0.0.1', + agent: new HttpsAgent({ + port: 443, + }), + path: '/resource', + }).href + ).toBe('https://127.0.0.1/resource') +}) + +it('respects explicitly provided port', () => { + expect( + getUrlByRequestOptions({ + protocol: 'http:', + host: '127.0.0.1', + port: 4002, + path: '/', + }).href + ).toBe('http://127.0.0.1:4002/') +}) + +it('inherits "username" and "password"', () => { + const url = getUrlByRequestOptions({ + protocol: 'https:', + host: '127.0.0.1', + path: '/user', + auth: 'admin:abc-123', + }) + + expect(url).toBeInstanceOf(URL) + expect(url).toHaveProperty('username', 'admin') + expect(url).toHaveProperty('password', 'abc-123') + expect(url).toHaveProperty('href', 'https://admin:abc-123@127.0.0.1/user') +}) + +it('resolves hostname to localhost if none provided', () => { + expect(getUrlByRequestOptions({}).hostname).toBe('localhost') +}) + +it('resolves host to localhost if none provided', () => { + expect(getUrlByRequestOptions({}).host).toBe('localhost') +}) + +it('supports "hostname" and "port"', () => { + const options: RequestOptions = { + protocol: 'https:', + hostname: '127.0.0.1', + port: 1234, + path: '/resource', + } + + expect(getUrlByRequestOptions(options).href).toBe( + 'https://127.0.0.1:1234/resource' + ) +}) + +it('use "hostname" if both "hostname" and "host" are specified', () => { + const options: RequestOptions = { + protocol: 'https:', + host: 'host', + hostname: 'hostname', + path: '/resource', + } + + expect(getUrlByRequestOptions(options).href).toBe( + 'https://hostname/resource' + ) +}) + +it('parses "host" in IPv6', () => { + expect( + getUrlByRequestOptions({ + host: '::1', + path: '/resource', + }).href + ).toBe('http://[::1]/resource') + + expect( + getUrlByRequestOptions({ + host: '[::1]', + path: '/resource', + }).href + ).toBe('http://[::1]/resource') + +}) + +it('parses "host" and "port" in IPv6', () => { + expect( + getUrlByRequestOptions({ + host: '::1', + port: 3001, + path: '/resource', + }).href + ).toBe('http://[::1]:3001/resource') +}) diff --git a/node_modules/@mswjs/interceptors/src/utils/getUrlByRequestOptions.ts b/node_modules/@mswjs/interceptors/src/utils/getUrlByRequestOptions.ts new file mode 100644 index 0000000000000000000000000000000000000000..0b8a5ef76010de2a957bbdc0b54b783b5cd9b836 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/getUrlByRequestOptions.ts @@ -0,0 +1,152 @@ +import { Agent } from 'http' +import { RequestOptions, Agent as HttpsAgent } from 'https' +import { Logger } from '@open-draft/logger' + +const logger = new Logger('utils getUrlByRequestOptions') + +// Request instance constructed by the "request" library +// has a "self" property that has a "uri" field. This is +// reproducible by performing a "XMLHttpRequest" request in JSDOM. +export interface RequestSelf { + uri?: URL +} + +export type ResolvedRequestOptions = RequestOptions & RequestSelf + +export const DEFAULT_PATH = '/' +const DEFAULT_PROTOCOL = 'http:' +const DEFAULT_HOSTNAME = 'localhost' +const SSL_PORT = 443 + +function getAgent( + options: ResolvedRequestOptions +): Agent | HttpsAgent | undefined { + return options.agent instanceof Agent ? options.agent : undefined +} + +function getProtocolByRequestOptions(options: ResolvedRequestOptions): string { + if (options.protocol) { + return options.protocol + } + + const agent = getAgent(options) + const agentProtocol = (agent as RequestOptions)?.protocol + + if (agentProtocol) { + return agentProtocol + } + + const port = getPortByRequestOptions(options) + const isSecureRequest = options.cert || port === SSL_PORT + + return isSecureRequest ? 'https:' : options.uri?.protocol || DEFAULT_PROTOCOL +} + +function getPortByRequestOptions( + options: ResolvedRequestOptions +): number | undefined { + // Use the explicitly provided port. + if (options.port) { + return Number(options.port) + } + + // Otherwise, try to resolve port from the agent. + const agent = getAgent(options) + + if ((agent as HttpsAgent)?.options.port) { + return Number((agent as HttpsAgent).options.port) + } + + if ((agent as RequestOptions)?.defaultPort) { + return Number((agent as RequestOptions).defaultPort) + } + + // Lastly, return undefined indicating that the port + // must inferred from the protocol. Do not infer it here. + return undefined +} + +interface RequestAuth { + username: string + password: string +} + +function getAuthByRequestOptions( + options: ResolvedRequestOptions +): RequestAuth | undefined { + if (options.auth) { + const [username, password] = options.auth.split(':') + return { username, password } + } +} + +/** + * Returns true if host looks like an IPv6 address without surrounding brackets + * It assumes any host containing `:` is definitely not IPv4 and probably IPv6, + * but note that this could include invalid IPv6 addresses as well. + */ +function isRawIPv6Address(host: string): boolean { + return host.includes(':') && !host.startsWith('[') && !host.endsWith(']') +} + +function getHostname(options: ResolvedRequestOptions): string | undefined { + let host = options.hostname || options.host + + if (host) { + if (isRawIPv6Address(host)) { + host = `[${host}]` + } + + // Check the presence of the port, and if it's present, + // remove it from the host, returning a hostname. + return new URL(`http://${host}`).hostname + } + + return DEFAULT_HOSTNAME +} + +/** + * Creates a `URL` instance from a given `RequestOptions` object. + */ +export function getUrlByRequestOptions(options: ResolvedRequestOptions): URL { + logger.info('request options', options) + + if (options.uri) { + logger.info( + 'constructing url from explicitly provided "options.uri": %s', + options.uri + ) + return new URL(options.uri.href) + } + + logger.info('figuring out url from request options...') + + const protocol = getProtocolByRequestOptions(options) + logger.info('protocol', protocol) + + const port = getPortByRequestOptions(options) + logger.info('port', port) + + const hostname = getHostname(options) + logger.info('hostname', hostname) + + const path = options.path || DEFAULT_PATH + logger.info('path', path) + + const credentials = getAuthByRequestOptions(options) + logger.info('credentials', credentials) + + const authString = credentials + ? `${credentials.username}:${credentials.password}@` + : '' + logger.info('auth string:', authString) + + const portString = typeof port !== 'undefined' ? `:${port}` : '' + const url = new URL(`${protocol}//${hostname}${portString}${path}`) + url.username = credentials?.username || '' + url.password = credentials?.password || '' + + logger.info('created url:', url) + + return url +} diff --git a/node_modules/@mswjs/interceptors/src/utils/getValueBySymbol.test.ts b/node_modules/@mswjs/interceptors/src/utils/getValueBySymbol.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..9e2b21c8ceda848d594162356257be11555811d4 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/getValueBySymbol.test.ts @@ -0,0 +1,14 @@ +import { it, expect } from 'vitest' +import { getValueBySymbol } from './getValueBySymbol' + +it('returns undefined given a non-existing symbol', () => { + expect(getValueBySymbol('non-existing', {})).toBeUndefined() +}) + +it('returns value behind the given symbol', () => { + const symbol = Symbol('kInternal') + + expect(getValueBySymbol('kInternal', { [symbol]: null })).toBe(null) + expect(getValueBySymbol('kInternal', { [symbol]: true })).toBe(true) + expect(getValueBySymbol('kInternal', { [symbol]: 'value' })).toBe('value') +}) diff --git a/node_modules/@mswjs/interceptors/src/utils/getValueBySymbol.ts b/node_modules/@mswjs/interceptors/src/utils/getValueBySymbol.ts new file mode 100644 index 0000000000000000000000000000000000000000..2c2e9541f44094b2e07b35154aeae9a2cc1a813c --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/getValueBySymbol.ts @@ -0,0 +1,19 @@ +/** + * Returns the value behind the symbol with the given name. + */ +export function getValueBySymbol( + symbolName: string, + source: object +): T | undefined { + const ownSymbols = Object.getOwnPropertySymbols(source) + + const symbol = ownSymbols.find((symbol) => { + return symbol.description === symbolName + }) + + if (symbol) { + return Reflect.get(source, symbol) + } + + return +} diff --git a/node_modules/@mswjs/interceptors/src/utils/isNodeLikeError.ts b/node_modules/@mswjs/interceptors/src/utils/isNodeLikeError.ts new file mode 100644 index 0000000000000000000000000000000000000000..f74dea789c9fd82fece9a8e57495f5fefc410bc1 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/isNodeLikeError.ts @@ -0,0 +1,13 @@ +export function isNodeLikeError( + error: unknown +): error is NodeJS.ErrnoException { + if (error == null) { + return false + } + + if (!(error instanceof Error)) { + return false + } + + return 'code' in error && 'errno' in error +} diff --git a/node_modules/@mswjs/interceptors/src/utils/isObject.test.ts b/node_modules/@mswjs/interceptors/src/utils/isObject.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..ea4e99d60a605eb74731c51d405e3dee30845ca5 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/isObject.test.ts @@ -0,0 +1,21 @@ +import { it, expect } from 'vitest' +import { isObject } from './isObject' + +it('returns true given an object', () => { + expect(isObject({})).toBe(true) + expect(isObject({ a: 1 })).toBe(true) +}) + +it('returns false given an object-like instance', () => { + expect(isObject([1])).toBe(false) + expect(isObject(function () {})).toBe(false) + expect(isObject(new Response())).toBe(false) +}) + +it('returns false given a non-object instance', () => { + expect(isObject(null)).toBe(false) + expect(isObject(undefined)).toBe(false) + expect(isObject(false)).toBe(false) + expect(isObject(123)).toBe(false) + expect(isObject(Symbol('object Object'))).toBe(false) +}) diff --git a/node_modules/@mswjs/interceptors/src/utils/isObject.ts b/node_modules/@mswjs/interceptors/src/utils/isObject.ts new file mode 100644 index 0000000000000000000000000000000000000000..096e12ea52e8fdefe0819d5717506a8d1a36707a --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/isObject.ts @@ -0,0 +1,8 @@ +/** + * Determines if a given value is an instance of object. + */ +export function isObject(value: any, loose = false): value is T { + return loose + ? Object.prototype.toString.call(value).startsWith('[object ') + : Object.prototype.toString.call(value) === '[object Object]' +} diff --git a/node_modules/@mswjs/interceptors/src/utils/isPropertyAccessible.ts b/node_modules/@mswjs/interceptors/src/utils/isPropertyAccessible.ts new file mode 100644 index 0000000000000000000000000000000000000000..4a80a75bc4b635f6d1e8ea2c8e01756f56da4bb5 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/isPropertyAccessible.ts @@ -0,0 +1,19 @@ +/** + * A function that validates if property access is possible on an object + * without throwing. It returns `true` if the property access is possible + * and `false` otherwise. + * + * Environments like miniflare will throw on property access on certain objects + * like Request and Response, for unimplemented properties. + */ +export function isPropertyAccessible>( + obj: Obj, + key: keyof Obj +) { + try { + obj[key] + return true + } catch { + return false + } +} diff --git a/node_modules/@mswjs/interceptors/src/utils/nextTick.ts b/node_modules/@mswjs/interceptors/src/utils/nextTick.ts new file mode 100644 index 0000000000000000000000000000000000000000..a080ca1e1f34f4a440497765d1509403b55025ed --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/nextTick.ts @@ -0,0 +1,11 @@ +export function nextTick(callback: () => void) { + setTimeout(callback, 0) +} + +export function nextTickAsync(callback: () => void) { + return new Promise((resolve) => { + setTimeout(() => { + resolve(callback()) + }, 0) + }) +} diff --git a/node_modules/@mswjs/interceptors/src/utils/parseJson.test.ts b/node_modules/@mswjs/interceptors/src/utils/parseJson.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..b0210348163aceceeb7bf077250bb5f7e5143eb2 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/parseJson.test.ts @@ -0,0 +1,10 @@ +import { it, expect } from 'vitest' +import { parseJson } from './parseJson' + +it('parses a given string into JSON', () => { + expect(parseJson('{"id":1}')).toEqual({ id: 1 }) +}) + +it('returns null given invalid JSON string', () => { + expect(parseJson('{"o:2\'')).toBeNull() +}) diff --git a/node_modules/@mswjs/interceptors/src/utils/parseJson.ts b/node_modules/@mswjs/interceptors/src/utils/parseJson.ts new file mode 100644 index 0000000000000000000000000000000000000000..af8d2e6da6e09485911865eba28b239db6fa26b1 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/parseJson.ts @@ -0,0 +1,12 @@ +/** + * Parses a given string into JSON. + * Gracefully handles invalid JSON by returning `null`. + */ +export function parseJson(data: string): Record | null { + try { + const json = JSON.parse(data) + return json + } catch (_) { + return null + } +} diff --git a/node_modules/@mswjs/interceptors/src/utils/responseUtils.ts b/node_modules/@mswjs/interceptors/src/utils/responseUtils.ts new file mode 100644 index 0000000000000000000000000000000000000000..e07b85be4ca635ea83f3e04cb0fdf1ab46299d30 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/responseUtils.ts @@ -0,0 +1,55 @@ +import { isPropertyAccessible } from './isPropertyAccessible' + +/** + * Response status codes for responses that cannot have body. + * @see https://fetch.spec.whatwg.org/#statuses + */ +export const RESPONSE_STATUS_CODES_WITHOUT_BODY = new Set([ + 101, 103, 204, 205, 304, +]) + +/** + * Returns a boolean indicating whether the given response status + * code represents a response that cannot have a body. + */ +export function isResponseWithoutBody(status: number): boolean { + return RESPONSE_STATUS_CODES_WITHOUT_BODY.has(status) +} + +/** + * Creates a generic 500 Unhandled Exception response. + */ +export function createServerErrorResponse(body: unknown): Response { + return new Response( + JSON.stringify( + body instanceof Error + ? { + name: body.name, + message: body.message, + stack: body.stack, + } + : body + ), + { + status: 500, + statusText: 'Unhandled Exception', + headers: { + 'Content-Type': 'application/json', + }, + } + ) +} + +/** + * Checks if the given response is a `Response.error()`. + * + * @note Some environments, like Miniflare (Cloudflare) do not + * implement the "Response.type" property and throw on its access. + * Safely check if we can access "type" on "Response" before continuing. + * @see https://github.com/mswjs/msw/issues/1834 + */ +export function isResponseError( + response: Response +): response is Response & { type: 'error' } { + return isPropertyAccessible(response, 'type') && response.type === 'error' +} diff --git a/node_modules/@mswjs/interceptors/src/utils/toInteractiveRequest.ts b/node_modules/@mswjs/interceptors/src/utils/toInteractiveRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..00064a646e06ade945cf5ce70477296a89873c78 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/toInteractiveRequest.ts @@ -0,0 +1,23 @@ +import { RequestController } from './RequestController' + +export type InteractiveRequest = globalThis.Request & { + respondWith: RequestController['respondWith'] +} + +export function toInteractiveRequest(request: Request): { + interactiveRequest: InteractiveRequest + requestController: RequestController +} { + const requestController = new RequestController(request) + + Reflect.set( + request, + 'respondWith', + requestController.respondWith.bind(requestController) + ) + + return { + interactiveRequest: request as InteractiveRequest, + requestController, + } +} diff --git a/node_modules/@open-draft/deferred-promise/README.md b/node_modules/@open-draft/deferred-promise/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e19d242ab6ebde58cbb679f472efa0acef4bcdf5 --- /dev/null +++ b/node_modules/@open-draft/deferred-promise/README.md @@ -0,0 +1,191 @@ +# Deferred Promise + +The `DeferredPromise` class is a Promise-compatible abstraction that defers resolving/rejecting promises to another closure. This class is primarily useful when one part of your system establishes as promise but another part of your system fulfills it. + +> This class is conceptually inspired by the [`createDeferredPromise()`](https://github.com/nodejs/node/blob/696fd4b14fc34cc2d01497a3abd9bb441b89be50/lib/internal/util.js#L468-L477) internal utility in Node.js. Unlike the Node.js implementation, however, `DeferredProimse` _extends_ a native `Promise`, allowing the consumer to handle deferred promises like regular promises (no `.promise` instance nesting). + +## Getting started + +```sh +npm install @open-draft/deferred-promise +``` + +## Documentation + +- [**`createDeferredExecutor()`**](#createdeferredexecutor) + - [`DeferredExecutor.state`](#deferredexecutorstate) + - [`DeferredExecutor.resolve()`](#deferredexecutorresolve) + - [`DeferredExecutor.reject()`](#deferredexecutorreject) + - [`DeferredExecutor.rejectionReason`](#deferredexecutorrejectionreason) +- [**Class: `DeferredPromise`**](#class-deferredpromise) + - [`new DeferredPromise()`](#new-defferedpromise) + - [`deferredPromise.state`](#deferredpromisestate) + - [`deferredPromise.resolve()`](#deferredpromiseresolve) + - [`deferredPromise.reject()`](#deferredpromisereject) + - [`deferredPromise.rejectionReason`](#deferredpromiserejectionreason) + +--- + +## `createDeferredExecutor()` + +Creates a Promise executor function that delegates its resolution to the current scope. + +```js +import { createDeferredExecutor } from '@open-draft/deferred-promise' + +const executor = createDeferredExecutor() +const promise = new Promise(executor) + +executor.resolve('hello') +// executor.reject(new Error('Reason')) +``` + +Deferred executor allows you to control any promise remotely and doesn't affect the Promise instance in any way. Similar to the [`DeferredPromise`](#class-deferredpromise) instance, the deferred executor exposes additional promise properties like `state`, `rejectionReason`, `resolve`, and `reject`. In fact, the `DeferredPromise` class is implemented on top of the deferred executor. + +```js +const executor = createDeferredExecutor() +const promise = new Promise(executor) + +executor.reject('reason') + +nextTick(() => { + console.log(executor.rejectionReason) // "reason" +}) +``` + +### `DeferredExecutor.state` + +- `<"pending" | "fulfilled" | "rejected">` **Default:** `"pending"` + +```js +const executor = createDeferredExecutor() +const promise = new Promise(executor) + +console.log(executor.state) // "pending" +``` + +Calling [`resolve()`](#deferredexecutorresolve) and [`reject()`](#deferredexecutorreject) methods of the executor transitions the state to "fulfilled" and "rejected" respectively. + +### `DeferredExecutor.resolve()` + +Resolves the promise with a given value. + +```js +const executor = createDeferredExecutor() +const promise = new Promise(executor) + +console.log(executor.state) // "pending" + +executor.resolve() + +// The promise state is still "pending" +// because promises are settled in the next microtask. +console.log(executor.state) // "pending" + +nextTick(() => { + // In the next microtask, the promise's state is resolved. + console.log(executor.state) // "fulfilled" +}) +``` + +### `DeferredExecutor.reject()` + +Rejects the promise with a given reason. + +```js +const executor = createDeferredExecutor() +const promise = new Promise(executor) + +executor.reject(new Error('Failed to fetch')) + +nextTick(() => { + console.log(executor.state) // "rejected" + console.log(executor.rejectionReason) // Error("Failed to fetch") +}) +``` + +You can access the rejection reason of the promise at any time by the [`rejectionReason`](#deferredexecutorrejectionreason) property of the deferred executor. + +### `DeferredExecutor.rejectionReason` + +Returns the reason of the promise rejection. If no reason has been provided to the `reject()` call, `undefined` is returned instead. + +```js +const executor = createDeferredExecutor() +const promise = new Promise(executor) + +promise.reject(new Error('Internal Server Error')) + +nextTick(() => { + console.log(promise.rejectionReason) // Error("Internal Server Error") +}) +``` + +--- + +## Class: `DeferredPromise` + +### `new DefferedPromise()` + +Creates a new instance of a deferred promise. + +```js +import { DeferredPromise } from '@open-draft/deferred-promise' + +const promise = new DeferredPromise() +``` + +A deferred promise is a Promise-compatible class that constructs a regular Promise instance under the hood, controlling it via the [deferred executor](#createdeferredexecutor). + +A deferred promise is fully compatible with the regular Promise, both type- and runtime-wise, e.g. a deferred promise can be chained and awaited normally. + +```js +const promise = new DefferredPromise() + .then((value) => value.toUpperCase()) + .then((value) => value.substring(0, 2)) + .catch((error) => console.error(error)) + +await promise +``` + +Unlike the regular Promise, however, a deferred promise doesn't accept the `executor` function as the constructor argument. Instead, the resolution of the deferred promise is deferred to the current scope (thus the name). + +```js +function getPort() { + // Notice that you don't provide any executor function + // when constructing a deferred promise. + const portPromise = new DeferredPromise() + + port.on('open', (port) => { + // Resolve the deferred promise whenever necessary. + portPromise.resolve(port) + }) + + // Return the deferred promise immediately. + return portPromise +} +``` + +Use the [`resolve()`](#deferredpromiseresolve) and [`reject()`](#deferredpromisereject) methods of the deferred promise instance to resolve and reject that promise respectively. + +### `deferredPromise.state` + +See [`DeferredExecutor.state`](#deferredexecutorstate) + +### `deferredPromise.resolve()` + +See [`DeferredExecutor.resolve()`](#deferredexecutorresolve) + +### `deferredPromise.reject()` + +See [`DeferredExecutor.reject()`](#deferredexecutorreject) + +### `deferredPromise.rejectionReason` + +See [`DeferredExecutor.rejectionReason`](#deferredexecutorrejectionreason) + +--- + +## Mentions + +- [Jonas Kuske](https://github.com/jonaskuske) for the phenomenal work around improving Promise-compliance. diff --git a/node_modules/@open-draft/deferred-promise/build/index.d.mts b/node_modules/@open-draft/deferred-promise/build/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..f4206473c47a52a6aef67d841aaa65168ad467a7 --- /dev/null +++ b/node_modules/@open-draft/deferred-promise/build/index.d.mts @@ -0,0 +1,27 @@ +declare type PromiseState = 'pending' | 'fulfilled' | 'rejected'; +declare type Executor = ConstructorParameters>[0]; +declare type ResolveFunction = Parameters>[0]; +declare type RejectFunction = Parameters>[1]; +declare type DeferredPromiseExecutor = { + (resolve?: ResolveFunction, reject?: RejectFunction): void; + resolve: ResolveFunction; + reject: RejectFunction; + result?: Output; + state: PromiseState; + rejectionReason?: unknown; +}; +declare function createDeferredExecutor(): DeferredPromiseExecutor; + +declare class DeferredPromise extends Promise { + #private; + resolve: ResolveFunction; + reject: RejectFunction; + constructor(executor?: Executor | null); + get state(): PromiseState; + get rejectionReason(): unknown; + then(onFulfilled?: (value: Input) => ThenResult | PromiseLike, onRejected?: (reason: any) => CatchResult | PromiseLike): DeferredPromise; + catch(onRejected?: (reason: any) => CatchResult | PromiseLike): DeferredPromise; + finally(onfinally?: () => void | Promise): DeferredPromise; +} + +export { DeferredPromise, DeferredPromiseExecutor, Executor, PromiseState, RejectFunction, ResolveFunction, createDeferredExecutor }; diff --git a/node_modules/@open-draft/deferred-promise/build/index.d.ts b/node_modules/@open-draft/deferred-promise/build/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f4206473c47a52a6aef67d841aaa65168ad467a7 --- /dev/null +++ b/node_modules/@open-draft/deferred-promise/build/index.d.ts @@ -0,0 +1,27 @@ +declare type PromiseState = 'pending' | 'fulfilled' | 'rejected'; +declare type Executor = ConstructorParameters>[0]; +declare type ResolveFunction = Parameters>[0]; +declare type RejectFunction = Parameters>[1]; +declare type DeferredPromiseExecutor = { + (resolve?: ResolveFunction, reject?: RejectFunction): void; + resolve: ResolveFunction; + reject: RejectFunction; + result?: Output; + state: PromiseState; + rejectionReason?: unknown; +}; +declare function createDeferredExecutor(): DeferredPromiseExecutor; + +declare class DeferredPromise extends Promise { + #private; + resolve: ResolveFunction; + reject: RejectFunction; + constructor(executor?: Executor | null); + get state(): PromiseState; + get rejectionReason(): unknown; + then(onFulfilled?: (value: Input) => ThenResult | PromiseLike, onRejected?: (reason: any) => CatchResult | PromiseLike): DeferredPromise; + catch(onRejected?: (reason: any) => CatchResult | PromiseLike): DeferredPromise; + finally(onfinally?: () => void | Promise): DeferredPromise; +} + +export { DeferredPromise, DeferredPromiseExecutor, Executor, PromiseState, RejectFunction, ResolveFunction, createDeferredExecutor }; diff --git a/node_modules/@open-draft/deferred-promise/build/index.js b/node_modules/@open-draft/deferred-promise/build/index.js new file mode 100644 index 0000000000000000000000000000000000000000..8612d834cc1d55e2e8e9f49df6c57087ae3084f7 --- /dev/null +++ b/node_modules/@open-draft/deferred-promise/build/index.js @@ -0,0 +1,99 @@ +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); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + DeferredPromise: () => DeferredPromise, + createDeferredExecutor: () => createDeferredExecutor +}); +module.exports = __toCommonJS(src_exports); + +// src/createDeferredExecutor.ts +function createDeferredExecutor() { + const executor = (resolve, reject) => { + executor.state = "pending"; + executor.resolve = (data) => { + if (executor.state !== "pending") { + return; + } + executor.result = data; + const onFulfilled = (value) => { + executor.state = "fulfilled"; + return value; + }; + return resolve( + data instanceof Promise ? data : Promise.resolve(data).then(onFulfilled) + ); + }; + executor.reject = (reason) => { + if (executor.state !== "pending") { + return; + } + queueMicrotask(() => { + executor.state = "rejected"; + }); + return reject(executor.rejectionReason = reason); + }; + }; + return executor; +} + +// src/DeferredPromise.ts +var DeferredPromise = class extends Promise { + #executor; + resolve; + reject; + constructor(executor = null) { + const deferredExecutor = createDeferredExecutor(); + super((originalResolve, originalReject) => { + deferredExecutor(originalResolve, originalReject); + executor?.(deferredExecutor.resolve, deferredExecutor.reject); + }); + this.#executor = deferredExecutor; + this.resolve = this.#executor.resolve; + this.reject = this.#executor.reject; + } + get state() { + return this.#executor.state; + } + get rejectionReason() { + return this.#executor.rejectionReason; + } + then(onFulfilled, onRejected) { + return this.#decorate(super.then(onFulfilled, onRejected)); + } + catch(onRejected) { + return this.#decorate(super.catch(onRejected)); + } + finally(onfinally) { + return this.#decorate(super.finally(onfinally)); + } + #decorate(promise) { + return Object.defineProperties(promise, { + resolve: { configurable: true, value: this.resolve }, + reject: { configurable: true, value: this.reject } + }); + } +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + DeferredPromise, + createDeferredExecutor +}); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@open-draft/deferred-promise/build/index.js.map b/node_modules/@open-draft/deferred-promise/build/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..55123c69bffa33aa648e4e4b08890b271e83a7b8 --- /dev/null +++ b/node_modules/@open-draft/deferred-promise/build/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/index.ts","../src/createDeferredExecutor.ts","../src/DeferredPromise.ts"],"sourcesContent":["export * from './createDeferredExecutor'\nexport * from './DeferredPromise'\n","export type PromiseState = 'pending' | 'fulfilled' | 'rejected'\n\nexport type Executor = ConstructorParameters>[0]\nexport type ResolveFunction = Parameters>[0]\nexport type RejectFunction = Parameters>[1]\n\nexport type DeferredPromiseExecutor = {\n (resolve?: ResolveFunction, reject?: RejectFunction): void\n\n resolve: ResolveFunction\n reject: RejectFunction\n result?: Output\n state: PromiseState\n rejectionReason?: unknown\n}\nexport function createDeferredExecutor<\n Input = never,\n Output = Input\n>(): DeferredPromiseExecutor {\n const executor = >((\n resolve,\n reject\n ) => {\n executor.state = 'pending'\n\n executor.resolve = (data) => {\n if (executor.state !== 'pending') {\n return\n }\n\n executor.result = data as Output\n\n const onFulfilled = (value: Value) => {\n executor.state = 'fulfilled'\n return value\n }\n\n return resolve(\n data instanceof Promise ? data : Promise.resolve(data).then(onFulfilled)\n )\n }\n\n executor.reject = (reason) => {\n if (executor.state !== 'pending') {\n return\n }\n\n queueMicrotask(() => {\n executor.state = 'rejected'\n })\n\n return reject((executor.rejectionReason = reason))\n }\n })\n\n return executor\n}\n","import {\n type Executor,\n type RejectFunction,\n type ResolveFunction,\n type DeferredPromiseExecutor,\n createDeferredExecutor,\n} from './createDeferredExecutor'\n\nexport class DeferredPromise extends Promise {\n #executor: DeferredPromiseExecutor\n\n public resolve: ResolveFunction\n public reject: RejectFunction\n\n constructor(executor: Executor | null = null) {\n const deferredExecutor = createDeferredExecutor()\n super((originalResolve, originalReject) => {\n deferredExecutor(originalResolve, originalReject)\n executor?.(deferredExecutor.resolve, deferredExecutor.reject)\n })\n\n this.#executor = deferredExecutor\n this.resolve = this.#executor.resolve\n this.reject = this.#executor.reject\n }\n\n public get state() {\n return this.#executor.state\n }\n\n public get rejectionReason() {\n return this.#executor.rejectionReason\n }\n\n public then(\n onFulfilled?: (value: Input) => ThenResult | PromiseLike,\n onRejected?: (reason: any) => CatchResult | PromiseLike\n ) {\n return this.#decorate(super.then(onFulfilled, onRejected))\n }\n\n public catch(\n onRejected?: (reason: any) => CatchResult | PromiseLike\n ) {\n return this.#decorate(super.catch(onRejected))\n }\n\n public finally(onfinally?: () => void | Promise) {\n return this.#decorate(super.finally(onfinally))\n }\n\n #decorate(\n promise: Promise\n ): DeferredPromise {\n return Object.defineProperties(promise, {\n resolve: { configurable: true, value: this.resolve },\n reject: { configurable: true, value: this.reject },\n }) as DeferredPromise\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACeO,SAAS,yBAG4B;AAC1C,QAAM,WAAoD,CACxD,SACA,WACG;AACH,aAAS,QAAQ;AAEjB,aAAS,UAAU,CAAC,SAAS;AAC3B,UAAI,SAAS,UAAU,WAAW;AAChC;AAAA,MACF;AAEA,eAAS,SAAS;AAElB,YAAM,cAAc,CAAQ,UAAiB;AAC3C,iBAAS,QAAQ;AACjB,eAAO;AAAA,MACT;AAEA,aAAO;AAAA,QACL,gBAAgB,UAAU,OAAO,QAAQ,QAAQ,IAAI,EAAE,KAAK,WAAW;AAAA,MACzE;AAAA,IACF;AAEA,aAAS,SAAS,CAAC,WAAW;AAC5B,UAAI,SAAS,UAAU,WAAW;AAChC;AAAA,MACF;AAEA,qBAAe,MAAM;AACnB,iBAAS,QAAQ;AAAA,MACnB,CAAC;AAED,aAAO,OAAQ,SAAS,kBAAkB,MAAO;AAAA,IACnD;AAAA,EACF;AAEA,SAAO;AACT;;;AChDO,IAAM,kBAAN,cAAqD,QAAe;AAAA,EACzE;AAAA,EAEO;AAAA,EACA;AAAA,EAEP,YAAY,WAAmC,MAAM;AACnD,UAAM,mBAAmB,uBAAuB;AAChD,UAAM,CAAC,iBAAiB,mBAAmB;AACzC,uBAAiB,iBAAiB,cAAc;AAChD,iBAAW,iBAAiB,SAAS,iBAAiB,MAAM;AAAA,IAC9D,CAAC;AAED,SAAK,YAAY;AACjB,SAAK,UAAU,KAAK,UAAU;AAC9B,SAAK,SAAS,KAAK,UAAU;AAAA,EAC/B;AAAA,EAEA,IAAW,QAAQ;AACjB,WAAO,KAAK,UAAU;AAAA,EACxB;AAAA,EAEA,IAAW,kBAAkB;AAC3B,WAAO,KAAK,UAAU;AAAA,EACxB;AAAA,EAEO,KACL,aACA,YACA;AACA,WAAO,KAAK,UAAU,MAAM,KAAK,aAAa,UAAU,CAAC;AAAA,EAC3D;AAAA,EAEO,MACL,YACA;AACA,WAAO,KAAK,UAAU,MAAM,MAAM,UAAU,CAAC;AAAA,EAC/C;AAAA,EAEO,QAAQ,WAAuC;AACpD,WAAO,KAAK,UAAU,MAAM,QAAQ,SAAS,CAAC;AAAA,EAChD;AAAA,EAEA,UACE,SACqC;AACrC,WAAO,OAAO,iBAAiB,SAAS;AAAA,MACtC,SAAS,EAAE,cAAc,MAAM,OAAO,KAAK,QAAQ;AAAA,MACnD,QAAQ,EAAE,cAAc,MAAM,OAAO,KAAK,OAAO;AAAA,IACnD,CAAC;AAAA,EACH;AACF;","names":[]} \ No newline at end of file diff --git a/node_modules/@open-draft/deferred-promise/build/index.mjs b/node_modules/@open-draft/deferred-promise/build/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a1a05c6cd21df1dc8fc65a8725f8853dbc500420 --- /dev/null +++ b/node_modules/@open-draft/deferred-promise/build/index.mjs @@ -0,0 +1,72 @@ +// src/createDeferredExecutor.ts +function createDeferredExecutor() { + const executor = (resolve, reject) => { + executor.state = "pending"; + executor.resolve = (data) => { + if (executor.state !== "pending") { + return; + } + executor.result = data; + const onFulfilled = (value) => { + executor.state = "fulfilled"; + return value; + }; + return resolve( + data instanceof Promise ? data : Promise.resolve(data).then(onFulfilled) + ); + }; + executor.reject = (reason) => { + if (executor.state !== "pending") { + return; + } + queueMicrotask(() => { + executor.state = "rejected"; + }); + return reject(executor.rejectionReason = reason); + }; + }; + return executor; +} + +// src/DeferredPromise.ts +var DeferredPromise = class extends Promise { + #executor; + resolve; + reject; + constructor(executor = null) { + const deferredExecutor = createDeferredExecutor(); + super((originalResolve, originalReject) => { + deferredExecutor(originalResolve, originalReject); + executor?.(deferredExecutor.resolve, deferredExecutor.reject); + }); + this.#executor = deferredExecutor; + this.resolve = this.#executor.resolve; + this.reject = this.#executor.reject; + } + get state() { + return this.#executor.state; + } + get rejectionReason() { + return this.#executor.rejectionReason; + } + then(onFulfilled, onRejected) { + return this.#decorate(super.then(onFulfilled, onRejected)); + } + catch(onRejected) { + return this.#decorate(super.catch(onRejected)); + } + finally(onfinally) { + return this.#decorate(super.finally(onfinally)); + } + #decorate(promise) { + return Object.defineProperties(promise, { + resolve: { configurable: true, value: this.resolve }, + reject: { configurable: true, value: this.reject } + }); + } +}; +export { + DeferredPromise, + createDeferredExecutor +}; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/@open-draft/deferred-promise/build/index.mjs.map b/node_modules/@open-draft/deferred-promise/build/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..b2340f4a1f44e2de9bc6cd6c9fdcf29a5dae6252 --- /dev/null +++ b/node_modules/@open-draft/deferred-promise/build/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/createDeferredExecutor.ts","../src/DeferredPromise.ts"],"sourcesContent":["export type PromiseState = 'pending' | 'fulfilled' | 'rejected'\n\nexport type Executor = ConstructorParameters>[0]\nexport type ResolveFunction = Parameters>[0]\nexport type RejectFunction = Parameters>[1]\n\nexport type DeferredPromiseExecutor = {\n (resolve?: ResolveFunction, reject?: RejectFunction): void\n\n resolve: ResolveFunction\n reject: RejectFunction\n result?: Output\n state: PromiseState\n rejectionReason?: unknown\n}\nexport function createDeferredExecutor<\n Input = never,\n Output = Input\n>(): DeferredPromiseExecutor {\n const executor = >((\n resolve,\n reject\n ) => {\n executor.state = 'pending'\n\n executor.resolve = (data) => {\n if (executor.state !== 'pending') {\n return\n }\n\n executor.result = data as Output\n\n const onFulfilled = (value: Value) => {\n executor.state = 'fulfilled'\n return value\n }\n\n return resolve(\n data instanceof Promise ? data : Promise.resolve(data).then(onFulfilled)\n )\n }\n\n executor.reject = (reason) => {\n if (executor.state !== 'pending') {\n return\n }\n\n queueMicrotask(() => {\n executor.state = 'rejected'\n })\n\n return reject((executor.rejectionReason = reason))\n }\n })\n\n return executor\n}\n","import {\n type Executor,\n type RejectFunction,\n type ResolveFunction,\n type DeferredPromiseExecutor,\n createDeferredExecutor,\n} from './createDeferredExecutor'\n\nexport class DeferredPromise extends Promise {\n #executor: DeferredPromiseExecutor\n\n public resolve: ResolveFunction\n public reject: RejectFunction\n\n constructor(executor: Executor | null = null) {\n const deferredExecutor = createDeferredExecutor()\n super((originalResolve, originalReject) => {\n deferredExecutor(originalResolve, originalReject)\n executor?.(deferredExecutor.resolve, deferredExecutor.reject)\n })\n\n this.#executor = deferredExecutor\n this.resolve = this.#executor.resolve\n this.reject = this.#executor.reject\n }\n\n public get state() {\n return this.#executor.state\n }\n\n public get rejectionReason() {\n return this.#executor.rejectionReason\n }\n\n public then(\n onFulfilled?: (value: Input) => ThenResult | PromiseLike,\n onRejected?: (reason: any) => CatchResult | PromiseLike\n ) {\n return this.#decorate(super.then(onFulfilled, onRejected))\n }\n\n public catch(\n onRejected?: (reason: any) => CatchResult | PromiseLike\n ) {\n return this.#decorate(super.catch(onRejected))\n }\n\n public finally(onfinally?: () => void | Promise) {\n return this.#decorate(super.finally(onfinally))\n }\n\n #decorate(\n promise: Promise\n ): DeferredPromise {\n return Object.defineProperties(promise, {\n resolve: { configurable: true, value: this.resolve },\n reject: { configurable: true, value: this.reject },\n }) as DeferredPromise\n }\n}\n"],"mappings":";AAeO,SAAS,yBAG4B;AAC1C,QAAM,WAAoD,CACxD,SACA,WACG;AACH,aAAS,QAAQ;AAEjB,aAAS,UAAU,CAAC,SAAS;AAC3B,UAAI,SAAS,UAAU,WAAW;AAChC;AAAA,MACF;AAEA,eAAS,SAAS;AAElB,YAAM,cAAc,CAAQ,UAAiB;AAC3C,iBAAS,QAAQ;AACjB,eAAO;AAAA,MACT;AAEA,aAAO;AAAA,QACL,gBAAgB,UAAU,OAAO,QAAQ,QAAQ,IAAI,EAAE,KAAK,WAAW;AAAA,MACzE;AAAA,IACF;AAEA,aAAS,SAAS,CAAC,WAAW;AAC5B,UAAI,SAAS,UAAU,WAAW;AAChC;AAAA,MACF;AAEA,qBAAe,MAAM;AACnB,iBAAS,QAAQ;AAAA,MACnB,CAAC;AAED,aAAO,OAAQ,SAAS,kBAAkB,MAAO;AAAA,IACnD;AAAA,EACF;AAEA,SAAO;AACT;;;AChDO,IAAM,kBAAN,cAAqD,QAAe;AAAA,EACzE;AAAA,EAEO;AAAA,EACA;AAAA,EAEP,YAAY,WAAmC,MAAM;AACnD,UAAM,mBAAmB,uBAAuB;AAChD,UAAM,CAAC,iBAAiB,mBAAmB;AACzC,uBAAiB,iBAAiB,cAAc;AAChD,iBAAW,iBAAiB,SAAS,iBAAiB,MAAM;AAAA,IAC9D,CAAC;AAED,SAAK,YAAY;AACjB,SAAK,UAAU,KAAK,UAAU;AAC9B,SAAK,SAAS,KAAK,UAAU;AAAA,EAC/B;AAAA,EAEA,IAAW,QAAQ;AACjB,WAAO,KAAK,UAAU;AAAA,EACxB;AAAA,EAEA,IAAW,kBAAkB;AAC3B,WAAO,KAAK,UAAU;AAAA,EACxB;AAAA,EAEO,KACL,aACA,YACA;AACA,WAAO,KAAK,UAAU,MAAM,KAAK,aAAa,UAAU,CAAC;AAAA,EAC3D;AAAA,EAEO,MACL,YACA;AACA,WAAO,KAAK,UAAU,MAAM,MAAM,UAAU,CAAC;AAAA,EAC/C;AAAA,EAEO,QAAQ,WAAuC;AACpD,WAAO,KAAK,UAAU,MAAM,QAAQ,SAAS,CAAC;AAAA,EAChD;AAAA,EAEA,UACE,SACqC;AACrC,WAAO,OAAO,iBAAiB,SAAS;AAAA,MACtC,SAAS,EAAE,cAAc,MAAM,OAAO,KAAK,QAAQ;AAAA,MACnD,QAAQ,EAAE,cAAc,MAAM,OAAO,KAAK,OAAO;AAAA,IACnD,CAAC;AAAA,EACH;AACF;","names":[]} \ No newline at end of file diff --git a/node_modules/@open-draft/deferred-promise/package.json b/node_modules/@open-draft/deferred-promise/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3acdd5e2da9b5c3401ebb9d01b746062d5d5095f --- /dev/null +++ b/node_modules/@open-draft/deferred-promise/package.json @@ -0,0 +1,81 @@ +{ + "_from": "@open-draft/deferred-promise@^2.2.0", + "_id": "@open-draft/deferred-promise@2.2.0", + "_inBundle": false, + "_integrity": "sha512-CecwLWx3rhxVQF6V4bAgPS5t+So2sTbPgAzafKkVizyi7tlwpcFpdFqq+wqF2OwNBmqFuu6tOyouTuxgpMfzmA==", + "_location": "/@open-draft/deferred-promise", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@open-draft/deferred-promise@^2.2.0", + "name": "@open-draft/deferred-promise", + "escapedName": "@open-draft%2fdeferred-promise", + "scope": "@open-draft", + "rawSpec": "^2.2.0", + "saveSpec": null, + "fetchSpec": "^2.2.0" + }, + "_requiredBy": [ + "/@mswjs/interceptors" + ], + "_resolved": "https://registry.npmjs.org/@open-draft/deferred-promise/-/deferred-promise-2.2.0.tgz", + "_shasum": "4a822d10f6f0e316be4d67b4d4f8c9a124b073bd", + "_spec": "@open-draft/deferred-promise@^2.2.0", + "_where": "/Users/sylvainfiloni/Documents/HuggingFace_Projects/live-vision/node_modules/@mswjs/interceptors", + "author": { + "name": "Artem Zakharchenko" + }, + "bugs": { + "url": "https://github.com/open-draft/deferred-promise/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "A Promise-compatible abstraction that defers resolving/rejecting promises to another closure.", + "devDependencies": { + "@ossjs/release": "^0.7.2", + "@types/jest": "^29.0.1", + "jest": "^29.0.3", + "rimraf": "^3.0.2", + "ts-jest": "^29.0.0", + "tsup": "^7.2.0", + "tsx": "^3.12.1", + "typescript": "^4.8.3" + }, + "exports": { + ".": { + "types": "./build/index.d.ts", + "require": "./build/index.js", + "default": "./build/index.mjs" + } + }, + "files": [ + "./build" + ], + "homepage": "https://github.com/open-draft/deferred-promise#readme", + "keywords": [ + "promise", + "defer", + "deferred", + "resolve", + "reject", + "executor" + ], + "license": "MIT", + "main": "./build/index.js", + "module": "./build/index.mjs", + "name": "@open-draft/deferred-promise", + "repository": { + "type": "git", + "url": "git+https://github.com/open-draft/deferred-promise.git" + }, + "scripts": { + "build": "tsup", + "prebuild": "rimraf ./build", + "release": "release publish", + "test": "jest", + "test:compliance": "export NODE_OPTIONS=--loader=tsx || set NODE_OPTIONS=--loader=tsx&& npx -y promises-aplus-tests ./test/aplus-tests-adapter.ts" + }, + "types": "./build/index.d.ts", + "version": "2.2.0" +} diff --git a/node_modules/@open-draft/logger/LICENSE b/node_modules/@open-draft/logger/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..7868ade175ae9284aadfba31049213f58147960e --- /dev/null +++ b/node_modules/@open-draft/logger/LICENSE @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) 2023—present Artem Zakharchenko + +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/node_modules/@open-draft/logger/README.md b/node_modules/@open-draft/logger/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2da7455957610e71785ad3d5885b512eeed52e8a --- /dev/null +++ b/node_modules/@open-draft/logger/README.md @@ -0,0 +1,225 @@ +# Logger + +Environment-agnostic, ESM-friendly logger for simple needs. + +## Why does this exist? + +I've been using `debug` for quite some time but wanted to migrate my projects to better ESM support. Alas, `debug` doesn't ship as ESM so I went and wrote this little logger just for my needs. You will likely see it printing useful data in Mock Service Worker and beyond. + +## Installation + +```sh +npm install @open-draft/logger +``` + +## Usage + +This package has the same API for both browser and Node.js and can run in those environments out of the box. + +```js +// app.js +import { Logger } from '@open-draft/logger' + +const logger = new Logger('parser') + +logger.info('starting parsing...') +logger.warning('found legacy document format') +logger.success('parsed 120 documents!') +``` + +Logging is disabled by default. To enable logging, provide the `DEBUG` environment variable: + +```sh +DEBUG=1 node ./app.js +``` + +> You can also use `true` instead of `1`. You can also use a specific logger's name to enable [logger filtering](#logger-filtering). + +## API + +- Class: `Logger` + - [`new Logger(name)`](#new-loggername) + - [`logger.debug(message, ...positionals)`](#loggerdebugmessage-positionals) + - [`logger.info(message, ...positionals)`](#loggerinfomessage-positionals) + - [`logger.success(message, ...positionals)`](#loggersuccessmessage-positionals) + - [`logger.warning(message, ...positionals)`](#loggerwarningmessage-positionals) + - [`logger.error(message, ...positionals)`](#loggererrormessage-positionals) + - [`logger.extend(name)`](#loggerextendprefix) + - [`logger.only(callback)`](#loggeronlycallback) + +### `new Logger(name)` + +- `name` `string` the name of the logger. + +Creates a new instance of the logger. Each message printed by the logger will be prefixed with the given `name`. You can have multiple loggers with different names for different areas of your system. + +```js +const logger = new Logger('parser') +``` + +> You can nest loggers via [`logger.extend()`](#loggerextendprefix). + +### `logger.debug(message, ...positionals)` + +- `message` `string` +- `positionals` `unknown[]` + +Prints a debug message. + +```js +logger.debug('no duplicates found, skipping...') +``` + +``` +12:34:56:789 [parser] no duplicates found, skipping... +``` + +### `logger.info(message, ...positionals)` + +- `message` `string` +- `positionals` `unknown[]` + +Prints an info message. + +```js +logger.info('new parse request') +``` + +``` +12:34:56:789 [parser] new parse request +``` + +### `logger.success(message, ...positionals)` + +- `message` `string` +- `positionals` `unknown[]` + +Prints a success message. + +```js +logger.success('prased 123 documents!') +``` + +``` +12:34:56:789 ✔ [parser] prased 123 documents! +``` + +### `logger.warning(message, ...positionals)` + +- `message` `string` +- `positionals` `unknown[]` + +Prints a warning. In Node.js, prints it to `process.stderr`. + +```js +logger.warning('found legacy document format') +``` + +``` +12:34:56:789 ⚠ [parser] found legacy document format +``` + +### `logger.error(message, ...positionals)` + +- `message` `string` +- `positionals` `unknown[]` + +Prints an error. In Node.js, prints it to `process.stderr`. + +```js +logger.error('failed to parse document') +``` + +``` +12:34:56:789 ✖ [parser] failed to parse document +``` + +### `logger.extend(prefix)` + +- `prefix` `string` Additional prefix to append to the logger's name. + +Creates a new logger out of the current one. + +```js +const logger = new Logger('parser') + +function parseRequest(request) { + const requestLogger = logger.extend(`${request.method} ${request.url}`) + requestLogger.info('start parsing...') +} +``` + +``` +12:34:56:789 [parser] [GET https://example.com] start parsing... +``` + +### `logger.only(callback)` + +Executes a given callback only when the logging is activated. Useful for computing additional information for logs. + +```js +logger.only(() => { + const documentSize = getSizeBytes(document) + logger.debug(`document size: ${documentSize}`) +}) +``` + +> You can nest `logger.*` methods in the callback to `logger.only()`. + +## Log levels + +You can specify the log levels to print using the `LOG_LEVEL` environment variable. + +There are the following log levels: + +- `debug` +- `info` +- `success` +- `warning` +- `error` + +> Providing no log level will print all the messages. + +Here's an example of how to print only warnings: + +```js +// app.js +import { Logger } from '@open-draft/logger' + +const logger = new Logger('parser') + +logger.info('some info') +logger.warning('some warning') +logger.error('some error') +``` + +```js +LOG_LEVEL=warning node ./app.js +``` + +``` +12:34:56:789 ⚠ [parser] some warning +``` + +## Logger filtering + +You can only print a specific logger by providing its name as the `DEBUG` environment variable. + +```js +// app.js +import { Logger } from '@open-draft/logger' + +const appLogger = new Logger('app') +const parserLogger = new Logger('parser') + +appLogger.info('starting app...') +parserLogger.info('creating a new parser...') +``` + +```sh +DEBUG=app node ./app.js +``` + +``` +12:34:56:789 [app] starting app... +``` diff --git a/node_modules/@open-draft/logger/lib/index.d.ts b/node_modules/@open-draft/logger/lib/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..547acfcd0c5271fd882e66c908996e5e6c71485c --- /dev/null +++ b/node_modules/@open-draft/logger/lib/index.d.ts @@ -0,0 +1,83 @@ +type ColorFunction = (text: string) => void; +declare function yellow(text: string): string; +declare function blue(text: string): string; +declare function gray(text: string): string; +declare function red(text: string): string; +declare function green(text: string): string; + +type colors_ColorFunction = ColorFunction; +declare const colors_blue: typeof blue; +declare const colors_gray: typeof gray; +declare const colors_green: typeof green; +declare const colors_red: typeof red; +declare const colors_yellow: typeof yellow; +declare namespace colors { + export { + colors_ColorFunction as ColorFunction, + colors_blue as blue, + colors_gray as gray, + colors_green as green, + colors_red as red, + colors_yellow as yellow, + }; +} + +type LogLevel = 'debug' | 'info' | 'success' | 'warning' | 'error'; +type LogColors = keyof typeof colors; +interface LogEntry { + timestamp: Date; + level: LogLevel; + message: any; +} +declare class Logger { + private readonly name; + private prefix; + constructor(name: string); + extend(domain: string): Logger; + /** + * Print a debug message. + * @example + * logger.debug('no duplicates found, creating a document...') + */ + debug(message: any, ...positionals: Array): void; + /** + * Print an info message. + * @example + * logger.info('start parsing...') + */ + info(message: any, ...positionals: Array): (message: any, ...positionals: Array) => void; + /** + * Print a success message. + * @example + * logger.success('successfully created document') + */ + success(message: any, ...positionals: Array): void; + /** + * Print a warning. + * @example + * logger.warning('found legacy document format') + */ + warning(message: any, ...positionals: Array): void; + /** + * Print an error message. + * @example + * logger.error('something went wrong') + */ + error(message: any, ...positionals: Array): void; + /** + * Execute the given callback only when the logging is enabled. + * This is skipped in its entirety and has no runtime cost otherwise. + * This executes regardless of the log level. + * @example + * logger.only(() => { + * logger.info('additional info') + * }) + */ + only(callback: () => void): void; + private createEntry; + private logEntry; + private formatTimestamp; + private getWriter; +} + +export { LogColors, LogEntry, LogLevel, Logger }; diff --git a/node_modules/@open-draft/logger/lib/index.js b/node_modules/@open-draft/logger/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ac101aec651bcc45a2cffffcb8e7242a649ce87b --- /dev/null +++ b/node_modules/@open-draft/logger/lib/index.js @@ -0,0 +1,295 @@ +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); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + Logger: () => Logger +}); +module.exports = __toCommonJS(src_exports); +var import_is_node_process = require("is-node-process"); +var import_outvariant = require("outvariant"); + +// src/colors.ts +var colors_exports = {}; +__export(colors_exports, { + blue: () => blue, + gray: () => gray, + green: () => green, + red: () => red, + yellow: () => yellow +}); +function yellow(text) { + return `\x1B[33m${text}\x1B[0m`; +} +function blue(text) { + return `\x1B[34m${text}\x1B[0m`; +} +function gray(text) { + return `\x1B[90m${text}\x1B[0m`; +} +function red(text) { + return `\x1B[31m${text}\x1B[0m`; +} +function green(text) { + return `\x1B[32m${text}\x1B[0m`; +} + +// src/index.ts +var IS_NODE = (0, import_is_node_process.isNodeProcess)(); +var Logger = class { + constructor(name) { + this.name = name; + this.prefix = `[${this.name}]`; + const LOGGER_NAME = getVariable("DEBUG"); + const LOGGER_LEVEL = getVariable("LOG_LEVEL"); + const isLoggingEnabled = LOGGER_NAME === "1" || LOGGER_NAME === "true" || typeof LOGGER_NAME !== "undefined" && this.name.startsWith(LOGGER_NAME); + if (isLoggingEnabled) { + this.debug = isDefinedAndNotEquals(LOGGER_LEVEL, "debug") ? noop : this.debug; + this.info = isDefinedAndNotEquals(LOGGER_LEVEL, "info") ? noop : this.info; + this.success = isDefinedAndNotEquals(LOGGER_LEVEL, "success") ? noop : this.success; + this.warning = isDefinedAndNotEquals(LOGGER_LEVEL, "warning") ? noop : this.warning; + this.error = isDefinedAndNotEquals(LOGGER_LEVEL, "error") ? noop : this.error; + } else { + this.info = noop; + this.success = noop; + this.warning = noop; + this.error = noop; + this.only = noop; + } + } + prefix; + extend(domain) { + return new Logger(`${this.name}:${domain}`); + } + /** + * Print a debug message. + * @example + * logger.debug('no duplicates found, creating a document...') + */ + debug(message, ...positionals) { + this.logEntry({ + level: "debug", + message: gray(message), + positionals, + prefix: this.prefix, + colors: { + prefix: "gray" + } + }); + } + /** + * Print an info message. + * @example + * logger.info('start parsing...') + */ + info(message, ...positionals) { + this.logEntry({ + level: "info", + message, + positionals, + prefix: this.prefix, + colors: { + prefix: "blue" + } + }); + const performance2 = new PerformanceEntry(); + return (message2, ...positionals2) => { + performance2.measure(); + this.logEntry({ + level: "info", + message: `${message2} ${gray(`${performance2.deltaTime}ms`)}`, + positionals: positionals2, + prefix: this.prefix, + colors: { + prefix: "blue" + } + }); + }; + } + /** + * Print a success message. + * @example + * logger.success('successfully created document') + */ + success(message, ...positionals) { + this.logEntry({ + level: "info", + message, + positionals, + prefix: `\u2714 ${this.prefix}`, + colors: { + timestamp: "green", + prefix: "green" + } + }); + } + /** + * Print a warning. + * @example + * logger.warning('found legacy document format') + */ + warning(message, ...positionals) { + this.logEntry({ + level: "warning", + message, + positionals, + prefix: `\u26A0 ${this.prefix}`, + colors: { + timestamp: "yellow", + prefix: "yellow" + } + }); + } + /** + * Print an error message. + * @example + * logger.error('something went wrong') + */ + error(message, ...positionals) { + this.logEntry({ + level: "error", + message, + positionals, + prefix: `\u2716 ${this.prefix}`, + colors: { + timestamp: "red", + prefix: "red" + } + }); + } + /** + * Execute the given callback only when the logging is enabled. + * This is skipped in its entirety and has no runtime cost otherwise. + * This executes regardless of the log level. + * @example + * logger.only(() => { + * logger.info('additional info') + * }) + */ + only(callback) { + callback(); + } + createEntry(level, message) { + return { + timestamp: /* @__PURE__ */ new Date(), + level, + message + }; + } + logEntry(args) { + const { + level, + message, + prefix, + colors: customColors, + positionals = [] + } = args; + const entry = this.createEntry(level, message); + const timestampColor = customColors?.timestamp || "gray"; + const prefixColor = customColors?.prefix || "gray"; + const colorize = { + timestamp: colors_exports[timestampColor], + prefix: colors_exports[prefixColor] + }; + const write = this.getWriter(level); + write( + [colorize.timestamp(this.formatTimestamp(entry.timestamp))].concat(prefix != null ? colorize.prefix(prefix) : []).concat(serializeInput(message)).join(" "), + ...positionals.map(serializeInput) + ); + } + formatTimestamp(timestamp) { + return `${timestamp.toLocaleTimeString( + "en-GB" + )}:${timestamp.getMilliseconds()}`; + } + getWriter(level) { + switch (level) { + case "debug": + case "success": + case "info": { + return log; + } + case "warning": { + return warn; + } + case "error": { + return error; + } + } + } +}; +var PerformanceEntry = class { + startTime; + endTime; + deltaTime; + constructor() { + this.startTime = performance.now(); + } + measure() { + this.endTime = performance.now(); + const deltaTime = this.endTime - this.startTime; + this.deltaTime = deltaTime.toFixed(2); + } +}; +var noop = () => void 0; +function log(message, ...positionals) { + if (IS_NODE) { + process.stdout.write((0, import_outvariant.format)(message, ...positionals) + "\n"); + return; + } + console.log(message, ...positionals); +} +function warn(message, ...positionals) { + if (IS_NODE) { + process.stderr.write((0, import_outvariant.format)(message, ...positionals) + "\n"); + return; + } + console.warn(message, ...positionals); +} +function error(message, ...positionals) { + if (IS_NODE) { + process.stderr.write((0, import_outvariant.format)(message, ...positionals) + "\n"); + return; + } + console.error(message, ...positionals); +} +function getVariable(variableName) { + if (IS_NODE) { + return process.env[variableName]; + } + return globalThis[variableName]?.toString(); +} +function isDefinedAndNotEquals(value, expected) { + return value !== void 0 && value !== expected; +} +function serializeInput(message) { + if (typeof message === "undefined") { + return "undefined"; + } + if (message === null) { + return "null"; + } + if (typeof message === "string") { + return message; + } + if (typeof message === "object") { + return JSON.stringify(message); + } + return message.toString(); +} diff --git a/node_modules/@open-draft/logger/lib/index.mjs b/node_modules/@open-draft/logger/lib/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ffb0b88b7a0ccc22ed7cb106b3b48a10b085df0e --- /dev/null +++ b/node_modules/@open-draft/logger/lib/index.mjs @@ -0,0 +1,281 @@ +var __defProp = Object.defineProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; + +// src/index.ts +import { isNodeProcess } from "is-node-process"; +import { format } from "outvariant"; + +// src/colors.ts +var colors_exports = {}; +__export(colors_exports, { + blue: () => blue, + gray: () => gray, + green: () => green, + red: () => red, + yellow: () => yellow +}); +function yellow(text) { + return `\x1B[33m${text}\x1B[0m`; +} +function blue(text) { + return `\x1B[34m${text}\x1B[0m`; +} +function gray(text) { + return `\x1B[90m${text}\x1B[0m`; +} +function red(text) { + return `\x1B[31m${text}\x1B[0m`; +} +function green(text) { + return `\x1B[32m${text}\x1B[0m`; +} + +// src/index.ts +var IS_NODE = isNodeProcess(); +var Logger = class { + constructor(name) { + this.name = name; + this.prefix = `[${this.name}]`; + const LOGGER_NAME = getVariable("DEBUG"); + const LOGGER_LEVEL = getVariable("LOG_LEVEL"); + const isLoggingEnabled = LOGGER_NAME === "1" || LOGGER_NAME === "true" || typeof LOGGER_NAME !== "undefined" && this.name.startsWith(LOGGER_NAME); + if (isLoggingEnabled) { + this.debug = isDefinedAndNotEquals(LOGGER_LEVEL, "debug") ? noop : this.debug; + this.info = isDefinedAndNotEquals(LOGGER_LEVEL, "info") ? noop : this.info; + this.success = isDefinedAndNotEquals(LOGGER_LEVEL, "success") ? noop : this.success; + this.warning = isDefinedAndNotEquals(LOGGER_LEVEL, "warning") ? noop : this.warning; + this.error = isDefinedAndNotEquals(LOGGER_LEVEL, "error") ? noop : this.error; + } else { + this.info = noop; + this.success = noop; + this.warning = noop; + this.error = noop; + this.only = noop; + } + } + prefix; + extend(domain) { + return new Logger(`${this.name}:${domain}`); + } + /** + * Print a debug message. + * @example + * logger.debug('no duplicates found, creating a document...') + */ + debug(message, ...positionals) { + this.logEntry({ + level: "debug", + message: gray(message), + positionals, + prefix: this.prefix, + colors: { + prefix: "gray" + } + }); + } + /** + * Print an info message. + * @example + * logger.info('start parsing...') + */ + info(message, ...positionals) { + this.logEntry({ + level: "info", + message, + positionals, + prefix: this.prefix, + colors: { + prefix: "blue" + } + }); + const performance2 = new PerformanceEntry(); + return (message2, ...positionals2) => { + performance2.measure(); + this.logEntry({ + level: "info", + message: `${message2} ${gray(`${performance2.deltaTime}ms`)}`, + positionals: positionals2, + prefix: this.prefix, + colors: { + prefix: "blue" + } + }); + }; + } + /** + * Print a success message. + * @example + * logger.success('successfully created document') + */ + success(message, ...positionals) { + this.logEntry({ + level: "info", + message, + positionals, + prefix: `\u2714 ${this.prefix}`, + colors: { + timestamp: "green", + prefix: "green" + } + }); + } + /** + * Print a warning. + * @example + * logger.warning('found legacy document format') + */ + warning(message, ...positionals) { + this.logEntry({ + level: "warning", + message, + positionals, + prefix: `\u26A0 ${this.prefix}`, + colors: { + timestamp: "yellow", + prefix: "yellow" + } + }); + } + /** + * Print an error message. + * @example + * logger.error('something went wrong') + */ + error(message, ...positionals) { + this.logEntry({ + level: "error", + message, + positionals, + prefix: `\u2716 ${this.prefix}`, + colors: { + timestamp: "red", + prefix: "red" + } + }); + } + /** + * Execute the given callback only when the logging is enabled. + * This is skipped in its entirety and has no runtime cost otherwise. + * This executes regardless of the log level. + * @example + * logger.only(() => { + * logger.info('additional info') + * }) + */ + only(callback) { + callback(); + } + createEntry(level, message) { + return { + timestamp: /* @__PURE__ */ new Date(), + level, + message + }; + } + logEntry(args) { + const { + level, + message, + prefix, + colors: customColors, + positionals = [] + } = args; + const entry = this.createEntry(level, message); + const timestampColor = customColors?.timestamp || "gray"; + const prefixColor = customColors?.prefix || "gray"; + const colorize = { + timestamp: colors_exports[timestampColor], + prefix: colors_exports[prefixColor] + }; + const write = this.getWriter(level); + write( + [colorize.timestamp(this.formatTimestamp(entry.timestamp))].concat(prefix != null ? colorize.prefix(prefix) : []).concat(serializeInput(message)).join(" "), + ...positionals.map(serializeInput) + ); + } + formatTimestamp(timestamp) { + return `${timestamp.toLocaleTimeString( + "en-GB" + )}:${timestamp.getMilliseconds()}`; + } + getWriter(level) { + switch (level) { + case "debug": + case "success": + case "info": { + return log; + } + case "warning": { + return warn; + } + case "error": { + return error; + } + } + } +}; +var PerformanceEntry = class { + startTime; + endTime; + deltaTime; + constructor() { + this.startTime = performance.now(); + } + measure() { + this.endTime = performance.now(); + const deltaTime = this.endTime - this.startTime; + this.deltaTime = deltaTime.toFixed(2); + } +}; +var noop = () => void 0; +function log(message, ...positionals) { + if (IS_NODE) { + process.stdout.write(format(message, ...positionals) + "\n"); + return; + } + console.log(message, ...positionals); +} +function warn(message, ...positionals) { + if (IS_NODE) { + process.stderr.write(format(message, ...positionals) + "\n"); + return; + } + console.warn(message, ...positionals); +} +function error(message, ...positionals) { + if (IS_NODE) { + process.stderr.write(format(message, ...positionals) + "\n"); + return; + } + console.error(message, ...positionals); +} +function getVariable(variableName) { + if (IS_NODE) { + return process.env[variableName]; + } + return globalThis[variableName]?.toString(); +} +function isDefinedAndNotEquals(value, expected) { + return value !== void 0 && value !== expected; +} +function serializeInput(message) { + if (typeof message === "undefined") { + return "undefined"; + } + if (message === null) { + return "null"; + } + if (typeof message === "string") { + return message; + } + if (typeof message === "object") { + return JSON.stringify(message); + } + return message.toString(); +} +export { + Logger +}; diff --git a/node_modules/@open-draft/logger/package.json b/node_modules/@open-draft/logger/package.json new file mode 100644 index 0000000000000000000000000000000000000000..acff2b73812989d26798415d6ff8ea6694910324 --- /dev/null +++ b/node_modules/@open-draft/logger/package.json @@ -0,0 +1,88 @@ +{ + "_from": "@open-draft/logger@^0.3.0", + "_id": "@open-draft/logger@0.3.0", + "_inBundle": false, + "_integrity": "sha512-X2g45fzhxH238HKO4xbSr7+wBS8Fvw6ixhTDuvLd5mqh6bJJCFAPwU9mPDxbcrRtfxv4u5IHCEH77BmxvXmmxQ==", + "_location": "/@open-draft/logger", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@open-draft/logger@^0.3.0", + "name": "@open-draft/logger", + "escapedName": "@open-draft%2flogger", + "scope": "@open-draft", + "rawSpec": "^0.3.0", + "saveSpec": null, + "fetchSpec": "^0.3.0" + }, + "_requiredBy": [ + "/@mswjs/interceptors" + ], + "_resolved": "https://registry.npmjs.org/@open-draft/logger/-/logger-0.3.0.tgz", + "_shasum": "2b3ab1242b360aa0adb28b85f5d7da1c133a0954", + "_spec": "@open-draft/logger@^0.3.0", + "_where": "/Users/sylvainfiloni/Documents/HuggingFace_Projects/live-vision/node_modules/@mswjs/interceptors", + "author": { + "name": "Artem Zakharchenko" + }, + "bugs": { + "url": "https://github.com/open-draft/logger/issues" + }, + "bundleDependencies": false, + "dependencies": { + "is-node-process": "^1.2.0", + "outvariant": "^1.4.0" + }, + "deprecated": false, + "description": "Environment-agnostic, ESM-friendly logger for simple needs.", + "devDependencies": { + "@ossjs/release": "^0.5.1", + "@playwright/test": "^1.32.3", + "@types/node": "^18.15.11", + "playwright": "^1.32.3", + "tsup": "^6.7.0", + "typescript": "^5.0.3", + "vitest": "^0.29.8", + "webpack-http-server": "^0.5.0" + }, + "exports": { + ".": { + "types": "./lib/index.d.ts", + "require": "./lib/index.js", + "import": "./lib/index.mjs", + "default": "./lib/index.js" + }, + "./package.json": "./package.json" + }, + "files": [ + "lib", + "LICENSE", + "README.md" + ], + "homepage": "https://github.com/open-draft/logger#readme", + "keywords": [ + "log", + "logger", + "logging", + "universal", + "tiny" + ], + "license": "MIT", + "main": "./lib/index.js", + "module": "./lib/index.mjs", + "name": "@open-draft/logger", + "repository": { + "type": "git", + "url": "git+https://github.com/open-draft/logger.git" + }, + "scripts": { + "build": "tsup", + "release": "release publish", + "test": "pnpm test:node && pnpm test:browser", + "test:browser": "playwright test", + "test:node": "vitest run" + }, + "types": "./lib/index.d.ts", + "version": "0.3.0" +} diff --git a/node_modules/socket.io-adapter/node_modules/ws/LICENSE b/node_modules/@open-draft/until/LICENSE similarity index 94% rename from node_modules/socket.io-adapter/node_modules/ws/LICENSE rename to node_modules/@open-draft/until/LICENSE index 65ff176bf67f4f829c254a44da5d36d0a0c070f2..8a1c628e5112fbb284d8e1cd9988c44d6599ddd5 100644 --- a/node_modules/socket.io-adapter/node_modules/ws/LICENSE +++ b/node_modules/@open-draft/until/LICENSE @@ -1,4 +1,6 @@ -Copyright (c) 2011 Einar Otto Stangvik +MIT License + +Copyright (c) 2021 Artem Zakharchenko 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/node_modules/@open-draft/until/README.md b/node_modules/@open-draft/until/README.md new file mode 100644 index 0000000000000000000000000000000000000000..be49a5049f72c28529ce0bb6c8d48080b067ca9a --- /dev/null +++ b/node_modules/@open-draft/until/README.md @@ -0,0 +1,150 @@ +[![Latest release](https://img.shields.io/npm/v/@open-draft/until.svg)](https://www.npmjs.com/package/@open-draft/until) + +# `until` + +Gracefully handle a Promise using `async`/`await`. + +## Why? + +With the addition of `async`/`await` keywords in ECMAScript 2017 the handling of Promises became much easier. However, one must keep in mind that the `await` keyword provides no standard error handling API. Consider this usage: + +```js +function getUser(id) { + const data = await fetchUser(id) + // Work with "data"... +} +``` + +In case `fetchUser()` throws an error, the entire `getUser()` function's scope will terminate. Because of this, it's recommended to implement error handling using `try`/`catch` block wrapping `await` expressions: + +```js +function getUser(id) + let data = null + + try { + data = await asyncAction() + } catch (error) { + console.error(error) + } + + // Work with "data"... +} +``` + +While this is a semantically valid approach, constructing `try`/`catch` around each awaited operation may be tedious and get overlooked at times. Such error handling also introduces separate closures for execution and error scenarios of an asynchronous operation. + +This library encapsulates the `try`/`catch` error handling in a utility function that does not create a separate closure and exposes a NodeJS-friendly API to work with errors and resolved data. + +## Getting started + +### Install + +```bash +npm install @open-draft/until +``` + +### Usage + +```js +import { until } from '@open-draft/until' + +async function(id) { + const { error, data } = await until(() => fetchUser(id)) + + if (error) { + return handleError(error) + } + + return data +} +``` + +### Usage with TypeScript + +```ts +import { until } from '@open-draft/until' + +interface User { + firstName: string + age: number +} + +interface UserFetchError { + type: 'FORBIDDEN' | 'NOT_FOUND' + message?: string +} + +async function(id: string) { + const { error, data } = await until(() => fetchUser(id)) + + if (error) { + handleError(error.type, error.message) + } + + return data.firstName +} +``` + +## Frequently asked questions + +### Why does `until` accept a function and not a `Promise` directly? + +This has been intentionally introduced to await a single logical unit as opposed to a single `Promise`. + +```js +// Notice how a single "until" invocation can handle +// a rather complex piece of logic. This way any rejections +// or exceptions happening within the given function +// can be handled via the same "error". +const { error, data } = until(async () => { + const user = await fetchUser() + const nextUser = normalizeUser(user) + const transaction = await saveModel('user', user) + + invariant(transaction.status === 'OK', 'Saving user failed') + + return transaction.result +}) + +if (error) { + // Handle any exceptions happened within the function. +} +``` + +### Why does `until` return an object and not an array? + +The `until` function used to return an array of shape `[error, data]` prior to `2.0.0`. That has been changed, however, to get proper type-safety using discriminated union type. + +Compare these two examples: + +```ts +const [error, data] = await until(() => action()) + +if (error) { + return null +} + +// Data still has ambiguous "DataType | null" type here +// even after you've checked and handled the "error" above. +console.log(data) +``` + +```ts +const result = await until(() => action()) + +// At this point, "data" is ambiguous "DataType | null" +// which is correct, as you haven't checked nor handled the "error". + +if (result.error) { + return null +} + +// Data is strict "DataType" since you've handled the "error" above. +console.log(result.data) +``` + +> It's crucial to keep the entire result of the `Promise` in a single variable and not destructure it. TypeScript will always keep the type of `error` and `data` as it was upon destructuring, ignoring any type guards you may perform later on. + +## Special thanks + +- [giuseppegurgone](https://twitter.com/giuseppegurgone) for the discussion about the original `until` API. diff --git a/node_modules/@open-draft/until/lib/index.d.ts b/node_modules/@open-draft/until/lib/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..19544f40af2d8200543b3de66a7440515b412fcf --- /dev/null +++ b/node_modules/@open-draft/until/lib/index.d.ts @@ -0,0 +1,15 @@ +type AsyncTuple = { + error: ErrorType; + data: null; +} | { + error: null; + data: DataType; +}; +/** + * Gracefully handles a given Promise factory. + * @example + * const { error, data } = await until(() => asyncAction()) + */ +declare const until: (promise: () => Promise) => Promise>; + +export { until }; diff --git a/node_modules/@open-draft/until/lib/index.js b/node_modules/@open-draft/until/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..3944d95acf437053955fb9693ab1c5a1846e547f --- /dev/null +++ b/node_modules/@open-draft/until/lib/index.js @@ -0,0 +1,41 @@ +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); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + until: () => until +}); +module.exports = __toCommonJS(src_exports); + +// src/until.ts +var until = async (promise) => { + try { + const data = await promise().catch((error) => { + throw error; + }); + return { error: null, data }; + } catch (error) { + return { error, data: null }; + } +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + until +}); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@open-draft/until/lib/index.js.map b/node_modules/@open-draft/until/lib/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..71429109f0c6a5f3b4d9ec7cc23e46daa40d58cc --- /dev/null +++ b/node_modules/@open-draft/until/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/index.ts","../src/until.ts"],"sourcesContent":["export { until } from './until'","export type AsyncTuple<\n ErrorType extends any = Error,\n DataType extends any = unknown,\n> =\n | {\n error: ErrorType\n data: null\n }\n | { error: null; data: DataType }\n\n/**\n * Gracefully handles a given Promise factory.\n * @example\n * const { error, data } = await until(() => asyncAction())\n */\nexport const until = async <\n ErrorType extends any = Error,\n DataType extends any = unknown,\n>(\n promise: () => Promise,\n): Promise> => {\n try {\n const data = await promise().catch((error) => {\n throw error\n })\n return { error: null, data }\n } catch (error) {\n return { error, data: null }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACeO,IAAM,QAAQ,OAInB,YAC6C;AAC7C,MAAI;AACF,UAAM,OAAO,MAAM,QAAQ,EAAE,MAAM,CAAC,UAAU;AAC5C,YAAM;AAAA,IACR,CAAC;AACD,WAAO,EAAE,OAAO,MAAM,KAAK;AAAA,EAC7B,SAAS,OAAP;AACA,WAAO,EAAE,OAAO,MAAM,KAAK;AAAA,EAC7B;AACF;","names":[]} \ No newline at end of file diff --git a/node_modules/@open-draft/until/lib/index.mjs b/node_modules/@open-draft/until/lib/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..12be84c8d15c8e5850d2b16a5f8cc26e69731a30 --- /dev/null +++ b/node_modules/@open-draft/until/lib/index.mjs @@ -0,0 +1,15 @@ +// src/until.ts +var until = async (promise) => { + try { + const data = await promise().catch((error) => { + throw error; + }); + return { error: null, data }; + } catch (error) { + return { error, data: null }; + } +}; +export { + until +}; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/@open-draft/until/lib/index.mjs.map b/node_modules/@open-draft/until/lib/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..6c246974fcda2bf89d775d88ecc5ddbd27706f4d --- /dev/null +++ b/node_modules/@open-draft/until/lib/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/until.ts"],"sourcesContent":["export type AsyncTuple<\n ErrorType extends any = Error,\n DataType extends any = unknown,\n> =\n | {\n error: ErrorType\n data: null\n }\n | { error: null; data: DataType }\n\n/**\n * Gracefully handles a given Promise factory.\n * @example\n * const { error, data } = await until(() => asyncAction())\n */\nexport const until = async <\n ErrorType extends any = Error,\n DataType extends any = unknown,\n>(\n promise: () => Promise,\n): Promise> => {\n try {\n const data = await promise().catch((error) => {\n throw error\n })\n return { error: null, data }\n } catch (error) {\n return { error, data: null }\n }\n}\n"],"mappings":";AAeO,IAAM,QAAQ,OAInB,YAC6C;AAC7C,MAAI;AACF,UAAM,OAAO,MAAM,QAAQ,EAAE,MAAM,CAAC,UAAU;AAC5C,YAAM;AAAA,IACR,CAAC;AACD,WAAO,EAAE,OAAO,MAAM,KAAK;AAAA,EAC7B,SAAS,OAAP;AACA,WAAO,EAAE,OAAO,MAAM,KAAK;AAAA,EAC7B;AACF;","names":[]} \ No newline at end of file diff --git a/node_modules/@open-draft/until/package.json b/node_modules/@open-draft/until/package.json new file mode 100644 index 0000000000000000000000000000000000000000..11f77b89c89a71cdbf994da9a91822db1125362a --- /dev/null +++ b/node_modules/@open-draft/until/package.json @@ -0,0 +1,74 @@ +{ + "_from": "@open-draft/until@^2.1.0", + "_id": "@open-draft/until@2.1.0", + "_inBundle": false, + "_integrity": "sha512-U69T3ItWHvLwGg5eJ0n3I62nWuE6ilHlmz7zM0npLBRvPRd7e6NYmg54vvRtP5mZG7kZqZCFVdsTWo7BPtBujg==", + "_location": "/@open-draft/until", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@open-draft/until@^2.1.0", + "name": "@open-draft/until", + "escapedName": "@open-draft%2funtil", + "scope": "@open-draft", + "rawSpec": "^2.1.0", + "saveSpec": null, + "fetchSpec": "^2.1.0" + }, + "_requiredBy": [ + "/@mswjs/interceptors", + "/msw" + ], + "_resolved": "https://registry.npmjs.org/@open-draft/until/-/until-2.1.0.tgz", + "_shasum": "0acf32f470af2ceaf47f095cdecd40d68666efda", + "_spec": "@open-draft/until@^2.1.0", + "_where": "/Users/sylvainfiloni/Documents/HuggingFace_Projects/live-vision/node_modules/msw", + "author": { + "name": "Artem Zakharchenko", + "email": "kettanaito@gmail.com" + }, + "bugs": { + "url": "https://github.com/open-draft/until/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Gracefully handle a Promise using async/await.", + "devDependencies": { + "@ossjs/release": "^0.5.1", + "@types/jest": "^26.0.22", + "jest": "^26.6.3", + "ts-jest": "^26.5.4", + "tsup": "^6.2.3", + "typescript": "^4.2.4" + }, + "exports": { + ".": { + "types": "./lib/index.d.ts", + "require": "./lib/index.js", + "import": "./lib/index.mjs", + "default": "./lib/index.mjs" + } + }, + "files": [ + "README.md", + "lib" + ], + "homepage": "https://github.com/open-draft/until#readme", + "license": "MIT", + "main": "./lib/index.js", + "module": "./lib/index.mjs", + "name": "@open-draft/until", + "repository": { + "type": "git", + "url": "git+https://github.com/open-draft/until.git" + }, + "scripts": { + "build": "tsup", + "release": "release publish", + "start": "tsc -w", + "test": "jest" + }, + "types": "./lib/index.d.ts", + "version": "2.1.0" +} diff --git a/node_modules/@socket.io/component-emitter/Readme.md b/node_modules/@socket.io/component-emitter/Readme.md index 0f3f9b9fc37c883b3a7288a8dc5fd1ae2df57afe..feb36f1918e11abea44039abc37d80e457166356 100644 --- a/node_modules/@socket.io/component-emitter/Readme.md +++ b/node_modules/@socket.io/component-emitter/Readme.md @@ -1,11 +1,13 @@ -# Emitter [![Build Status](https://travis-ci.org/component/emitter.png)](https://travis-ci.org/component/emitter) +# `@socket.io/component-emitter` Event emitter component. +This project is a fork of the [`component-emitter`](https://github.com/sindresorhus/component-emitter) project, with [Socket.IO](https://socket.io/)-specific TypeScript typings. + ## Installation ``` -$ component install component/emitter +$ npm i @socket.io/component-emitter ``` ## API @@ -19,7 +21,8 @@ $ component install component/emitter As an `Emitter` instance: ```js -var Emitter = require('emitter'); +import { Emitter } from '@socket.io/component-emitter'; + var emitter = new Emitter; emitter.emit('something'); ``` @@ -27,7 +30,8 @@ emitter.emit('something'); As a mixin: ```js -var Emitter = require('emitter'); +import { Emitter } from '@socket.io/component-emitter'; + var user = { name: 'tobi' }; Emitter(user); @@ -37,7 +41,8 @@ user.emit('im a user'); As a prototype mixin: ```js -var Emitter = require('emitter'); +import { Emitter } from '@socket.io/component-emitter'; + Emitter(User.prototype); ``` diff --git a/node_modules/@socket.io/component-emitter/index.d.ts b/node_modules/@socket.io/component-emitter/lib/cjs/index.d.ts similarity index 100% rename from node_modules/@socket.io/component-emitter/index.d.ts rename to node_modules/@socket.io/component-emitter/lib/cjs/index.d.ts diff --git a/node_modules/@socket.io/component-emitter/index.js b/node_modules/@socket.io/component-emitter/lib/cjs/index.js similarity index 100% rename from node_modules/@socket.io/component-emitter/index.js rename to node_modules/@socket.io/component-emitter/lib/cjs/index.js diff --git a/node_modules/@socket.io/component-emitter/lib/cjs/package.json b/node_modules/@socket.io/component-emitter/lib/cjs/package.json new file mode 100644 index 0000000000000000000000000000000000000000..b6cc1b6318effe05a3ae0b51bdbeb58b215c5d35 --- /dev/null +++ b/node_modules/@socket.io/component-emitter/lib/cjs/package.json @@ -0,0 +1,4 @@ +{ + "name": "@socket.io/component-emitter", + "type": "commonjs" +} diff --git a/node_modules/@socket.io/component-emitter/lib/esm/index.d.ts b/node_modules/@socket.io/component-emitter/lib/esm/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..49a74e142d2ff53c361b061d58640a80008dfb96 --- /dev/null +++ b/node_modules/@socket.io/component-emitter/lib/esm/index.d.ts @@ -0,0 +1,179 @@ +/** + * An events map is an interface that maps event names to their value, which + * represents the type of the `on` listener. + */ +export interface EventsMap { + [event: string]: any; +} + +/** + * The default events map, used if no EventsMap is given. Using this EventsMap + * is equivalent to accepting all event names, and any data. + */ +export interface DefaultEventsMap { + [event: string]: (...args: any[]) => void; +} + +/** + * Returns a union type containing all the keys of an event map. + */ +export type EventNames = keyof Map & (string | symbol); + +/** The tuple type representing the parameters of an event listener */ +export type EventParams< + Map extends EventsMap, + Ev extends EventNames + > = Parameters; + +/** + * The event names that are either in ReservedEvents or in UserEvents + */ +export type ReservedOrUserEventNames< + ReservedEventsMap extends EventsMap, + UserEvents extends EventsMap + > = EventNames | EventNames; + +/** + * Type of a listener of a user event or a reserved event. If `Ev` is in + * `ReservedEvents`, the reserved event listener is returned. + */ +export type ReservedOrUserListener< + ReservedEvents extends EventsMap, + UserEvents extends EventsMap, + Ev extends ReservedOrUserEventNames + > = FallbackToUntypedListener< + Ev extends EventNames + ? ReservedEvents[Ev] + : Ev extends EventNames + ? UserEvents[Ev] + : never + >; + +/** + * Returns an untyped listener type if `T` is `never`; otherwise, returns `T`. + * + * This is a hack to mitigate https://github.com/socketio/socket.io/issues/3833. + * Needed because of https://github.com/microsoft/TypeScript/issues/41778 + */ +type FallbackToUntypedListener = [T] extends [never] + ? (...args: any[]) => void | Promise + : T; + +/** + * Strictly typed version of an `EventEmitter`. A `TypedEventEmitter` takes type + * parameters for mappings of event names to event data types, and strictly + * types method calls to the `EventEmitter` according to these event maps. + * + * @typeParam ListenEvents - `EventsMap` of user-defined events that can be + * listened to with `on` or `once` + * @typeParam EmitEvents - `EventsMap` of user-defined events that can be + * emitted with `emit` + * @typeParam ReservedEvents - `EventsMap` of reserved events, that can be + * emitted by socket.io with `emitReserved`, and can be listened to with + * `listen`. + */ +export class Emitter< + ListenEvents extends EventsMap, + EmitEvents extends EventsMap, + ReservedEvents extends EventsMap = {} + > { + /** + * Adds the `listener` function as an event listener for `ev`. + * + * @param ev Name of the event + * @param listener Callback function + */ + on>( + ev: Ev, + listener: ReservedOrUserListener + ): this; + + /** + * Adds a one-time `listener` function as an event listener for `ev`. + * + * @param ev Name of the event + * @param listener Callback function + */ + once>( + ev: Ev, + listener: ReservedOrUserListener + ): this; + + /** + * Removes the `listener` function as an event listener for `ev`. + * + * @param ev Name of the event + * @param listener Callback function + */ + off>( + ev?: Ev, + listener?: ReservedOrUserListener + ): this; + + /** + * Emits an event. + * + * @param ev Name of the event + * @param args Values to send to listeners of this event + */ + emit>( + ev: Ev, + ...args: EventParams + ): this; + + /** + * Emits a reserved event. + * + * This method is `protected`, so that only a class extending + * `StrictEventEmitter` can emit its own reserved events. + * + * @param ev Reserved event name + * @param args Arguments to emit along with the event + */ + protected emitReserved>( + ev: Ev, + ...args: EventParams + ): this; + + /** + * Returns the listeners listening to an event. + * + * @param event Event name + * @returns Array of listeners subscribed to `event` + */ + listeners>( + event: Ev + ): ReservedOrUserListener[]; + + /** + * Returns true if there is a listener for this event. + * + * @param event Event name + * @returns boolean + */ + hasListeners< + Ev extends ReservedOrUserEventNames + >(event: Ev): boolean; + + /** + * Removes the `listener` function as an event listener for `ev`. + * + * @param ev Name of the event + * @param listener Callback function + */ + removeListener< + Ev extends ReservedOrUserEventNames + >( + ev?: Ev, + listener?: ReservedOrUserListener + ): this; + + /** + * Removes all `listener` function as an event listener for `ev`. + * + * @param ev Name of the event + */ + removeAllListeners< + Ev extends ReservedOrUserEventNames + >(ev?: Ev): this; +} diff --git a/node_modules/@socket.io/component-emitter/index.mjs b/node_modules/@socket.io/component-emitter/lib/esm/index.js similarity index 100% rename from node_modules/@socket.io/component-emitter/index.mjs rename to node_modules/@socket.io/component-emitter/lib/esm/index.js diff --git a/node_modules/@socket.io/component-emitter/lib/esm/package.json b/node_modules/@socket.io/component-emitter/lib/esm/package.json new file mode 100644 index 0000000000000000000000000000000000000000..0511a0cbe72c469239dd63e913edc663a302ef36 --- /dev/null +++ b/node_modules/@socket.io/component-emitter/lib/esm/package.json @@ -0,0 +1,4 @@ +{ + "name": "@socket.io/component-emitter", + "type": "module" +} diff --git a/node_modules/@socket.io/component-emitter/package.json b/node_modules/@socket.io/component-emitter/package.json index c73c23da8e637bfcb4fe5752fbb8da9be8e5e92b..f3f1edcff26d4a7e0d1bc2a6d2039165ed6be436 100644 --- a/node_modules/@socket.io/component-emitter/package.json +++ b/node_modules/@socket.io/component-emitter/package.json @@ -1,31 +1,58 @@ { - "name": "@socket.io/component-emitter", - "description": "Event emitter", - "version": "3.1.0", - "license": "MIT", - "devDependencies": { - "mocha": "*", - "should": "*" + "_from": "@socket.io/component-emitter@~3.1.0", + "_id": "@socket.io/component-emitter@3.1.2", + "_inBundle": false, + "_integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==", + "_location": "/@socket.io/component-emitter", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@socket.io/component-emitter@~3.1.0", + "name": "@socket.io/component-emitter", + "escapedName": "@socket.io%2fcomponent-emitter", + "scope": "@socket.io", + "rawSpec": "~3.1.0", + "saveSpec": null, + "fetchSpec": "~3.1.0" }, + "_requiredBy": [ + "/socket.io-parser" + ], + "_resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz", + "_shasum": "821f8442f4175d8f0467b9daf26e3a18e2d02af2", + "_spec": "@socket.io/component-emitter@~3.1.0", + "_where": "/Users/sylvainfiloni/Documents/HuggingFace_Projects/live-vision/node_modules/socket.io-parser", + "bugs": { + "url": "https://github.com/socketio/emitter/issues" + }, + "bundleDependencies": false, "component": { "scripts": { "emitter/index.js": "index.js" } }, - "main": "index.js", - "module": "index.mjs", - "types": "index.d.ts", + "deprecated": false, + "description": "Event emitter", + "devDependencies": { + "mocha": "*", + "should": "*" + }, + "files": [ + "lib/" + ], + "homepage": "https://github.com/socketio/emitter#readme", + "license": "MIT", + "main": "./lib/cjs/index.js", + "module": "./lib/esm/index.js", + "name": "@socket.io/component-emitter", "repository": { "type": "git", - "url": "https://github.com/socketio/emitter.git" + "url": "git+https://github.com/socketio/emitter.git" }, "scripts": { "test": "make test" }, - "files": [ - "index.js", - "index.mjs", - "index.d.ts", - "LICENSE" - ] + "types": "./lib/cjs/index.d.ts", + "version": "3.1.2" } diff --git a/node_modules/@types/cookie/LICENSE b/node_modules/@types/cookie/LICENSE old mode 100644 new mode 100755 diff --git a/node_modules/@types/cookie/README.md b/node_modules/@types/cookie/README.md old mode 100644 new mode 100755 index 2070bb5cb1106691d75ccda96726fddadb4de091..b6b69985d3a928686b479814e49a0ee3e5d2e6f2 --- a/node_modules/@types/cookie/README.md +++ b/node_modules/@types/cookie/README.md @@ -1,16 +1,16 @@ -# Installation -> `npm install --save @types/cookie` - -# Summary -This package contains type definitions for cookie (https://github.com/jshttp/cookie). - -# Details -Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/cookie. - -### Additional Details - * Last updated: Tue, 06 Jul 2021 20:32:30 GMT - * Dependencies: none - * Global values: none - -# Credits -These definitions were written by [Pine Mizune](https://github.com/pine), and [Piotr Błażejewicz](https://github.com/peterblazejewicz). +# Installation +> `npm install --save @types/cookie` + +# Summary +This package contains type definitions for cookie (https://github.com/jshttp/cookie). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/cookie. + +### Additional Details + * Last updated: Tue, 06 Jul 2021 20:32:30 GMT + * Dependencies: none + * Global values: none + +# Credits +These definitions were written by [Pine Mizune](https://github.com/pine), and [Piotr Błażejewicz](https://github.com/peterblazejewicz). diff --git a/node_modules/@types/cookie/index.d.ts b/node_modules/@types/cookie/index.d.ts old mode 100644 new mode 100755 diff --git a/node_modules/@types/cookie/package.json b/node_modules/@types/cookie/package.json old mode 100644 new mode 100755 index 4aae1e43f60a00fe8ddd1d5cd80bc164e330f77b..981223a499d69f3430422dc61d4ef403120885ba --- a/node_modules/@types/cookie/package.json +++ b/node_modules/@types/cookie/package.json @@ -1,30 +1,57 @@ { + "_from": "@types/cookie@^0.4.1", + "_id": "@types/cookie@0.4.1", + "_inBundle": false, + "_integrity": "sha512-XW/Aa8APYr6jSVVA1y/DEIZX0/GMKLEVekNG727R8cs56ahETkRAy/3DR7+fJyh7oUgGwNQaRfXCun0+KbWY7Q==", + "_location": "/@types/cookie", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@types/cookie@^0.4.1", "name": "@types/cookie", - "version": "0.4.1", - "description": "TypeScript definitions for cookie", - "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/cookie", - "license": "MIT", - "contributors": [ - { - "name": "Pine Mizune", - "url": "https://github.com/pine", - "githubUsername": "pine" - }, - { - "name": "Piotr Błażejewicz", - "url": "https://github.com/peterblazejewicz", - "githubUsername": "peterblazejewicz" - } - ], - "main": "", - "types": "index.d.ts", - "repository": { - "type": "git", - "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", - "directory": "types/cookie" + "escapedName": "@types%2fcookie", + "scope": "@types", + "rawSpec": "^0.4.1", + "saveSpec": null, + "fetchSpec": "^0.4.1" + }, + "_requiredBy": [ + "/engine.io" + ], + "_resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.4.1.tgz", + "_shasum": "bfd02c1f2224567676c1545199f87c3a861d878d", + "_spec": "@types/cookie@^0.4.1", + "_where": "/Users/sylvainfiloni/Documents/HuggingFace_Projects/live-vision/node_modules/engine.io", + "bugs": { + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Pine Mizune", + "url": "https://github.com/pine" }, - "scripts": {}, - "dependencies": {}, - "typesPublisherContentHash": "7d4a6dd505c896319459ae131b5fa8fc0a2ed25552db53dac87946119bb21559", - "typeScriptVersion": "3.6" -} \ No newline at end of file + { + "name": "Piotr Błażejewicz", + "url": "https://github.com/peterblazejewicz" + } + ], + "dependencies": {}, + "deprecated": false, + "description": "TypeScript definitions for cookie", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/cookie", + "license": "MIT", + "main": "", + "name": "@types/cookie", + "repository": { + "type": "git", + "url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/cookie" + }, + "scripts": {}, + "typeScriptVersion": "3.6", + "types": "index.d.ts", + "typesPublisherContentHash": "7d4a6dd505c896319459ae131b5fa8fc0a2ed25552db53dac87946119bb21559", + "version": "0.4.1" +} diff --git a/node_modules/@types/cors/README.md b/node_modules/@types/cors/README.md index efa62370e95152781be2f7d34d70ab570fea70e5..79c8b00b23d3ad05f8cfbf6f84fc36adef6bf12c 100644 --- a/node_modules/@types/cors/README.md +++ b/node_modules/@types/cors/README.md @@ -1,13 +1,13 @@ -# Installation -> `npm install --save @types/cors` - -# Summary -This package contains type definitions for cors (https://github.com/expressjs/cors/). - -# Details -Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/cors. -## [index.d.ts](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/cors/index.d.ts) -````ts +# Installation +> `npm install --save @types/cors` + +# Summary +This package contains type definitions for cors (https://github.com/expressjs/cors/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/cors. +## [index.d.ts](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/cors/index.d.ts) +````ts /// import { IncomingHttpHeaders } from "http"; @@ -64,12 +64,12 @@ declare function e( next: (err?: any) => any, ) => void; export = e; - -```` - -### Additional Details - * Last updated: Mon, 20 Nov 2023 23:36:24 GMT - * Dependencies: [@types/node](https://npmjs.com/package/@types/node) - -# Credits -These definitions were written by [Alan Plum](https://github.com/pluma), and [Gaurav Sharma](https://github.com/gtpan77). + +```` + +### Additional Details + * Last updated: Mon, 20 Nov 2023 23:36:24 GMT + * Dependencies: [@types/node](https://npmjs.com/package/@types/node) + +# Credits +These definitions were written by [Alan Plum](https://github.com/pluma), and [Gaurav Sharma](https://github.com/gtpan77). diff --git a/node_modules/@types/cors/package.json b/node_modules/@types/cors/package.json index 5b400cb216cc72297dd33ce16882e10e4123d83f..1fb32e9484331fd695999eafb88fddc33fab20c0 100644 --- a/node_modules/@types/cors/package.json +++ b/node_modules/@types/cors/package.json @@ -1,32 +1,59 @@ { + "_from": "@types/cors@^2.8.12", + "_id": "@types/cors@2.8.17", + "_inBundle": false, + "_integrity": "sha512-8CGDvrBj1zgo2qE+oS3pOCyYNqCPryMWY2bGfwA0dcfopWGgxs+78df0Rs3rc9THP4JkOhLsAa+15VdpAqkcUA==", + "_location": "/@types/cors", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@types/cors@^2.8.12", "name": "@types/cors", - "version": "2.8.17", - "description": "TypeScript definitions for cors", - "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/cors", - "license": "MIT", - "contributors": [ - { - "name": "Alan Plum", - "githubUsername": "pluma", - "url": "https://github.com/pluma" - }, - { - "name": "Gaurav Sharma", - "githubUsername": "gtpan77", - "url": "https://github.com/gtpan77" - } - ], - "main": "", - "types": "index.d.ts", - "repository": { - "type": "git", - "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", - "directory": "types/cors" + "escapedName": "@types%2fcors", + "scope": "@types", + "rawSpec": "^2.8.12", + "saveSpec": null, + "fetchSpec": "^2.8.12" + }, + "_requiredBy": [ + "/engine.io" + ], + "_resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.17.tgz", + "_shasum": "5d718a5e494a8166f569d986794e49c48b216b2b", + "_spec": "@types/cors@^2.8.12", + "_where": "/Users/sylvainfiloni/Documents/HuggingFace_Projects/live-vision/node_modules/engine.io", + "bugs": { + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Alan Plum", + "url": "https://github.com/pluma" }, - "scripts": {}, - "dependencies": { - "@types/node": "*" - }, - "typesPublisherContentHash": "04d506dbb23d9e7a142bfb227d59c61102abec00fb40694bb64a8d9fe1f1a3a1", - "typeScriptVersion": "4.5" -} \ No newline at end of file + { + "name": "Gaurav Sharma", + "url": "https://github.com/gtpan77" + } + ], + "dependencies": { + "@types/node": "*" + }, + "deprecated": false, + "description": "TypeScript definitions for cors", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/cors", + "license": "MIT", + "main": "", + "name": "@types/cors", + "repository": { + "type": "git", + "url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/cors" + }, + "scripts": {}, + "typeScriptVersion": "4.5", + "types": "index.d.ts", + "typesPublisherContentHash": "04d506dbb23d9e7a142bfb227d59c61102abec00fb40694bb64a8d9fe1f1a3a1", + "version": "2.8.17" +} diff --git a/node_modules/@types/eventsource/LICENSE b/node_modules/@types/eventsource/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/node_modules/@types/eventsource/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/node_modules/@types/eventsource/README.md b/node_modules/@types/eventsource/README.md new file mode 100644 index 0000000000000000000000000000000000000000..10fa78f8a7454691e8f36a64661cbcab2082b489 --- /dev/null +++ b/node_modules/@types/eventsource/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/eventsource` + +# Summary +This package contains type definitions for eventsource (https://github.com/EventSource/eventsource). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/eventsource. + +### Additional Details + * Last updated: Mon, 06 Nov 2023 22:41:05 GMT + * Dependencies: none + +# Credits +These definitions were written by [Scott Lee Davis](https://github.com/scottleedavis), [Ali Afroozeh](https://github.com/afroozeh), [Pedro Gámez](https://github.com/snakedrak), and [Akuukis](https://github.com/Akuukis). diff --git a/node_modules/@types/eventsource/dom-monkeypatch.d.ts b/node_modules/@types/eventsource/dom-monkeypatch.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..27df09e8638944ba0c74d37c3efff9628b5916d3 --- /dev/null +++ b/node_modules/@types/eventsource/dom-monkeypatch.d.ts @@ -0,0 +1,92 @@ +/** + * The Event interface represents any event which takes place in the DOM; some are user-generated (such as mouse or keyboard events), while others are generated by APIs (such as + * events that indicate an animation has finished running, a video has been paused, and so forth). While events are usually triggered by such "external" sources, they can also be + * triggered programmatically, such as by calling the HTMLElement.click() method of an element, or by defining the event, then sending it to a specified target using + * EventTarget.dispatchEvent(). There are many types of events, some of which use other interfaces based on the main Event interface. Event itself contains the properties and + * methods which are common to all events. + */ +interface Event { + /** + * Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. + */ + readonly bubbles: boolean; + cancelBubble: boolean; + readonly cancelable: boolean; + /** + * Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. + */ + readonly composed: boolean; + readonly defaultPrevented: boolean; + readonly eventPhase: number; + /** + * Returns true if event was dispatched by the user agent, and + * false otherwise. + */ + readonly isTrusted: boolean; + returnValue: boolean; + /** + * Returns the event's timestamp as the number of milliseconds measured relative to + * the time origin. + */ + readonly timeStamp: number; + /** + * Unauthorized and redirect error status codes (for example 401, 403, 301, 307) + */ + readonly status?: number | undefined; + /** + * Returns the type of event, e.g. + * "click", "hashchange", or + * "submit". + */ + readonly type: string; + readonly AT_TARGET: 2; + readonly BUBBLING_PHASE: 3; + readonly CAPTURING_PHASE: 1; + readonly NONE: 0; + composedPath(): any[]; + initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void; + preventDefault(): void; + /** + * Invoking this method prevents event from reaching + * any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any + * other objects. + */ + stopImmediatePropagation(): void; + /** + * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. + */ + stopPropagation(): void; +} + +interface EventInit { + bubbles?: boolean | undefined; + cancelable?: boolean | undefined; + composed?: boolean | undefined; +} + +interface MessageEventInit extends EventInit { + data?: T | undefined; + lastEventId?: string | undefined; + origin?: string | undefined; +} + +/** The MessageEvent interface represents a message received by a target object. */ +interface MessageEvent extends Event { + /** + * Returns the data of the message. + */ + readonly data: T; + /** + * Returns the last event ID string, for server-sent events. + */ + readonly lastEventId: string; + /** + * Returns the origin of the message, for server-sent events and + * cross-document messaging. + */ + readonly origin: string; +} +declare var MessageEvent: { + prototype: MessageEvent; + new(type: string, eventInitDict?: MessageEventInit): MessageEvent; +}; diff --git a/node_modules/@types/eventsource/index.d.ts b/node_modules/@types/eventsource/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1ab7bee2989fd6b4e3db9e20cc5c1e6ed6bd52e3 --- /dev/null +++ b/node_modules/@types/eventsource/index.d.ts @@ -0,0 +1,45 @@ +// eventsource uses DOM dependencies which are absent in a browserless environment like node.js. +// to avoid compiler errors this monkey patch is used. See more details in: +// - sinon: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/11351 +// - rxjs: https://github.com/ReactiveX/rxjs/issues/1986 +/// + +declare class EventSource { + static readonly CLOSED: number; + static readonly CONNECTING: number; + static readonly OPEN: number; + + constructor(url: string, eventSourceInitDict?: EventSource.EventSourceInitDict); + + readonly CLOSED: number; + readonly CONNECTING: number; + readonly OPEN: number; + readonly url: string; + readonly readyState: number; + readonly withCredentials: boolean; + onopen: (evt: MessageEvent) => any; + onmessage: (evt: MessageEvent) => any; + onerror: (evt: MessageEvent) => any; + addEventListener(type: string, listener: (evt: MessageEvent) => void): void; + dispatchEvent(evt: Event): boolean; + removeEventListener(type: string, listener: (evt: MessageEvent) => void): void; + close(): void; +} + +declare namespace EventSource { + enum ReadyState { + CONNECTING = 0, + OPEN = 1, + CLOSED = 2, + } + + interface EventSourceInitDict { + withCredentials?: boolean | undefined; + headers?: object | undefined; + proxy?: string | undefined; + https?: object | undefined; + rejectUnauthorized?: boolean | undefined; + } +} + +export = EventSource; diff --git a/node_modules/@types/eventsource/lib/eventsource-polyfill/index.d.ts b/node_modules/@types/eventsource/lib/eventsource-polyfill/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..663e82f0ad7b709589d22e042a167101f66e3379 --- /dev/null +++ b/node_modules/@types/eventsource/lib/eventsource-polyfill/index.d.ts @@ -0,0 +1,2 @@ +import * as EventSource from "../../index"; +export = EventSource; diff --git a/node_modules/@types/eventsource/package.json b/node_modules/@types/eventsource/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a5c4e962faccadd19b4214ee6ab3fe7f60d75a1c --- /dev/null +++ b/node_modules/@types/eventsource/package.json @@ -0,0 +1,65 @@ +{ + "_from": "@types/eventsource@^1.1.15", + "_id": "@types/eventsource@1.1.15", + "_inBundle": false, + "_integrity": "sha512-XQmGcbnxUNa06HR3VBVkc9+A2Vpi9ZyLJcdS5dwaQQ/4ZMWFO+5c90FnMUpbtMZwB/FChoYHwuVg8TvkECacTA==", + "_location": "/@types/eventsource", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@types/eventsource@^1.1.15", + "name": "@types/eventsource", + "escapedName": "@types%2feventsource", + "scope": "@types", + "rawSpec": "^1.1.15", + "saveSpec": null, + "fetchSpec": "^1.1.15" + }, + "_requiredBy": [ + "/@gradio/client" + ], + "_resolved": "https://registry.npmjs.org/@types/eventsource/-/eventsource-1.1.15.tgz", + "_shasum": "949383d3482e20557cbecbf3b038368d94b6be27", + "_spec": "@types/eventsource@^1.1.15", + "_where": "/Users/sylvainfiloni/Documents/HuggingFace_Projects/live-vision/node_modules/@gradio/client", + "bugs": { + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Scott Lee Davis", + "url": "https://github.com/scottleedavis" + }, + { + "name": "Ali Afroozeh", + "url": "https://github.com/afroozeh" + }, + { + "name": "Pedro Gámez", + "url": "https://github.com/snakedrak" + }, + { + "name": "Akuukis", + "url": "https://github.com/Akuukis" + } + ], + "dependencies": {}, + "deprecated": false, + "description": "TypeScript definitions for eventsource", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/eventsource", + "license": "MIT", + "main": "", + "name": "@types/eventsource", + "repository": { + "type": "git", + "url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/eventsource" + }, + "scripts": {}, + "typeScriptVersion": "5.0", + "types": "index.d.ts", + "typesPublisherContentHash": "6a075ca22dc3b8841f58d5e2e758b840c8e2e48ae90c56c69f07cb5694d4a112", + "version": "1.1.15" +} diff --git a/node_modules/@types/mute-stream/LICENSE b/node_modules/@types/mute-stream/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/node_modules/@types/mute-stream/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/node_modules/@types/mute-stream/README.md b/node_modules/@types/mute-stream/README.md new file mode 100644 index 0000000000000000000000000000000000000000..65bfbca18043c1b10ab2d55804ffd55357a17d69 --- /dev/null +++ b/node_modules/@types/mute-stream/README.md @@ -0,0 +1,49 @@ +# Installation +> `npm install --save @types/mute-stream` + +# Summary +This package contains type definitions for mute-stream (https://github.com/isaacs/mute-stream#readme). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/mute-stream. +## [index.d.ts](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/mute-stream/index.d.ts) +````ts +/// + +import { Duplex } from "stream"; + +declare namespace MuteStream { + interface Options { + /** + * Set to a string to replace each character with the specified string when muted. + * (So you can show **** instead of the password, for example.) + */ + replace?: string | undefined; + + /** + * If you are using a replacement char, and also using a prompt with a readline stream + * (as for a Password: ***** input), then specify what the prompt is so that backspace + * will work properly. Otherwise, pressing backspace will overwrite the prompt with the + * replacement character, which is weird. + */ + prompt?: string | undefined; + } +} + +declare class MuteStream extends Duplex { + constructor(options?: MuteStream.Options); + mute: () => void; + unmute: () => void; + isTTY: boolean; +} + +export = MuteStream; + +```` + +### Additional Details + * Last updated: Tue, 07 Nov 2023 09:09:39 GMT + * Dependencies: [@types/node](https://npmjs.com/package/@types/node) + +# Credits +These definitions were written by [Adam Jarret](https://github.com/adamjarret). diff --git a/node_modules/@types/mute-stream/index.d.ts b/node_modules/@types/mute-stream/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fe0acf87b8fca11bd7a5f63cd9b329ee8b826dbc --- /dev/null +++ b/node_modules/@types/mute-stream/index.d.ts @@ -0,0 +1,30 @@ +/// + +import { Duplex } from "stream"; + +declare namespace MuteStream { + interface Options { + /** + * Set to a string to replace each character with the specified string when muted. + * (So you can show **** instead of the password, for example.) + */ + replace?: string | undefined; + + /** + * If you are using a replacement char, and also using a prompt with a readline stream + * (as for a Password: ***** input), then specify what the prompt is so that backspace + * will work properly. Otherwise, pressing backspace will overwrite the prompt with the + * replacement character, which is weird. + */ + prompt?: string | undefined; + } +} + +declare class MuteStream extends Duplex { + constructor(options?: MuteStream.Options); + mute: () => void; + unmute: () => void; + isTTY: boolean; +} + +export = MuteStream; diff --git a/node_modules/@types/mute-stream/package.json b/node_modules/@types/mute-stream/package.json new file mode 100644 index 0000000000000000000000000000000000000000..410023d4db5e85b35048f4fcb490cbd76dcd7845 --- /dev/null +++ b/node_modules/@types/mute-stream/package.json @@ -0,0 +1,55 @@ +{ + "_from": "@types/mute-stream@^0.0.4", + "_id": "@types/mute-stream@0.0.4", + "_inBundle": false, + "_integrity": "sha512-CPM9nzrCPPJHQNA9keH9CVkVI+WR5kMa+7XEs5jcGQ0VoAGnLv242w8lIVgwAEfmE4oufJRaTc9PNLQl0ioAow==", + "_location": "/@types/mute-stream", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@types/mute-stream@^0.0.4", + "name": "@types/mute-stream", + "escapedName": "@types%2fmute-stream", + "scope": "@types", + "rawSpec": "^0.0.4", + "saveSpec": null, + "fetchSpec": "^0.0.4" + }, + "_requiredBy": [ + "/@inquirer/core" + ], + "_resolved": "https://registry.npmjs.org/@types/mute-stream/-/mute-stream-0.0.4.tgz", + "_shasum": "77208e56a08767af6c5e1237be8888e2f255c478", + "_spec": "@types/mute-stream@^0.0.4", + "_where": "/Users/sylvainfiloni/Documents/HuggingFace_Projects/live-vision/node_modules/@inquirer/core", + "bugs": { + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Adam Jarret", + "url": "https://github.com/adamjarret" + } + ], + "dependencies": { + "@types/node": "*" + }, + "deprecated": false, + "description": "TypeScript definitions for mute-stream", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/mute-stream", + "license": "MIT", + "main": "", + "name": "@types/mute-stream", + "repository": { + "type": "git", + "url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/mute-stream" + }, + "scripts": {}, + "typeScriptVersion": "4.5", + "types": "index.d.ts", + "typesPublisherContentHash": "0a0047b7ac14dcaf2bf9afa6933c9ca7e51b2196a8d57e82b9f54b872acd6eb4", + "version": "0.0.4" +} diff --git a/node_modules/@types/node/README.md b/node_modules/@types/node/README.md index 7686130d1d3407a990c31910b85eb64804940eab..2af213c8e31d2e1def418f811fc0eb237db4e72c 100644 --- a/node_modules/@types/node/README.md +++ b/node_modules/@types/node/README.md @@ -1,15 +1,15 @@ -# Installation -> `npm install --save @types/node` - -# Summary -This package contains type definitions for node (https://nodejs.org/). - -# Details -Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node. - -### Additional Details - * Last updated: Wed, 24 Jan 2024 06:08:24 GMT - * Dependencies: [undici-types](https://npmjs.com/package/undici-types) - -# Credits -These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [Alberto Schiabel](https://github.com/jkomyno), [Alvis HT Tang](https://github.com/alvis), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [Chigozirim C.](https://github.com/smac89), [David Junger](https://github.com/touffy), [Deividas Bakanas](https://github.com/DeividasBakanas), [Eugene Y. Q. Shen](https://github.com/eyqs), [Hannes Magnusson](https://github.com/Hannes-Magnusson-CK), [Huw](https://github.com/hoo29), [Kelvin Jin](https://github.com/kjin), [Klaus Meinhardt](https://github.com/ajafff), [Lishude](https://github.com/islishude), [Mariusz Wiktorczyk](https://github.com/mwiktorczyk), [Mohsen Azimi](https://github.com/mohsen1), [Nicolas Even](https://github.com/n-e), [Nikita Galkin](https://github.com/galkin), [Parambir Singh](https://github.com/parambirs), [Sebastian Silbermann](https://github.com/eps1lon), [Thomas den Hollander](https://github.com/ThomasdenH), [Wilco Bakker](https://github.com/WilcoBakker), [wwwy3y3](https://github.com/wwwy3y3), [Samuel Ainsworth](https://github.com/samuela), [Kyle Uehlein](https://github.com/kuehlein), [Thanik Bhongbhibhat](https://github.com/bhongy), [Marcin Kopacz](https://github.com/chyzwar), [Trivikram Kamat](https://github.com/trivikr), [Junxiao Shi](https://github.com/yoursunny), [Ilia Baryshnikov](https://github.com/qwelias), [ExE Boss](https://github.com/ExE-Boss), [Piotr Błażejewicz](https://github.com/peterblazejewicz), [Anna Henningsen](https://github.com/addaleax), [Victor Perin](https://github.com/victorperin), [Yongsheng Zhang](https://github.com/ZYSzys), [NodeJS Contributors](https://github.com/NodeJS), [Linus Unnebäck](https://github.com/LinusU), [wafuwafu13](https://github.com/wafuwafu13), [Matteo Collina](https://github.com/mcollina), and [Dmitry Semigradsky](https://github.com/Semigradsky). +# Installation +> `npm install --save @types/node` + +# Summary +This package contains type definitions for node (https://nodejs.org/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node. + +### Additional Details + * Last updated: Sat, 22 Jun 2024 07:35:32 GMT + * Dependencies: [undici-types](https://npmjs.com/package/undici-types) + +# Credits +These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [Alberto Schiabel](https://github.com/jkomyno), [Alvis HT Tang](https://github.com/alvis), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [Chigozirim C.](https://github.com/smac89), [David Junger](https://github.com/touffy), [Deividas Bakanas](https://github.com/DeividasBakanas), [Eugene Y. Q. Shen](https://github.com/eyqs), [Hannes Magnusson](https://github.com/Hannes-Magnusson-CK), [Huw](https://github.com/hoo29), [Kelvin Jin](https://github.com/kjin), [Klaus Meinhardt](https://github.com/ajafff), [Lishude](https://github.com/islishude), [Mariusz Wiktorczyk](https://github.com/mwiktorczyk), [Mohsen Azimi](https://github.com/mohsen1), [Nikita Galkin](https://github.com/galkin), [Parambir Singh](https://github.com/parambirs), [Sebastian Silbermann](https://github.com/eps1lon), [Thomas den Hollander](https://github.com/ThomasdenH), [Wilco Bakker](https://github.com/WilcoBakker), [wwwy3y3](https://github.com/wwwy3y3), [Samuel Ainsworth](https://github.com/samuela), [Kyle Uehlein](https://github.com/kuehlein), [Thanik Bhongbhibhat](https://github.com/bhongy), [Marcin Kopacz](https://github.com/chyzwar), [Trivikram Kamat](https://github.com/trivikr), [Junxiao Shi](https://github.com/yoursunny), [Ilia Baryshnikov](https://github.com/qwelias), [ExE Boss](https://github.com/ExE-Boss), [Piotr Błażejewicz](https://github.com/peterblazejewicz), [Anna Henningsen](https://github.com/addaleax), [Victor Perin](https://github.com/victorperin), [Yongsheng Zhang](https://github.com/ZYSzys), [NodeJS Contributors](https://github.com/NodeJS), [Linus Unnebäck](https://github.com/LinusU), [wafuwafu13](https://github.com/wafuwafu13), [Matteo Collina](https://github.com/mcollina), and [Dmitry Semigradsky](https://github.com/Semigradsky). diff --git a/node_modules/@types/node/assert.d.ts b/node_modules/@types/node/assert.d.ts index cd821433575b42840106da9995aaaec26eb0edc7..4e465c5751655c6c99b515d61baf5de6557ddd91 100644 --- a/node_modules/@types/node/assert.d.ts +++ b/node_modules/@types/node/assert.d.ts @@ -1,7 +1,7 @@ /** * The `node:assert` module provides a set of assertion functions for verifying * invariants. - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/assert.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/assert.js) */ declare module "assert" { /** @@ -12,7 +12,7 @@ declare module "assert" { function assert(value: unknown, message?: string | Error): asserts value; namespace assert { /** - * Indicates the failure of an assertion. All errors thrown by the `node:assert`module will be instances of the `AssertionError` class. + * Indicates the failure of an assertion. All errors thrown by the `node:assert` module will be instances of the `AssertionError` class. */ class AssertionError extends Error { /** @@ -76,7 +76,7 @@ declare module "assert" { * @since v14.2.0, v12.19.0 * @param [fn='A no-op function'] * @param [exact=1] - * @return that wraps `fn`. + * @return A function that wraps `fn`. */ calls(exact?: number): () => void; calls any>(fn?: Func, exact?: number): Func; @@ -96,8 +96,7 @@ declare module "assert" { * [{ thisArg: undefined, arguments: [1, 2, 3] }]); * ``` * @since v18.8.0, v16.18.0 - * @param fn - * @return An Array with all the calls to a tracked function. + * @return An array with all the calls to a tracked function. */ getCalls(fn: Function): CallTrackerCall[]; /** @@ -130,12 +129,11 @@ declare module "assert" { * // ] * ``` * @since v14.2.0, v12.19.0 - * @return An Array of objects containing information about the wrapper functions returned by `calls`. + * @return An array of objects containing information about the wrapper functions returned by {@link tracker.calls()}. */ report(): CallTrackerReportInformation[]; /** - * Reset calls of the call tracker. - * If a tracked function is passed as an argument, the calls will be reset for it. + * Reset calls of the call tracker. If a tracked function is passed as an argument, the calls will be reset for it. * If no arguments are passed, all tracked functions will be reset. * * ```js @@ -158,7 +156,7 @@ declare module "assert" { */ reset(fn?: Function): void; /** - * Iterates through the list of functions passed to `tracker.calls()` and will throw an error for functions that + * Iterates through the list of functions passed to {@link tracker.calls()} and will throw an error for functions that * have not been called the expected number of times. * * ```js @@ -232,10 +230,10 @@ declare module "assert" { stackStartFn?: Function, ): never; /** - * Tests if `value` is truthy. It is equivalent to`assert.equal(!!value, true, message)`. + * Tests if `value` is truthy. It is equivalent to `assert.equal(!!value, true, message)`. * - * If `value` is not truthy, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is `undefined`, a default - * error message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. + * If `value` is not truthy, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is `undefined`, a default + * error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`. * If no arguments are passed in at all `message` will be set to the string:`` 'No value argument passed to `assert.ok()`' ``. * * Be aware that in the `repl` the error message will be different to the one @@ -317,8 +315,8 @@ declare module "assert" { * // AssertionError: { a: { b: 1 } } == { a: { b: 1 } } * ``` * - * If the values are not equal, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is undefined, a default - * error message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. + * If the values are not equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default + * error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`. * @since v0.1.21 */ function equal(actual: unknown, expected: unknown, message?: string | Error): void; @@ -347,8 +345,8 @@ declare module "assert" { * // AssertionError: 1 != '1' * ``` * - * If the values are equal, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is undefined, a default error - * message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. + * If the values are equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default error + * message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`. * @since v0.1.21 */ function notEqual(actual: unknown, expected: unknown, message?: string | Error): void; @@ -414,8 +412,8 @@ declare module "assert" { * // OK * ``` * - * If the values are deeply equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a default - * error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown + * If the values are deeply equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default + * error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown * instead of the `AssertionError`. * @since v0.1.21 */ @@ -452,8 +450,8 @@ declare module "assert" { * // TypeError: Inputs are not identical * ``` * - * If the values are not strictly equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a - * default error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown + * If the values are not strictly equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a + * default error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown * instead of the `AssertionError`. * @since v0.1.21 */ @@ -477,8 +475,8 @@ declare module "assert" { * // OK * ``` * - * If the values are strictly equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a - * default error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown + * If the values are strictly equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a + * default error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown * instead of the `AssertionError`. * @since v0.1.21 */ @@ -519,7 +517,7 @@ declare module "assert" { * using an object, it is also possible to use a regular expression, when * validating against a string property. See below for examples. * - * If specified, `message` will be appended to the message provided by the`AssertionError` if the `fn` call fails to throw or in case the error validation + * If specified, `message` will be appended to the message provided by the `AssertionError` if the `fn` call fails to throw or in case the error validation * fails. * * Custom validation object/error instance: @@ -649,8 +647,8 @@ declare module "assert" { * ``` * * `error` cannot be a string. If a string is provided as the second - * argument, then `error` is assumed to be omitted and the string will be used for`message` instead. This can lead to easy-to-miss mistakes. Using the same - * message as the thrown error message is going to result in an`ERR_AMBIGUOUS_ARGUMENT` error. Please read the example below carefully if using + * argument, then `error` is assumed to be omitted and the string will be used for `message` instead. This can lead to easy-to-miss mistakes. Using the same + * message as the thrown error message is going to result in an `ERR_AMBIGUOUS_ARGUMENT` error. Please read the example below carefully if using * a string as the second argument gets considered: * * ```js @@ -703,9 +701,9 @@ declare module "assert" { * adding a comment next to the specific code path that should not throw and keep * error messages as expressive as possible. * - * When `assert.doesNotThrow()` is called, it will immediately call the `fn`function. + * When `assert.doesNotThrow()` is called, it will immediately call the `fn` function. * - * If an error is thrown and it is the same type as that specified by the `error`parameter, then an `AssertionError` is thrown. If the error is of a + * If an error is thrown and it is the same type as that specified by the `error` parameter, then an `AssertionError` is thrown. If the error is of a * different type, or if the `error` parameter is undefined, the error is * propagated back to the caller. * @@ -741,7 +739,7 @@ declare module "assert" { * ); * ``` * - * If an `AssertionError` is thrown and a value is provided for the `message`parameter, the value of `message` will be appended to the `AssertionError` message: + * If an `AssertionError` is thrown and a value is provided for the `message` parameter, the value of `message` will be appended to the `AssertionError` message: * * ```js * import assert from 'node:assert/strict'; @@ -762,7 +760,7 @@ declare module "assert" { /** * Throws `value` if `value` is not `undefined` or `null`. This is useful when * testing the `error` argument in callbacks. The stack trace contains all frames - * from the error passed to `ifError()` including the potential new frames for`ifError()` itself. + * from the error passed to `ifError()` including the potential new frames for `ifError()` itself. * * ```js * import assert from 'node:assert/strict'; @@ -797,18 +795,18 @@ declare module "assert" { * calls the function and awaits the returned promise to complete. It will then * check that the promise is rejected. * - * If `asyncFn` is a function and it throws an error synchronously,`assert.rejects()` will return a rejected `Promise` with that error. If the - * function does not return a promise, `assert.rejects()` will return a rejected`Promise` with an `ERR_INVALID_RETURN_VALUE` error. In both cases the error - * handler is skipped. + * If `asyncFn` is a function and it throws an error synchronously, `assert.rejects()` will return a rejected `Promise` with that error. If the + * function does not return a promise, `assert.rejects()` will return a rejected `Promise` with an [ERR_INVALID_RETURN_VALUE](https://nodejs.org/docs/latest-v20.x/api/errors.html#err_invalid_return_value) + * error. In both cases the error handler is skipped. * * Besides the async nature to await the completion behaves identically to {@link throws}. * * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, * an object where each property will be tested for, or an instance of error where - * each property will be tested for including the non-enumerable `message` and`name` properties. + * each property will be tested for including the non-enumerable `message` and `name` properties. * - * If specified, `message` will be the message provided by the `AssertionError` if the `asyncFn` fails to reject. + * If specified, `message` will be the message provided by the `{@link AssertionError}` if the `asyncFn` fails to reject. * * ```js * import assert from 'node:assert/strict'; @@ -850,10 +848,9 @@ declare module "assert" { * }); * ``` * - * `error` cannot be a string. If a string is provided as the second - * argument, then `error` is assumed to be omitted and the string will be used for`message` instead. This can lead to easy-to-miss mistakes. Please read the - * example in {@link throws} carefully if using a string as the second - * argument gets considered. + * `error` cannot be a string. If a string is provided as the second argument, then `error` is assumed to + * be omitted and the string will be used for `message` instead. This can lead to easy-to-miss mistakes. Please read the + * example in {@link throws} carefully if using a string as the second argument gets considered. * @since v10.0.0 */ function rejects(block: (() => Promise) | Promise, message?: string | Error): Promise; @@ -867,9 +864,9 @@ declare module "assert" { * calls the function and awaits the returned promise to complete. It will then * check that the promise is not rejected. * - * If `asyncFn` is a function and it throws an error synchronously,`assert.doesNotReject()` will return a rejected `Promise` with that error. If + * If `asyncFn` is a function and it throws an error synchronously, `assert.doesNotReject()` will return a rejected `Promise` with that error. If * the function does not return a promise, `assert.doesNotReject()` will return a - * rejected `Promise` with an `ERR_INVALID_RETURN_VALUE` error. In both cases + * rejected `Promise` with an [ERR_INVALID_RETURN_VALUE](https://nodejs.org/docs/latest-v20.x/api/errors.html#err_invalid_return_value) error. In both cases * the error handler is skipped. * * Using `assert.doesNotReject()` is actually not useful because there is little @@ -929,10 +926,10 @@ declare module "assert" { * // OK * ``` * - * If the values do not match, or if the `string` argument is of another type than`string`, an `AssertionError` is thrown with a `message` property set equal + * If the values do not match, or if the `string` argument is of another type than `string`, an `{@link AssertionError}` is thrown with a `message` property set equal * to the value of the `message` parameter. If the `message` parameter is * undefined, a default error message is assigned. If the `message` parameter is an - * instance of an `Error` then it will be thrown instead of the `AssertionError`. + * instance of an [Error](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) then it will be thrown instead of the `{@link AssertionError}`. * @since v13.6.0, v12.16.0 */ function match(value: string, regExp: RegExp, message?: string | Error): void; @@ -952,13 +949,60 @@ declare module "assert" { * // OK * ``` * - * If the values do match, or if the `string` argument is of another type than`string`, an `AssertionError` is thrown with a `message` property set equal + * If the values do match, or if the `string` argument is of another type than `string`, an `{@link AssertionError}` is thrown with a `message` property set equal * to the value of the `message` parameter. If the `message` parameter is * undefined, a default error message is assigned. If the `message` parameter is an - * instance of an `Error` then it will be thrown instead of the `AssertionError`. + * instance of an [Error](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) then it will be thrown instead of the `{@link AssertionError}`. * @since v13.6.0, v12.16.0 */ function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void; + /** + * In strict assertion mode, non-strict methods behave like their corresponding strict methods. For example, + * {@link deepEqual} will behave like {@link deepStrictEqual}. + * + * In strict assertion mode, error messages for objects display a diff. In legacy assertion mode, error + * messages for objects display the objects, often truncated. + * + * To use strict assertion mode: + * + * ```js + * import { strict as assert } from 'node:assert';COPY + * import assert from 'node:assert/strict'; + * ``` + * + * Example error diff: + * + * ```js + * import { strict as assert } from 'node:assert'; + * + * assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]); + * // AssertionError: Expected inputs to be strictly deep-equal: + * // + actual - expected ... Lines skipped + * // + * // [ + * // [ + * // ... + * // 2, + * // + 3 + * // - '3' + * // ], + * // ... + * // 5 + * // ] + * ``` + * + * To deactivate the colors, use the `NO_COLOR` or `NODE_DISABLE_COLORS` environment variables. This will also + * deactivate the colors in the REPL. For more on color support in terminal environments, read the tty + * `getColorDepth()` documentation. + * + * @since v15.0.0, v13.9.0, v12.16.2, v9.9.0 + */ + namespace strict { + type AssertionError = assert.AssertionError; + type AssertPredicate = assert.AssertPredicate; + type CallTrackerCall = assert.CallTrackerCall; + type CallTrackerReportInformation = assert.CallTrackerReportInformation; + } const strict: & Omit< typeof assert, diff --git a/node_modules/@types/node/async_hooks.d.ts b/node_modules/@types/node/async_hooks.d.ts index 0667a6150af717a759e15e4fe04b6d29fe533411..f5432e238d14c47ed12bcf13522531559e16cf42 100644 --- a/node_modules/@types/node/async_hooks.d.ts +++ b/node_modules/@types/node/async_hooks.d.ts @@ -2,8 +2,8 @@ * We strongly discourage the use of the `async_hooks` API. * Other APIs that can cover most of its use cases include: * - * * `AsyncLocalStorage` tracks async context - * * `process.getActiveResourcesInfo()` tracks active resources + * * [`AsyncLocalStorage`](https://nodejs.org/docs/latest-v20.x/api/async_context.html#class-asynclocalstorage) tracks async context + * * [`process.getActiveResourcesInfo()`](https://nodejs.org/docs/latest-v20.x/api/process.html#processgetactiveresourcesinfo) tracks active resources * * The `node:async_hooks` module provides an API to track asynchronous resources. * It can be accessed using: @@ -12,7 +12,7 @@ * import async_hooks from 'node:async_hooks'; * ``` * @experimental - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/async_hooks.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/async_hooks.js) */ declare module "async_hooks" { /** @@ -44,7 +44,7 @@ declare module "async_hooks" { * ``` * * Promise contexts may not get precise `executionAsyncIds` by default. - * See the section on `promise execution tracking`. + * See the section on [promise execution tracking](https://nodejs.org/docs/latest-v20.x/api/async_hooks.html#promise-execution-tracking). * @since v8.1.0 * @return The `asyncId` of the current execution context. Useful to track when something calls. */ @@ -117,17 +117,17 @@ declare module "async_hooks" { * ``` * * Promise contexts may not get valid `triggerAsyncId`s by default. See - * the section on `promise execution tracking`. + * the section on [promise execution tracking](https://nodejs.org/docs/latest-v20.x/api/async_hooks.html#promise-execution-tracking). * @return The ID of the resource responsible for calling the callback that is currently being executed. */ function triggerAsyncId(): number; interface HookCallbacks { /** * Called when a class is constructed that has the possibility to emit an asynchronous event. - * @param asyncId a unique ID for the async resource - * @param type the type of the async resource - * @param triggerAsyncId the unique ID of the async resource in whose execution context this async resource was created - * @param resource reference to the resource representing the async operation, needs to be released during destroy + * @param asyncId A unique ID for the async resource + * @param type The type of the async resource + * @param triggerAsyncId The unique ID of the async resource in whose execution context this async resource was created + * @param resource Reference to the resource representing the async operation, needs to be released during destroy */ init?(asyncId: number, type: string, triggerAsyncId: number, resource: object): void; /** @@ -137,7 +137,9 @@ declare module "async_hooks" { */ before?(asyncId: number): void; /** - * Called immediately after the callback specified in before is completed. + * Called immediately after the callback specified in `before` is completed. + * + * If an uncaught exception occurs during execution of the callback, then `after` will run after the `'uncaughtException'` event is emitted or a `domain`'s handler runs. * @param asyncId the unique identifier assigned to the resource which has executed the callback. */ after?(asyncId: number): void; @@ -321,7 +323,7 @@ declare module "async_hooks" { /** * This class creates stores that stay coherent through asynchronous operations. * - * While you can create your own implementation on top of the `node:async_hooks`module, `AsyncLocalStorage` should be preferred as it is a performant and memory + * While you can create your own implementation on top of the `node:async_hooks` module, `AsyncLocalStorage` should be preferred as it is a performant and memory * safe implementation that involves significant optimizations that are non-obvious * to implement. * @@ -407,12 +409,12 @@ declare module "async_hooks" { static snapshot(): (fn: (...args: TArgs) => R, ...args: TArgs) => R; /** * Disables the instance of `AsyncLocalStorage`. All subsequent calls - * to `asyncLocalStorage.getStore()` will return `undefined` until`asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()` is called again. + * to `asyncLocalStorage.getStore()` will return `undefined` until `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()` is called again. * * When calling `asyncLocalStorage.disable()`, all current contexts linked to the * instance will be exited. * - * Calling `asyncLocalStorage.disable()` is required before the`asyncLocalStorage` can be garbage collected. This does not apply to stores + * Calling `asyncLocalStorage.disable()` is required before the `asyncLocalStorage` can be garbage collected. This does not apply to stores * provided by the `asyncLocalStorage`, as those objects are garbage collected * along with the corresponding async resources. * @@ -465,7 +467,7 @@ declare module "async_hooks" { /** * Runs a function synchronously outside of a context and returns its * return value. The store is not accessible within the callback function or - * the asynchronous operations created within the callback. Any `getStore()`call done within the callback function will always return `undefined`. + * the asynchronous operations created within the callback. Any `getStore()` call done within the callback function will always return `undefined`. * * The optional `args` are passed to the callback function. * @@ -511,7 +513,7 @@ declare module "async_hooks" { * This transition will continue for the _entire_ synchronous execution. * This means that if, for example, the context is entered within an event * handler subsequent event handlers will also run within that context unless - * specifically bound to another context with an `AsyncResource`. That is why`run()` should be preferred over `enterWith()` unless there are strong reasons + * specifically bound to another context with an `AsyncResource`. That is why `run()` should be preferred over `enterWith()` unless there are strong reasons * to use the latter method. * * ```js diff --git a/node_modules/@types/node/buffer.d.ts b/node_modules/@types/node/buffer.d.ts index 2fa2e745ffbedb44e198850165d2fd17968b8775..abdf9a6fd2b0921a90dfe4c54f874ac02283f506 100644 --- a/node_modules/@types/node/buffer.d.ts +++ b/node_modules/@types/node/buffer.d.ts @@ -41,7 +41,7 @@ * // Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74]. * const buf7 = Buffer.from('tést', 'latin1'); * ``` - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/buffer.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/buffer.js) */ declare module "buffer" { import { BinaryLike } from "node:crypto"; @@ -88,7 +88,7 @@ declare module "buffer" { * Throws if the `fromEnc` or `toEnc` specify invalid character encodings or if * conversion from `fromEnc` to `toEnc` is not permitted. * - * Encodings supported by `buffer.transcode()` are: `'ascii'`, `'utf8'`,`'utf16le'`, `'ucs2'`, `'latin1'`, and `'binary'`. + * Encodings supported by `buffer.transcode()` are: `'ascii'`, `'utf8'`, `'utf16le'`, `'ucs2'`, `'latin1'`, and `'binary'`. * * The transcoding process will use substitution characters if a given byte * sequence cannot be adequately represented in the target encoding. For instance: @@ -128,9 +128,10 @@ declare module "buffer" { */ export interface BlobOptions { /** - * @default 'utf8' + * One of either `'transparent'` or `'native'`. When set to `'native'`, line endings in string source parts + * will be converted to the platform native line-ending as specified by `require('node:os').EOL`. */ - encoding?: BufferEncoding | undefined; + endings?: "transparent" | "native"; /** * The Blob content-type. The intent is for `type` to convey * the MIME media type of the data, however no validation of the type format @@ -162,7 +163,7 @@ declare module "buffer" { * * String sources are also copied into the `Blob`. */ - constructor(sources: Array, options?: BlobOptions); + constructor(sources: Array, options?: BlobOptions); /** * Returns a promise that fulfills with an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing a copy of * the `Blob` data. @@ -310,12 +311,12 @@ declare module "buffer" { * * If `array` is an `Array`\-like object (that is, one with a `length` property of * type `number`), it is treated as if it is an array, unless it is a `Buffer` or - * a `Uint8Array`. This means all other `TypedArray` variants get treated as an`Array`. To create a `Buffer` from the bytes backing a `TypedArray`, use `Buffer.copyBytesFrom()`. + * a `Uint8Array`. This means all other `TypedArray` variants get treated as an `Array`. To create a `Buffer` from the bytes backing a `TypedArray`, use `Buffer.copyBytesFrom()`. * * A `TypeError` will be thrown if `array` is not an `Array` or another type * appropriate for `Buffer.from()` variants. * - * `Buffer.from(array)` and `Buffer.from(string)` may also use the internal`Buffer` pool like `Buffer.allocUnsafe()` does. + * `Buffer.from(array)` and `Buffer.from(string)` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does. * @since v5.10.0 */ from( @@ -415,13 +416,13 @@ declare module "buffer" { * @return The number of bytes contained within `string`. */ byteLength( - string: string | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer, + string: string | Buffer | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer, encoding?: BufferEncoding, ): number; /** - * Returns a new `Buffer` which is the result of concatenating all the `Buffer`instances in the `list` together. + * Returns a new `Buffer` which is the result of concatenating all the `Buffer` instances in the `list` together. * - * If the list has no items, or if the `totalLength` is 0, then a new zero-length`Buffer` is returned. + * If the list has no items, or if the `totalLength` is 0, then a new zero-length `Buffer` is returned. * * If `totalLength` is not provided, it is calculated from the `Buffer` instances * in `list` by adding their lengths. @@ -470,12 +471,12 @@ declare module "buffer" { * ``` * @since v19.8.0 * @param view The {TypedArray} to copy. - * @param [offset=': 0'] The starting offset within `view`. + * @param [offset=0] The starting offset within `view`. * @param [length=view.length - offset] The number of elements from `view` to copy. */ copyBytesFrom(view: NodeJS.TypedArray, offset?: number, length?: number): Buffer; /** - * Compares `buf1` to `buf2`, typically for the purpose of sorting arrays of`Buffer` instances. This is equivalent to calling `buf1.compare(buf2)`. + * Compares `buf1` to `buf2`, typically for the purpose of sorting arrays of `Buffer` instances. This is equivalent to calling `buf1.compare(buf2)`. * * ```js * import { Buffer } from 'node:buffer'; @@ -563,8 +564,8 @@ declare module "buffer" { * A `TypeError` will be thrown if `size` is not a number. * * The `Buffer` module pre-allocates an internal `Buffer` instance of - * size `Buffer.poolSize` that is used as a pool for the fast allocation of new`Buffer` instances created using `Buffer.allocUnsafe()`, `Buffer.from(array)`, - * and `Buffer.concat()` only when `size` is less than`Buffer.poolSize >>> 1` (floor of `Buffer.poolSize` divided by two). + * size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe()`, `Buffer.from(array)`, + * and `Buffer.concat()` only when `size` is less than `Buffer.poolSize >>> 1` (floor of `Buffer.poolSize` divided by two). * * Use of this pre-allocated internal memory pool is a key difference between * calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. @@ -780,7 +781,7 @@ declare module "buffer" { * // (This result is equal to: [buf1, buf3, buf2].) * ``` * - * The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd`arguments can be used to limit the comparison to specific ranges within `target`and `buf` respectively. + * The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd` arguments can be used to limit the comparison to specific ranges within `target` and `buf` respectively. * * ```js * import { Buffer } from 'node:buffer'; @@ -796,7 +797,7 @@ declare module "buffer" { * // Prints: 1 * ``` * - * `ERR_OUT_OF_RANGE` is thrown if `targetStart < 0`, `sourceStart < 0`,`targetEnd > target.byteLength`, or `sourceEnd > source.byteLength`. + * `ERR_OUT_OF_RANGE` is thrown if `targetStart < 0`, `sourceStart < 0`, `targetEnd > target.byteLength`, or `sourceEnd > source.byteLength`. * @since v0.11.13 * @param target A `Buffer` or {@link Uint8Array} with which to compare `buf`. * @param [targetStart=0] The offset within `target` at which to begin comparison. @@ -1214,7 +1215,7 @@ declare module "buffer" { */ readBigInt64LE(offset?: number): bigint; /** - * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as an unsigned, little-endian integer supporting + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as an unsigned, little-endian integer supporting * up to 48 bits of accuracy. * * This function is also available under the `readUintLE` alias. @@ -1238,7 +1239,7 @@ declare module "buffer" { */ readUintLE(offset: number, byteLength: number): number; /** - * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as an unsigned big-endian integer supporting + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as an unsigned big-endian integer supporting * up to 48 bits of accuracy. * * This function is also available under the `readUintBE` alias. @@ -1264,7 +1265,7 @@ declare module "buffer" { */ readUintBE(offset: number, byteLength: number): number; /** - * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as a little-endian, two's complement signed value + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as a little-endian, two's complement signed value * supporting up to 48 bits of accuracy. * * ```js @@ -1281,7 +1282,7 @@ declare module "buffer" { */ readIntLE(offset: number, byteLength: number): number; /** - * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as a big-endian, two's complement signed value + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as a big-endian, two's complement signed value * supporting up to 48 bits of accuracy. * * ```js @@ -1328,7 +1329,7 @@ declare module "buffer" { */ readUint8(offset?: number): number; /** - * Reads an unsigned, little-endian 16-bit integer from `buf` at the specified`offset`. + * Reads an unsigned, little-endian 16-bit integer from `buf` at the specified `offset`. * * This function is also available under the `readUint16LE` alias. * @@ -1701,7 +1702,7 @@ declare module "buffer" { */ writeUint8(value: number, offset?: number): number; /** - * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid unsigned 16-bit integer. Behavior is undefined when `value` is + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid unsigned 16-bit integer. Behavior is undefined when `value` is * anything other than an unsigned 16-bit integer. * * This function is also available under the `writeUint16LE` alias. @@ -1729,7 +1730,7 @@ declare module "buffer" { */ writeUint16LE(value: number, offset?: number): number; /** - * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid unsigned 16-bit integer. Behavior is undefined when `value`is anything other than an + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid unsigned 16-bit integer. Behavior is undefined when `value`is anything other than an * unsigned 16-bit integer. * * This function is also available under the `writeUint16BE` alias. @@ -1757,7 +1758,7 @@ declare module "buffer" { */ writeUint16BE(value: number, offset?: number): number; /** - * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid unsigned 32-bit integer. Behavior is undefined when `value` is + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid unsigned 32-bit integer. Behavior is undefined when `value` is * anything other than an unsigned 32-bit integer. * * This function is also available under the `writeUint32LE` alias. @@ -1784,7 +1785,7 @@ declare module "buffer" { */ writeUint32LE(value: number, offset?: number): number; /** - * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid unsigned 32-bit integer. Behavior is undefined when `value`is anything other than an + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid unsigned 32-bit integer. Behavior is undefined when `value`is anything other than an * unsigned 32-bit integer. * * This function is also available under the `writeUint32BE` alias. @@ -1835,7 +1836,7 @@ declare module "buffer" { */ writeInt8(value: number, offset?: number): number; /** - * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid signed 16-bit integer. Behavior is undefined when `value` is * anything other than a signed 16-bit integer. * * The `value` is interpreted and written as a two's complement signed integer. @@ -1857,7 +1858,7 @@ declare module "buffer" { */ writeInt16LE(value: number, offset?: number): number; /** - * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid signed 16-bit integer. Behavior is undefined when `value` is * anything other than a signed 16-bit integer. * * The `value` is interpreted and written as a two's complement signed integer. @@ -1879,7 +1880,7 @@ declare module "buffer" { */ writeInt16BE(value: number, offset?: number): number; /** - * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid signed 32-bit integer. Behavior is undefined when `value` is * anything other than a signed 32-bit integer. * * The `value` is interpreted and written as a two's complement signed integer. @@ -1901,7 +1902,7 @@ declare module "buffer" { */ writeInt32LE(value: number, offset?: number): number; /** - * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid signed 32-bit integer. Behavior is undefined when `value` is * anything other than a signed 32-bit integer. * * The `value` is interpreted and written as a two's complement signed integer. @@ -1963,7 +1964,7 @@ declare module "buffer" { */ writeFloatBE(value: number, offset?: number): number; /** - * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a JavaScript number. Behavior is undefined when `value` is anything + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a JavaScript number. Behavior is undefined when `value` is anything * other than a JavaScript number. * * ```js @@ -1983,7 +1984,7 @@ declare module "buffer" { */ writeDoubleLE(value: number, offset?: number): number; /** - * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a JavaScript number. Behavior is undefined when `value` is anything + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a JavaScript number. Behavior is undefined when `value` is anything * other than a JavaScript number. * * ```js @@ -2065,7 +2066,7 @@ declare module "buffer" { /** * If `value` is: * - * * a string, `value` is interpreted according to the character encoding in`encoding`. + * * a string, `value` is interpreted according to the character encoding in `encoding`. * * a `Buffer` or [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array), `value` will be used in its entirety. * To compare a partial `Buffer`, use `buf.subarray`. * * a number, `value` will be interpreted as an unsigned 8-bit integer @@ -2097,7 +2098,7 @@ declare module "buffer" { * // Prints: 6 * ``` * - * If `value` is not a string, number, or `Buffer`, this method will throw a`TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * If `value` is not a string, number, or `Buffer`, this method will throw a `TypeError`. If `value` is a number, it will be coerced to a valid byte value, * an integer between 0 and 255. * * If `byteOffset` is not a number, it will be coerced to a number. If the result @@ -2163,7 +2164,7 @@ declare module "buffer" { * // Prints: 4 * ``` * - * If `value` is not a string, number, or `Buffer`, this method will throw a`TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * If `value` is not a string, number, or `Buffer`, this method will throw a `TypeError`. If `value` is a number, it will be coerced to a valid byte value, * an integer between 0 and 255. * * If `byteOffset` is not a number, it will be coerced to a number. Any arguments @@ -2322,7 +2323,7 @@ declare module "buffer" { * **and should never be used in new code, because they use strings to represent** * **binary data and predate the introduction of typed arrays in JavaScript.** * **For code running using Node.js APIs, converting between base64-encoded strings** - * **and binary data should be performed using `Buffer.from(str, 'base64')` and`buf.toString('base64')`.** + * **and binary data should be performed using `Buffer.from(str, 'base64')` and `buf.toString('base64')`.** * @since v15.13.0, v14.17.0 * @legacy Use `Buffer.from(data, 'base64')` instead. * @param data The Base64-encoded input string. @@ -2338,7 +2339,7 @@ declare module "buffer" { * **and should never be used in new code, because they use strings to represent** * **binary data and predate the introduction of typed arrays in JavaScript.** * **For code running using Node.js APIs, converting between base64-encoded strings** - * **and binary data should be performed using `Buffer.from(str, 'base64')` and`buf.toString('base64')`.** + * **and binary data should be performed using `Buffer.from(str, 'base64')` and `buf.toString('base64')`.** * @since v15.13.0, v14.17.0 * @legacy Use `buf.toString('base64')` instead. * @param data An ASCII (Latin1) string. diff --git a/node_modules/@types/node/child_process.d.ts b/node_modules/@types/node/child_process.d.ts index a97532b474dd66ee96bf1c13335136727f4c0398..b642adcdd67ff525022746492decc7ced659ed12 100644 --- a/node_modules/@types/node/child_process.d.ts +++ b/node_modules/@types/node/child_process.d.ts @@ -25,7 +25,7 @@ * limited (and platform-specific) capacity. If the subprocess writes to * stdout in excess of that limit without the output being captured, the * subprocess blocks waiting for the pipe buffer to accept more data. This is - * identical to the behavior of pipes in the shell. Use the `{ stdio: 'ignore' }`option if the output will not be consumed. + * identical to the behavior of pipes in the shell. Use the `{ stdio: 'ignore' }` option if the output will not be consumed. * * The command lookup is performed using the `options.env.PATH` environment * variable if `env` is in the `options` object. Otherwise, `process.env.PATH` is @@ -38,7 +38,7 @@ * lexicographically sorts the `env` keys and uses the first one that * case-insensitively matches. Only first (in lexicographic order) entry will be * passed to the subprocess. This might lead to issues on Windows when passing - * objects to the `env` option that have multiple variants of the same key, such as`PATH` and `Path`. + * objects to the `env` option that have multiple variants of the same key, such as `PATH` and `Path`. * * The {@link spawn} method spawns the child process asynchronously, * without blocking the Node.js event loop. The {@link spawnSync} function provides equivalent functionality in a synchronous manner that blocks @@ -63,16 +63,17 @@ * For certain use cases, such as automating shell scripts, the `synchronous counterparts` may be more convenient. In many cases, however, * the synchronous methods can have significant impact on performance due to * stalling the event loop while spawned processes complete. - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/child_process.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/child_process.js) */ declare module "child_process" { import { ObjectEncodingOptions } from "node:fs"; import { Abortable, EventEmitter } from "node:events"; + import * as dgram from "node:dgram"; import * as net from "node:net"; import { Pipe, Readable, Stream, Writable } from "node:stream"; import { URL } from "node:url"; type Serializable = string | object | number | boolean | bigint; - type SendHandle = net.Socket | net.Server; + type SendHandle = net.Socket | net.Server | dgram.Socket | undefined; /** * Instances of the `ChildProcess` represent spawned child processes. * @@ -94,7 +95,7 @@ declare module "child_process" { * `subprocess.stdin` is an alias for `subprocess.stdio[0]`. Both properties will * refer to the same value. * - * The `subprocess.stdin` property can be `null` or `undefined`if the child process could not be successfully spawned. + * The `subprocess.stdin` property can be `null` or `undefined` if the child process could not be successfully spawned. * @since v0.1.90 */ stdin: Writable | null; @@ -117,7 +118,7 @@ declare module "child_process" { * }); * ``` * - * The `subprocess.stdout` property can be `null` or `undefined`if the child process could not be successfully spawned. + * The `subprocess.stdout` property can be `null` or `undefined` if the child process could not be successfully spawned. * @since v0.1.90 */ stdout: Readable | null; @@ -130,7 +131,7 @@ declare module "child_process" { * `subprocess.stderr` is an alias for `subprocess.stdio[2]`. Both properties will * refer to the same value. * - * The `subprocess.stderr` property can be `null` or `undefined`if the child process could not be successfully spawned. + * The `subprocess.stderr` property can be `null` or `undefined` if the child process could not be successfully spawned. * @since v0.1.90 */ stderr: Readable | null; @@ -143,7 +144,7 @@ declare module "child_process" { /** * A sparse array of pipes to the child process, corresponding with positions in * the `stdio` option passed to {@link spawn} that have been set - * to the value `'pipe'`. `subprocess.stdio[0]`, `subprocess.stdio[1]`, and`subprocess.stdio[2]` are also available as `subprocess.stdin`,`subprocess.stdout`, and `subprocess.stderr`, + * to the value `'pipe'`. `subprocess.stdio[0]`, `subprocess.stdio[1]`, and `subprocess.stdio[2]` are also available as `subprocess.stdin`, `subprocess.stdout`, and `subprocess.stderr`, * respectively. * * In the following example, only the child's fd `1` (stdout) is configured as a @@ -212,7 +213,7 @@ declare module "child_process" { readonly pid?: number | undefined; /** * The `subprocess.connected` property indicates whether it is still possible to - * send and receive messages from a child process. When `subprocess.connected` is`false`, it is no longer possible to send or receive messages. + * send and receive messages from a child process. When `subprocess.connected` is `false`, it is no longer possible to send or receive messages. * @since v0.7.2 */ readonly connected: boolean; @@ -272,7 +273,7 @@ declare module "child_process" { * See [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for reference. * * On Windows, where POSIX signals do not exist, the `signal` argument will be - * ignored, and the process will be killed forcefully and abruptly (similar to`'SIGKILL'`). + * ignored, and the process will be killed forcefully and abruptly (similar to `'SIGKILL'`). * See `Signal Events` for more details. * * On Linux, child processes of child processes will not be terminated @@ -346,20 +347,20 @@ declare module "child_process" { * * There is a special case when sending a `{cmd: 'NODE_foo'}` message. Messages * containing a `NODE_` prefix in the `cmd` property are reserved for use within - * Node.js core and will not be emitted in the child's `'message'` event. Rather, such messages are emitted using the`'internalMessage'` event and are consumed internally by Node.js. - * Applications should avoid using such messages or listening for`'internalMessage'` events as it is subject to change without notice. + * Node.js core and will not be emitted in the child's `'message'` event. Rather, such messages are emitted using the `'internalMessage'` event and are consumed internally by Node.js. + * Applications should avoid using such messages or listening for `'internalMessage'` events as it is subject to change without notice. * * The optional `sendHandle` argument that may be passed to `subprocess.send()` is * for passing a TCP server or socket object to the child process. The child will * receive the object as the second argument passed to the callback function - * registered on the `'message'` event. Any data that is received - * and buffered in the socket will not be sent to the child. + * registered on the `'message'` event. Any data that is received and buffered in + * the socket will not be sent to the child. Sending IPC sockets is not supported on Windows. * * The optional `callback` is a function that is invoked after the message is * sent but before the child may have received it. The function is called with a * single argument: `null` on success, or an `Error` object on failure. * - * If no `callback` function is provided and the message cannot be sent, an`'error'` event will be emitted by the `ChildProcess` object. This can + * If no `callback` function is provided and the message cannot be sent, an `'error'` event will be emitted by the `ChildProcess` object. This can * happen, for instance, when the child process has already exited. * * `subprocess.send()` will return `false` if the channel has closed or when the @@ -400,8 +401,8 @@ declare module "child_process" { * Once the server is now shared between the parent and child, some connections * can be handled by the parent and some by the child. * - * While the example above uses a server created using the `node:net` module,`node:dgram` module servers use exactly the same workflow with the exceptions of - * listening on a `'message'` event instead of `'connection'` and using`server.bind()` instead of `server.listen()`. This is, however, only + * While the example above uses a server created using the `node:net` module, `node:dgram` module servers use exactly the same workflow with the exceptions of + * listening on a `'message'` event instead of `'connection'` and using `server.bind()` instead of `server.listen()`. This is, however, only * supported on Unix platforms. * * #### Example: sending a socket object @@ -454,6 +455,7 @@ declare module "child_process" { * as the connection may have been closed during the time it takes to send the * connection to the child. * @since v0.5.9 + * @param sendHandle `undefined`, or a [`net.Socket`](https://nodejs.org/docs/latest-v20.x/api/net.html#class-netsocket), [`net.Server`](https://nodejs.org/docs/latest-v20.x/api/net.html#class-netserver), or [`dgram.Socket`](https://nodejs.org/docs/latest-v20.x/api/dgram.html#class-dgramsocket) object. * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties: */ send(message: Serializable, callback?: (error: Error | null) => void): boolean; @@ -482,7 +484,7 @@ declare module "child_process" { disconnect(): void; /** * By default, the parent will wait for the detached child to exit. To prevent the - * parent from waiting for a given `subprocess` to exit, use the`subprocess.unref()` method. Doing so will cause the parent's event loop to not + * parent from waiting for a given `subprocess` to exit, use the `subprocess.unref()` method. Doing so will cause the parent's event loop to not * include the child in its reference count, allowing the parent to exit * independently of the child, unless there is an established IPC channel between * the child and the parent. @@ -678,7 +680,7 @@ declare module "child_process" { stdio: [Stdin, Stdout, Stderr]; } /** - * The `child_process.spawn()` method spawns a new process using the given`command`, with command-line arguments in `args`. If omitted, `args` defaults + * The `child_process.spawn()` method spawns a new process using the given `command`, with command-line arguments in `args`. If omitted, `args` defaults * to an empty array. * * **If the `shell` option is enabled, do not pass unsanitized user input to this** @@ -776,10 +778,10 @@ declare module "child_process" { * Certain platforms (macOS, Linux) will use the value of `argv[0]` for the process * title while others (Windows, SunOS) will use `command`. * - * Node.js overwrites `argv[0]` with `process.execPath` on startup, so`process.argv[0]` in a Node.js child process will not match the `argv0`parameter passed to `spawn` from the parent. Retrieve - * it with the`process.argv0` property instead. + * Node.js overwrites `argv[0]` with `process.execPath` on startup, so `process.argv[0]` in a Node.js child process will not match the `argv0` parameter passed to `spawn` from the parent. Retrieve + * it with the `process.argv0` property instead. * - * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except * the error passed to the callback will be an `AbortError`: * * ```js @@ -894,6 +896,8 @@ declare module "child_process" { killed?: boolean | undefined; code?: number | undefined; signal?: NodeJS.Signals | undefined; + stdout?: string; + stderr?: string; } /** * Spawns a shell then executes the `command` within that shell, buffering any @@ -915,9 +919,9 @@ declare module "child_process" { * **Never pass unsanitized user input to this function. Any input containing shell** * **metacharacters may be used to trigger arbitrary command execution.** * - * If a `callback` function is provided, it is called with the arguments`(error, stdout, stderr)`. On success, `error` will be `null`. On error,`error` will be an instance of `Error`. The + * If a `callback` function is provided, it is called with the arguments `(error, stdout, stderr)`. On success, `error` will be `null`. On error, `error` will be an instance of `Error`. The * `error.code` property will be - * the exit code of the process. By convention, any exit code other than `0`indicates an error. `error.signal` will be the signal that terminated the + * the exit code of the process. By convention, any exit code other than `0` indicates an error. `error.signal` will be the signal that terminated the * process. * * The `stdout` and `stderr` arguments passed to the callback will contain the @@ -947,7 +951,7 @@ declare module "child_process" { * the existing process and uses a shell to execute the command. * * If this method is invoked as its `util.promisify()` ed version, it returns - * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned`ChildProcess` instance is attached to the `Promise` as a `child` property. In + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned `ChildProcess` instance is attached to the `Promise` as a `child` property. In * case of an error (including any error resulting in an exit code other than 0), a * rejected promise is returned, with the same `error` object given in the * callback, but with two additional properties `stdout` and `stderr`. @@ -964,7 +968,7 @@ declare module "child_process" { * lsExample(); * ``` * - * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except * the error passed to the callback will be an `AbortError`: * * ```js @@ -1109,7 +1113,7 @@ declare module "child_process" { * encoding, `Buffer` objects will be passed to the callback instead. * * If this method is invoked as its `util.promisify()` ed version, it returns - * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned`ChildProcess` instance is attached to the `Promise` as a `child` property. In + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned `ChildProcess` instance is attached to the `Promise` as a `child` property. In * case of an error (including any error resulting in an exit code other than 0), a * rejected promise is returned, with the same `error` object given in the * callback, but with two additional properties `stdout` and `stderr`. @@ -1128,7 +1132,7 @@ declare module "child_process" { * **function. Any input containing shell metacharacters may be used to trigger** * **arbitrary command execution.** * - * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except * the error passed to the callback will be an `AbortError`: * * ```js @@ -1352,7 +1356,7 @@ declare module "child_process" { * required, spawning a large number of child Node.js processes is not * recommended. * - * By default, `child_process.fork()` will spawn new Node.js instances using the `process.execPath` of the parent process. The `execPath` property in the`options` object allows for an alternative + * By default, `child_process.fork()` will spawn new Node.js instances using the `process.execPath` of the parent process. The `execPath` property in the `options` object allows for an alternative * execution path to be used. * * Node.js processes launched with a custom `execPath` will communicate with the @@ -1362,9 +1366,9 @@ declare module "child_process" { * Unlike the [`fork(2)`](http://man7.org/linux/man-pages/man2/fork.2.html) POSIX system call, `child_process.fork()` does not clone the * current process. * - * The `shell` option available in {@link spawn} is not supported by`child_process.fork()` and will be ignored if set. + * The `shell` option available in {@link spawn} is not supported by `child_process.fork()` and will be ignored if set. * - * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except * the error passed to the callback will be an `AbortError`: * * ```js @@ -1387,8 +1391,8 @@ declare module "child_process" { * @param modulePath The module to run in the child. * @param args List of string arguments. */ - function fork(modulePath: string, options?: ForkOptions): ChildProcess; - function fork(modulePath: string, args?: readonly string[], options?: ForkOptions): ChildProcess; + function fork(modulePath: string | URL, options?: ForkOptions): ChildProcess; + function fork(modulePath: string | URL, args?: readonly string[], options?: ForkOptions): ChildProcess; interface SpawnSyncOptions extends CommonSpawnOptions { input?: string | NodeJS.ArrayBufferView | undefined; maxBuffer?: number | undefined; @@ -1473,7 +1477,7 @@ declare module "child_process" { * The `child_process.execSync()` method is generally identical to {@link exec} with the exception that the method will not return * until the child process has fully closed. When a timeout has been encountered * and `killSignal` is sent, the method won't return until the process has - * completely exited. If the child process intercepts and handles the `SIGTERM`signal and doesn't exit, the parent process will wait until the child process + * completely exited. If the child process intercepts and handles the `SIGTERM` signal and doesn't exit, the parent process will wait until the child process * has exited. * * If the process times out or has a non-zero exit code, this method will throw. diff --git a/node_modules/@types/node/cluster.d.ts b/node_modules/@types/node/cluster.d.ts index 39cd56ad3c6e2fa946dc94c84e581e385eab2627..771192783944aefa8242a32ab0fcc52a4d453e36 100644 --- a/node_modules/@types/node/cluster.d.ts +++ b/node_modules/@types/node/cluster.d.ts @@ -1,8 +1,8 @@ /** * Clusters of Node.js processes can be used to run multiple instances of Node.js - * that can distribute workloads among their application threads. When process - * isolation is not needed, use the `worker_threads` module instead, which - * allows running multiple application threads within a single Node.js instance. + * that can distribute workloads among their application threads. When process isolation + * is not needed, use the [`worker_threads`](https://nodejs.org/docs/latest-v20.x/api/worker_threads.html) + * module instead, which allows running multiple application threads within a single Node.js instance. * * The cluster module allows easy creation of child processes that all share * server ports. @@ -50,7 +50,7 @@ * ``` * * On Windows, it is not yet possible to set up a named pipe server in a worker. - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/cluster.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/cluster.js) */ declare module "cluster" { import * as child from "node:child_process"; @@ -58,22 +58,74 @@ declare module "cluster" { import * as net from "node:net"; type SerializationType = "json" | "advanced"; export interface ClusterSettings { - execArgv?: string[] | undefined; // default: process.execArgv + /** + * List of string arguments passed to the Node.js executable. + * @default process.execArgv + */ + execArgv?: string[] | undefined; + /** + * File path to worker file. + * @default process.argv[1] + */ exec?: string | undefined; + /** + * String arguments passed to worker. + * @default process.argv.slice(2) + */ args?: string[] | undefined; + /** + * Whether or not to send output to parent's stdio. + * @default false + */ silent?: boolean | undefined; + /** + * Configures the stdio of forked processes. Because the cluster module relies on IPC to function, this configuration must + * contain an `'ipc'` entry. When this option is provided, it overrides `silent`. See [`child_prcess.spawn()`](https://nodejs.org/docs/latest-v20.x/api/child_process.html#child_processspawncommand-args-options)'s + * [`stdio`](https://nodejs.org/docs/latest-v20.x/api/child_process.html#optionsstdio). + */ stdio?: any[] | undefined; + /** + * Sets the user identity of the process. (See [`setuid(2)`](https://man7.org/linux/man-pages/man2/setuid.2.html).) + */ uid?: number | undefined; + /** + * Sets the group identity of the process. (See [`setgid(2)`](https://man7.org/linux/man-pages/man2/setgid.2.html).) + */ gid?: number | undefined; + /** + * Sets inspector port of worker. This can be a number, or a function that takes no arguments and returns a number. + * By default each worker gets its own port, incremented from the primary's `process.debugPort`. + */ inspectPort?: number | (() => number) | undefined; + /** + * Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. + * See [Advanced serialization for `child_process`](https://nodejs.org/docs/latest-v20.x/api/child_process.html#advanced-serialization) for more details. + * @default false + */ serialization?: SerializationType | undefined; + /** + * Current working directory of the worker process. + * @default undefined (inherits from parent process) + */ cwd?: string | undefined; + /** + * Hide the forked processes console window that would normally be created on Windows systems. + * @default false + */ windowsHide?: boolean | undefined; } export interface Address { address: string; port: number; - addressType: number | "udp4" | "udp6"; // 4, 6, -1, "udp4", "udp6" + /** + * The `addressType` is one of: + * + * * `4` (TCPv4) + * * `6` (TCPv6) + * * `-1` (Unix domain socket) + * * `'udp4'` or `'udp6'` (UDPv4 or UDPv6) + */ + addressType: 4 | 6 | -1 | "udp4" | "udp6"; } /** * A `Worker` object contains all public information and method about a worker. @@ -83,17 +135,17 @@ declare module "cluster" { */ export class Worker extends EventEmitter { /** - * Each new worker is given its own unique id, this id is stored in the`id`. + * Each new worker is given its own unique id, this id is stored in the `id`. * - * While a worker is alive, this is the key that indexes it in`cluster.workers`. + * While a worker is alive, this is the key that indexes it in `cluster.workers`. * @since v0.8.0 */ id: number; /** - * All workers are created using `child_process.fork()`, the returned object - * from this function is stored as `.process`. In a worker, the global `process`is stored. + * All workers are created using [`child_process.fork()`](https://nodejs.org/docs/latest-v20.x/api/child_process.html#child_processforkmodulepath-args-options), the returned object + * from this function is stored as `.process`. In a worker, the global `process` is stored. * - * See: `Child Process module`. + * See: [Child Process module](https://nodejs.org/docs/latest-v20.x/api/child_process.html#child_processforkmodulepath-args-options). * * Workers will call `process.exit(0)` if the `'disconnect'` event occurs * on `process` and `.exitedAfterDisconnect` is not `true`. This protects against @@ -104,9 +156,9 @@ declare module "cluster" { /** * Send a message to a worker or primary, optionally with a handle. * - * In the primary, this sends a message to a specific worker. It is identical to `ChildProcess.send()`. + * In the primary, this sends a message to a specific worker. It is identical to [`ChildProcess.send()`](https://nodejs.org/docs/latest-v20.x/api/child_process.html#subprocesssendmessage-sendhandle-options-callback). * - * In a worker, this sends a message to the primary. It is identical to`process.send()`. + * In a worker, this sends a message to the primary. It is identical to `process.send()`. * * This example will echo back all messages from the primary: * @@ -122,7 +174,7 @@ declare module "cluster" { * } * ``` * @since v0.7.0 - * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties: + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. */ send(message: child.Serializable, callback?: (error: Error | null) => void): boolean; send( @@ -138,7 +190,7 @@ declare module "cluster" { ): boolean; /** * This function will kill the worker. In the primary worker, it does this by - * disconnecting the `worker.process`, and once disconnected, killing with`signal`. In the worker, it does it by killing the process with `signal`. + * disconnecting the `worker.process`, and once disconnected, killing with `signal`. In the worker, it does it by killing the process with `signal`. * * The `kill()` function kills the worker process without waiting for a graceful * disconnect, it has the same behavior as `worker.process.kill()`. @@ -146,7 +198,7 @@ declare module "cluster" { * This method is aliased as `worker.destroy()` for backwards compatibility. * * In a worker, `process.kill()` exists, but it is not this function; - * it is `kill()`. + * it is [`kill()`](https://nodejs.org/docs/latest-v20.x/api/process.html#processkillpid-signal). * @since v0.9.12 * @param [signal='SIGTERM'] Name of the kill signal to send to the worker process. */ @@ -156,7 +208,7 @@ declare module "cluster" { * In a worker, this function will close all servers, wait for the `'close'` event * on those servers, and then disconnect the IPC channel. * - * In the primary, an internal message is sent to the worker causing it to call`.disconnect()` on itself. + * In the primary, an internal message is sent to the worker causing it to call `.disconnect()` on itself. * * Causes `.exitedAfterDisconnect` to be set. * @@ -336,20 +388,114 @@ declare module "cluster" { } export interface Cluster extends EventEmitter { disconnect(callback?: () => void): void; + /** + * Spawn a new worker process. + * + * This can only be called from the primary process. + * @param env Key/value pairs to add to worker process environment. + * @since v0.6.0 + */ fork(env?: any): Worker; /** @deprecated since v16.0.0 - use isPrimary. */ readonly isMaster: boolean; + /** + * True if the process is a primary. This is determined by the `process.env.NODE_UNIQUE_ID`. If `process.env.NODE_UNIQUE_ID` + * is undefined, then `isPrimary` is `true`. + * @since v16.0.0 + */ readonly isPrimary: boolean; + /** + * True if the process is not a primary (it is the negation of `cluster.isPrimary`). + * @since v0.6.0 + */ readonly isWorker: boolean; + /** + * The scheduling policy, either `cluster.SCHED_RR` for round-robin or `cluster.SCHED_NONE` to leave it to the operating system. This is a + * global setting and effectively frozen once either the first worker is spawned, or [`.setupPrimary()`](https://nodejs.org/docs/latest-v20.x/api/cluster.html#clustersetupprimarysettings) + * is called, whichever comes first. + * + * `SCHED_RR` is the default on all operating systems except Windows. Windows will change to `SCHED_RR` once libuv is able to effectively distribute + * IOCP handles without incurring a large performance hit. + * + * `cluster.schedulingPolicy` can also be set through the `NODE_CLUSTER_SCHED_POLICY` environment variable. Valid values are `'rr'` and `'none'`. + * @since v0.11.2 + */ schedulingPolicy: number; + /** + * After calling [`.setupPrimary()`](https://nodejs.org/docs/latest-v20.x/api/cluster.html#clustersetupprimarysettings) + * (or [`.fork()`](https://nodejs.org/docs/latest-v20.x/api/cluster.html#clusterforkenv)) this settings object will contain + * the settings, including the default values. + * + * This object is not intended to be changed or set manually. + * @since v0.7.1 + */ readonly settings: ClusterSettings; - /** @deprecated since v16.0.0 - use setupPrimary. */ + /** @deprecated since v16.0.0 - use [`.setupPrimary()`](https://nodejs.org/docs/latest-v20.x/api/cluster.html#clustersetupprimarysettings) instead. */ setupMaster(settings?: ClusterSettings): void; /** - * `setupPrimary` is used to change the default 'fork' behavior. Once called, the settings will be present in cluster.settings. + * `setupPrimary` is used to change the default 'fork' behavior. Once called, the settings will be present in `cluster.settings`. + * + * Any settings changes only affect future calls to [`.fork()`](https://nodejs.org/docs/latest-v20.x/api/cluster.html#clusterforkenv) + * and have no effect on workers that are already running. + * + * The only attribute of a worker that cannot be set via `.setupPrimary()` is the `env` passed to + * [`.fork()`](https://nodejs.org/docs/latest-v20.x/api/cluster.html#clusterforkenv). + * + * The defaults above apply to the first call only; the defaults for later calls are the current values at the time of + * `cluster.setupPrimary()` is called. + * + * ```js + * import cluster from 'node:cluster'; + * + * cluster.setupPrimary({ + * exec: 'worker.js', + * args: ['--use', 'https'], + * silent: true, + * }); + * cluster.fork(); // https worker + * cluster.setupPrimary({ + * exec: 'worker.js', + * args: ['--use', 'http'], + * }); + * cluster.fork(); // http worker + * ``` + * + * This can only be called from the primary process. + * @since v16.0.0 */ setupPrimary(settings?: ClusterSettings): void; + /** + * A reference to the current worker object. Not available in the primary process. + * + * ```js + * import cluster from 'node:cluster'; + * + * if (cluster.isPrimary) { + * console.log('I am primary'); + * cluster.fork(); + * cluster.fork(); + * } else if (cluster.isWorker) { + * console.log(`I am worker #${cluster.worker.id}`); + * } + * ``` + * @since v0.7.0 + */ readonly worker?: Worker | undefined; + /** + * A hash that stores the active worker objects, keyed by `id` field. This makes it easy to loop through all the workers. It is only available in the primary process. + * + * A worker is removed from `cluster.workers` after the worker has disconnected _and_ exited. The order between these two events cannot be determined in advance. However, it + * is guaranteed that the removal from the `cluster.workers` list happens before the last `'disconnect'` or `'exit'` event is emitted. + * + * ```js + * import cluster from 'node:cluster'; + * + * for (const worker of Object.values(cluster.workers)) { + * worker.send('big announcement to all workers'); + * } + * ``` + * @since v0.7.0 + */ readonly workers?: NodeJS.Dict | undefined; readonly SCHED_NONE: number; readonly SCHED_RR: number; diff --git a/node_modules/@types/node/console.d.ts b/node_modules/@types/node/console.d.ts index bcc345042058790cbb22a77c89c62cab472ab86d..3d1a6c2e75da3e21a01b944585450284cf8cb93e 100644 --- a/node_modules/@types/node/console.d.ts +++ b/node_modules/@types/node/console.d.ts @@ -4,12 +4,13 @@ * * The module exports two specific components: * - * * A `Console` class with methods such as `console.log()`, `console.error()`, and`console.warn()` that can be used to write to any Node.js stream. - * * A global `console` instance configured to write to `process.stdout` and `process.stderr`. The global `console` can be used without calling`require('node:console')`. + * * A `Console` class with methods such as `console.log()`, `console.error()`, and `console.warn()` that can be used to write to any Node.js stream. + * * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and + * [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without calling `require('node:console')`. * * _**Warning**_: The global console object's methods are neither consistently * synchronous like the browser APIs they resemble, nor are they consistently - * asynchronous like all other Node.js streams. See the `note on process I/O` for + * asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for * more information. * * Example using the global `console`: @@ -53,7 +54,7 @@ * myConsole.warn(`Danger ${name}! Danger!`); * // Prints: Danger Will Robinson! Danger!, to err * ``` - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/console.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/console.js) */ declare module "console" { import console = require("node:console"); @@ -68,7 +69,8 @@ declare module "node:console" { /** * `console.assert()` writes a message if `value` is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) or omitted. It only * writes a message and does not otherwise affect execution. The output always - * starts with `"Assertion failed"`. If provided, `message` is formatted using `util.format()`. + * starts with `"Assertion failed"`. If provided, `message` is formatted using + * [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args). * * If `value` is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), nothing happens. * @@ -91,7 +93,7 @@ declare module "node:console" { * TTY. When `stdout` is not a TTY, this method does nothing. * * The specific operation of `console.clear()` can vary across operating systems - * and terminal types. For most Linux operating systems, `console.clear()`operates similarly to the `clear` shell command. On Windows, `console.clear()`will clear only the output in the + * and terminal types. For most Linux operating systems, `console.clear()` operates similarly to the `clear` shell command. On Windows, `console.clear()` will clear only the output in the * current terminal viewport for the Node.js * binary. * @since v8.3.0 @@ -150,7 +152,7 @@ declare module "node:console" { */ debug(message?: any, ...optionalParams: any[]): void; /** - * Uses `util.inspect()` on `obj` and prints the resulting string to `stdout`. + * Uses [`util.inspect()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilinspectobject-options) on `obj` and prints the resulting string to `stdout`. * This function bypasses any custom `inspect()` function defined on `obj`. * @since v0.1.101 */ @@ -164,7 +166,8 @@ declare module "node:console" { /** * Prints to `stderr` with newline. Multiple arguments can be passed, with the * first used as the primary message and all additional used as substitution - * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to `util.format()`). + * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) + * (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args)). * * ```js * const code = 5; @@ -174,13 +177,15 @@ declare module "node:console" { * // Prints: error 5, to stderr * ``` * - * If formatting elements (e.g. `%d`) are not found in the first string then `util.inspect()` is called on each argument and the resulting string - * values are concatenated. See `util.format()` for more information. + * If formatting elements (e.g. `%d`) are not found in the first string then + * [`util.inspect()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilinspectobject-options) is called on each argument and the + * resulting string values are concatenated. See [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args) + * for more information. * @since v0.1.100 */ error(message?: any, ...optionalParams: any[]): void; /** - * Increases indentation of subsequent lines by spaces for `groupIndentation`length. + * Increases indentation of subsequent lines by spaces for `groupIndentation` length. * * If one or more `label`s are provided, those are printed first without the * additional indentation. @@ -193,7 +198,7 @@ declare module "node:console" { */ groupCollapsed(...label: any[]): void; /** - * Decreases indentation of subsequent lines by spaces for `groupIndentation`length. + * Decreases indentation of subsequent lines by spaces for `groupIndentation` length. * @since v8.5.0 */ groupEnd(): void; @@ -205,7 +210,8 @@ declare module "node:console" { /** * Prints to `stdout` with newline. Multiple arguments can be passed, with the * first used as the primary message and all additional used as substitution - * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to `util.format()`). + * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) + * (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args)). * * ```js * const count = 5; @@ -215,12 +221,12 @@ declare module "node:console" { * // Prints: count: 5, to stdout * ``` * - * See `util.format()` for more information. + * See [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args) for more information. * @since v0.1.100 */ log(message?: any, ...optionalParams: any[]): void; /** - * Try to construct a table with the columns of the properties of `tabularData`(or use `properties`) and rows of `tabularData` and log it. Falls back to just + * Try to construct a table with the columns of the properties of `tabularData` (or use `properties`) and rows of `tabularData` and log it. Falls back to just * logging the argument if it can't be parsed as tabular. * * ```js @@ -291,7 +297,8 @@ declare module "node:console" { */ timeLog(label?: string, ...data: any[]): void; /** - * Prints to `stderr` the string `'Trace: '`, followed by the `util.format()` formatted message and stack trace to the current position in the code. + * Prints to `stderr` the string `'Trace: '`, followed by the [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args) + * formatted message and stack trace to the current position in the code. * * ```js * console.trace('Show me'); @@ -318,18 +325,32 @@ declare module "node:console" { warn(message?: any, ...optionalParams: any[]): void; // --- Inspector mode only --- /** - * This method does not display anything unless used in the inspector. - * Starts a JavaScript CPU profile with an optional label. + * This method does not display anything unless used in the inspector. The `console.profile()` + * method starts a JavaScript CPU profile with an optional label until {@link profileEnd} + * is called. The profile is then added to the Profile panel of the inspector. + * + * ```js + * console.profile('MyLabel'); + * // Some code + * console.profileEnd('MyLabel'); + * // Adds the profile 'MyLabel' to the Profiles panel of the inspector. + * ``` + * @since v8.0.0 */ profile(label?: string): void; /** - * This method does not display anything unless used in the inspector. - * Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector. + * This method does not display anything unless used in the inspector. Stops the current + * JavaScript CPU profiling session if one has been started and prints the report to the + * Profiles panel of the inspector. See {@link profile} for an example. + * + * If this method is called without a label, the most recently started profile is stopped. + * @since v8.0.0 */ profileEnd(label?: string): void; /** - * This method does not display anything unless used in the inspector. - * Adds an event with the label `label` to the Timeline panel of the inspector. + * This method does not display anything unless used in the inspector. The `console.timeStamp()` + * method adds an event with the label `'label'` to the Timeline panel of the inspector. + * @since v8.0.0 */ timeStamp(label?: string): void; } @@ -339,12 +360,13 @@ declare module "node:console" { * * The module exports two specific components: * - * * A `Console` class with methods such as `console.log()`, `console.error()` and`console.warn()` that can be used to write to any Node.js stream. - * * A global `console` instance configured to write to `process.stdout` and `process.stderr`. The global `console` can be used without calling`require('console')`. + * * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. + * * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and + * [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without calling `require('console')`. * * _**Warning**_: The global console object's methods are neither consistently * synchronous like the browser APIs they resemble, nor are they consistently - * asynchronous like all other Node.js streams. See the `note on process I/O` for + * asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for * more information. * * Example using the global `console`: @@ -388,17 +410,32 @@ declare module "node:console" { * myConsole.warn(`Danger ${name}! Danger!`); * // Prints: Danger Will Robinson! Danger!, to err * ``` - * @see [source](https://github.com/nodejs/node/blob/v16.4.2/lib/console.js) + * @see [source](https://github.com/nodejs/node/blob/v20.11.1/lib/console.js) */ namespace console { interface ConsoleConstructorOptions { stdout: NodeJS.WritableStream; stderr?: NodeJS.WritableStream | undefined; + /** + * Ignore errors when writing to the underlying streams. + * @default true + */ ignoreErrors?: boolean | undefined; + /** + * Set color support for this `Console` instance. Setting to true enables coloring while inspecting + * values. Setting to `false` disables coloring while inspecting values. Setting to `'auto'` makes color + * support depend on the value of the `isTTY` property and the value returned by `getColorDepth()` on the + * respective stream. This option can not be used, if `inspectOptions.colors` is set as well. + * @default auto + */ colorMode?: boolean | "auto" | undefined; + /** + * Specifies options that are passed along to + * [`util.inspect()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilinspectobject-options). + */ inspectOptions?: InspectOptions | undefined; /** - * Set group indentation + * Set group indentation. * @default 2 */ groupIndentation?: number | undefined; diff --git a/node_modules/@types/node/crypto.d.ts b/node_modules/@types/node/crypto.d.ts index 7509b762fd6e5e342fc2bea04a4133365c8d1ffe..5173dbf918e91e3119ad9b2b00e0c8d757e494d1 100644 --- a/node_modules/@types/node/crypto.d.ts +++ b/node_modules/@types/node/crypto.d.ts @@ -14,7 +14,7 @@ * // Prints: * // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e * ``` - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/crypto.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/crypto.js) */ declare module "crypto" { import * as stream from "node:stream"; @@ -27,7 +27,7 @@ declare module "crypto" { * should not use this element anymore. * * The `node:crypto` module provides the `Certificate` class for working with SPKAC - * data. The most common usage is handling output generated by the HTML5`` element. Node.js uses [OpenSSL's SPKAC + * data. The most common usage is handling output generated by the HTML5 `` element. Node.js uses [OpenSSL's SPKAC * implementation](https://www.openssl.org/docs/man3.0/man1/openssl-spkac.html) internally. * @since v0.11.8 */ @@ -106,7 +106,7 @@ declare module "crypto" { const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; /** Attempts to use the server's preferences instead of the client's when selecting a cipher. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ const SSL_OP_CIPHER_SERVER_PREFERENCE: number; - /** Instructs OpenSSL to use Cisco's "speshul" version of DTLS_BAD_VER. */ + /** Instructs OpenSSL to use Cisco's version identifier of DTLS_BAD_VER. */ const SSL_OP_CISCO_ANYCONNECT: number; /** Instructs OpenSSL to turn on cookie exchange. */ const SSL_OP_COOKIE_EXCHANGE: number; @@ -470,6 +470,7 @@ declare module "crypto" { * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e * ``` * @since v0.1.94 + * @deprecated Since v20.13.0 Calling `Hmac` class directly with `Hmac()` or `new Hmac()` is deprecated due to being internals, not intended for public use. Please use the {@link createHmac} method to create Hmac instances. */ class Hmac extends stream.Transform { private constructor(); @@ -688,7 +689,7 @@ declare module "crypto" { authTagLength: number; } /** - * Creates and returns a `Cipher` object that uses the given `algorithm` and`password`. + * Creates and returns a `Cipher` object that uses the given `algorithm` and `password`. * * The `options` argument controls stream behavior and is optional except when a * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the @@ -906,8 +907,8 @@ declare module "crypto" { private constructor(); /** * Updates the cipher with `data`. If the `inputEncoding` argument is given, - * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`, `TypedArray`, or`DataView`. If `data` is a `Buffer`, - * `TypedArray`, or `DataView`, then`inputEncoding` is ignored. + * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`, `TypedArray`, or `DataView`. If `data` is a `Buffer`, + * `TypedArray`, or `DataView`, then `inputEncoding` is ignored. * * The `outputEncoding` specifies the output format of the enciphered * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned. @@ -977,10 +978,10 @@ declare module "crypto" { getAuthTag(): Buffer; } /** - * Creates and returns a `Decipher` object that uses the given `algorithm` and`password` (key). + * Creates and returns a `Decipher` object that uses the given `algorithm` and `password` (key). * * The `options` argument controls stream behavior and is optional except when a - * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the `authTagLength` option is required and specifies the length of the * authentication tag in bytes, see `CCM mode`. * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. * @@ -1008,11 +1009,11 @@ declare module "crypto" { /** @deprecated since v10.0.0 use `createDecipheriv()` */ function createDecipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Decipher; /** - * Creates and returns a `Decipher` object that uses the given `algorithm`, `key`and initialization vector (`iv`). + * Creates and returns a `Decipher` object that uses the given `algorithm`, `key` and initialization vector (`iv`). * * The `options` argument controls stream behavior and is optional except when a - * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the - * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to restrict accepted authentication tags + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the `authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength` option is not required but can be used to restrict accepted authentication tags * to those with the specified length. * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. * @@ -1172,11 +1173,11 @@ declare module "crypto" { private constructor(); /** * Updates the decipher with `data`. If the `inputEncoding` argument is given, - * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`. If `data` is a `Buffer` then `inputEncoding` is + * the `data` argument is a string using the specified encoding. If the `inputEncoding` argument is not given, `data` must be a `Buffer`. If `data` is a `Buffer` then `inputEncoding` is * ignored. * * The `outputEncoding` specifies the output format of the enciphered - * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned. + * data. If the `outputEncoding` is specified, a string using the specified encoding is returned. If no `outputEncoding` is provided, a `Buffer` is returned. * * The `decipher.update()` method can be called multiple times with new data until `decipher.final()` is called. Calling `decipher.update()` after `decipher.final()` will result in an error * being thrown. @@ -1199,7 +1200,7 @@ declare module "crypto" { final(): Buffer; final(outputEncoding: BufferEncoding): string; /** - * When data has been encrypted without standard block padding, calling`decipher.setAutoPadding(false)` will disable automatic padding to prevent `decipher.final()` from checking for and + * When data has been encrypted without standard block padding, calling `decipher.setAutoPadding(false)` will disable automatic padding to prevent `decipher.final()` from checking for and * removing padding. * * Turning auto padding off will only work if the input data's length is a @@ -1253,7 +1254,7 @@ declare module "crypto" { encoding?: string | undefined; } /** - * Asynchronously generates a new random secret key of the given `length`. The`type` will determine which validations will be performed on the `length`. + * Asynchronously generates a new random secret key of the given `length`. The `type` will determine which validations will be performed on the `length`. * * ```js * const { @@ -1279,7 +1280,7 @@ declare module "crypto" { callback: (err: Error | null, key: KeyObject) => void, ): void; /** - * Synchronously generates a new random secret key of the given `length`. The`type` will determine which validations will be performed on the `length`. + * Synchronously generates a new random secret key of the given `length`. The `type` will determine which validations will be performed on the `length`. * * ```js * const { @@ -1307,7 +1308,7 @@ declare module "crypto" { } /** * Creates and returns a new key object containing a private key. If `key` is a - * string or `Buffer`, `format` is assumed to be `'pem'`; otherwise, `key`must be an object with the properties described above. + * string or `Buffer`, `format` is assumed to be `'pem'`; otherwise, `key` must be an object with the properties described above. * * If the private key is encrypted, a `passphrase` must be specified. The length * of the passphrase is limited to 1024 bytes. @@ -1316,7 +1317,7 @@ declare module "crypto" { function createPrivateKey(key: PrivateKeyInput | string | Buffer | JsonWebKeyInput): KeyObject; /** * Creates and returns a new key object containing a public key. If `key` is a - * string or `Buffer`, `format` is assumed to be `'pem'`; if `key` is a `KeyObject`with type `'private'`, the public key is derived from the given private key; + * string or `Buffer`, `format` is assumed to be `'pem'`; if `key` is a `KeyObject` with type `'private'`, the public key is derived from the given private key; * otherwise, `key` must be an object with the properties described above. * * If the format is `'pem'`, the `'key'` may also be an X.509 certificate. @@ -1324,7 +1325,7 @@ declare module "crypto" { * Because public keys can be derived from private keys, a private key may be * passed instead of a public key. In that case, this function behaves as if {@link createPrivateKey} had been called, except that the type of the * returned `KeyObject` will be `'public'` and that the private key cannot be - * extracted from the returned `KeyObject`. Similarly, if a `KeyObject` with type`'private'` is given, a new `KeyObject` with type `'public'` will be returned + * extracted from the returned `KeyObject`. Similarly, if a `KeyObject` with type `'private'` is given, a new `KeyObject` with type `'public'` will be returned * and it will be impossible to extract the private key from the returned object. * @since v11.6.0 */ @@ -1449,7 +1450,7 @@ declare module "crypto" { /** * Calculates the signature on all the data passed through using either `sign.update()` or `sign.write()`. * - * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an + * If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to {@link createPrivateKey}. If it is an * object, the following additional properties can be passed: * * If `outputEncoding` is provided a string is returned; otherwise a `Buffer` is returned. @@ -1467,7 +1468,7 @@ declare module "crypto" { /** * Creates and returns a `Verify` object that uses the given algorithm. * Use {@link getHashes} to obtain an array of names of the available - * signing algorithms. Optional `options` argument controls the`stream.Writable` behavior. + * signing algorithms. Optional `options` argument controls the `stream.Writable` behavior. * * In some cases, a `Verify` instance can be created using the name of a signature * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use @@ -1487,7 +1488,7 @@ declare module "crypto" { * * Using the `verify.update()` and `verify.verify()` methods to verify * the signature. * - * The {@link createVerify} method is used to create `Verify` instances.`Verify` objects are not to be created directly using the `new` keyword. + * The {@link createVerify} method is used to create `Verify` instances. `Verify` objects are not to be created directly using the `new` keyword. * * See `Sign` for examples. * @since v0.1.92 @@ -1498,7 +1499,7 @@ declare module "crypto" { * Updates the `Verify` content with the given `data`, the encoding of which * is given in `inputEncoding`. * If `inputEncoding` is not provided, and the `data` is a string, an - * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or `DataView`, then `inputEncoding` is ignored. * * This can be called many times with new data as it is streamed. * @since v0.1.92 @@ -1509,13 +1510,13 @@ declare module "crypto" { /** * Verifies the provided data using the given `object` and `signature`. * - * If `object` is not a `KeyObject`, this function behaves as if`object` had been passed to {@link createPublicKey}. If it is an + * If `object` is not a `KeyObject`, this function behaves as if `object` had been passed to {@link createPublicKey}. If it is an * object, the following additional properties can be passed: * * The `signature` argument is the previously calculated signature for the data, in * the `signatureEncoding`. * If a `signatureEncoding` is specified, the `signature` is expected to be a - * string; otherwise `signature` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * string; otherwise `signature` is expected to be a `Buffer`, `TypedArray`, or `DataView`. * * The `verify` object can not be used again after `verify.verify()` has been * called. Multiple calls to `verify.verify()` will result in an error being @@ -1539,7 +1540,7 @@ declare module "crypto" { * Creates a `DiffieHellman` key exchange object using the supplied `prime` and an * optional specific `generator`. * - * The `generator` argument can be a number, string, or `Buffer`. If`generator` is not specified, the value `2` is used. + * The `generator` argument can be a number, string, or `Buffer`. If `generator` is not specified, the value `2` is used. * * If `primeEncoding` is specified, `prime` is expected to be a string; otherwise * a `Buffer`, `TypedArray`, or `DataView` is expected. @@ -1625,7 +1626,7 @@ declare module "crypto" { * key is interpreted using the specified `inputEncoding`, and secret is * encoded using specified `outputEncoding`. * If the `inputEncoding` is not - * provided, `otherPublicKey` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or `DataView`. * * If `outputEncoding` is given a string is returned; otherwise, a `Buffer` is returned. * @since v0.5.0 @@ -1681,7 +1682,7 @@ declare module "crypto" { getPrivateKey(): Buffer; getPrivateKey(encoding: BinaryToTextEncoding): string; /** - * Sets the Diffie-Hellman public key. If the `encoding` argument is provided,`publicKey` is expected + * Sets the Diffie-Hellman public key. If the `encoding` argument is provided, `publicKey` is expected * to be a string. If no `encoding` is provided, `publicKey` is expected * to be a `Buffer`, `TypedArray`, or `DataView`. * @since v0.5.0 @@ -1784,10 +1785,10 @@ declare module "crypto" { /** * Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2) * implementation. A selected HMAC digest algorithm specified by `digest` is - * applied to derive a key of the requested byte length (`keylen`) from the`password`, `salt` and `iterations`. + * applied to derive a key of the requested byte length (`keylen`) from the `password`, `salt` and `iterations`. * - * The supplied `callback` function is called with two arguments: `err` and`derivedKey`. If an error occurs while deriving the key, `err` will be set; - * otherwise `err` will be `null`. By default, the successfully generated`derivedKey` will be passed to the callback as a `Buffer`. An error will be + * The supplied `callback` function is called with two arguments: `err` and `derivedKey`. If an error occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. By default, the successfully generated `derivedKey` will be passed to the callback as a `Buffer`. An error will be * thrown if any of the input arguments specify invalid values or types. * * The `iterations` argument must be a number set as high as possible. The @@ -1827,7 +1828,7 @@ declare module "crypto" { /** * Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2) * implementation. A selected HMAC digest algorithm specified by `digest` is - * applied to derive a key of the requested byte length (`keylen`) from the`password`, `salt` and `iterations`. + * applied to derive a key of the requested byte length (`keylen`) from the `password`, `salt` and `iterations`. * * If an error occurs an `Error` will be thrown, otherwise the derived key will be * returned as a `Buffer`. @@ -1866,7 +1867,7 @@ declare module "crypto" { * * If a `callback` function is provided, the bytes are generated asynchronously * and the `callback` function is invoked with two arguments: `err` and `buf`. - * If an error occurs, `err` will be an `Error` object; otherwise it is `null`. The`buf` argument is a `Buffer` containing the generated bytes. + * If an error occurs, `err` will be an `Error` object; otherwise it is `null`. The `buf` argument is a `Buffer` containing the generated bytes. * * ```js * // Asynchronous @@ -1920,7 +1921,7 @@ declare module "crypto" { * Return a random integer `n` such that `min <= n < max`. This * implementation avoids [modulo bias](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modulo_bias). * - * The range (`max - min`) must be less than 248. `min` and `max` must + * The range (`max - min`) must be less than 2**48. `min` and `max` must * be [safe integers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger). * * If the `callback` function is not provided, the random integer is @@ -2037,7 +2038,7 @@ declare module "crypto" { * }); * ``` * - * Any `ArrayBuffer`, `TypedArray`, or `DataView` instance may be passed as`buffer`. + * Any `ArrayBuffer`, `TypedArray`, or `DataView` instance may be passed as `buffer`. * * While this includes instances of `Float32Array` and `Float64Array`, this * function should not be used to generate random floating-point numbers. The @@ -2117,7 +2118,7 @@ declare module "crypto" { * * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. * - * The `callback` function is called with two arguments: `err` and `derivedKey`.`err` is an exception object when key derivation fails, otherwise `err` is`null`. `derivedKey` is passed to the + * The `callback` function is called with two arguments: `err` and `derivedKey`. `err` is an exception object when key derivation fails, otherwise `err` is `null`. `derivedKey` is passed to the * callback as a `Buffer`. * * An exception is thrown when any of the input arguments specify invalid values @@ -2203,8 +2204,8 @@ declare module "crypto" { * Encrypts the content of `buffer` with `key` and returns a new `Buffer` with encrypted content. The returned data can be decrypted using * the corresponding private key, for example using {@link privateDecrypt}. * - * If `key` is not a `KeyObject`, this function behaves as if`key` had been passed to {@link createPublicKey}. If it is an - * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_OAEP_PADDING`. + * If `key` is not a `KeyObject`, this function behaves as if `key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_OAEP_PADDING`. * * Because RSA public keys can be derived from private keys, a private key may * be passed instead of a public key. @@ -2215,8 +2216,8 @@ declare module "crypto" { * Decrypts `buffer` with `key`.`buffer` was previously encrypted using * the corresponding private key, for example using {@link privateEncrypt}. * - * If `key` is not a `KeyObject`, this function behaves as if`key` had been passed to {@link createPublicKey}. If it is an - * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_PADDING`. + * If `key` is not a `KeyObject`, this function behaves as if `key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_PADDING`. * * Because RSA public keys can be derived from private keys, a private key may * be passed instead of a public key. @@ -2227,8 +2228,8 @@ declare module "crypto" { * Decrypts `buffer` with `privateKey`. `buffer` was previously encrypted using * the corresponding public key, for example using {@link publicEncrypt}. * - * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an - * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_OAEP_PADDING`. + * If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_OAEP_PADDING`. * @since v0.11.14 */ function privateDecrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; @@ -2236,8 +2237,8 @@ declare module "crypto" { * Encrypts `buffer` with `privateKey`. The returned data can be decrypted using * the corresponding public key, for example using {@link publicDecrypt}. * - * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an - * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_PADDING`. + * If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_PADDING`. * @since v1.1.0 */ function privateEncrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; @@ -2332,9 +2333,9 @@ declare module "crypto" { * On recent OpenSSL releases, `openssl ecparam -list_curves` will also display * the name and description of each available elliptic curve. * - * If `format` is not specified the point will be returned in `'uncompressed'`format. + * If `format` is not specified the point will be returned in `'uncompressed'` format. * - * If the `inputEncoding` is not provided, `key` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * If the `inputEncoding` is not provided, `key` is expected to be a `Buffer`, `TypedArray`, or `DataView`. * * Example (uncompressing a key): * @@ -2375,7 +2376,7 @@ declare module "crypto" { * the public key in the specified `format` and `encoding`. This key should be * transferred to the other party. * - * The `format` argument specifies point encoding and can be `'compressed'` or`'uncompressed'`. If `format` is not specified, the point will be returned in`'uncompressed'` format. + * The `format` argument specifies point encoding and can be `'compressed'` or `'uncompressed'`. If `format` is not specified, the point will be returned in`'uncompressed'` format. * * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. * @since v0.11.14 @@ -2390,11 +2391,11 @@ declare module "crypto" { * key is interpreted using specified `inputEncoding`, and the returned secret * is encoded using the specified `outputEncoding`. * If the `inputEncoding` is not - * provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or`DataView`. + * provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or `DataView`. * * If `outputEncoding` is given a string will be returned; otherwise a `Buffer` is returned. * - * `ecdh.computeSecret` will throw an`ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY` error when `otherPublicKey`lies outside of the elliptic curve. Since `otherPublicKey` is + * `ecdh.computeSecret` will throw an`ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY` error when `otherPublicKey` lies outside of the elliptic curve. Since `otherPublicKey` is * usually supplied from a remote user over an insecure network, * be sure to handle this exception accordingly. * @since v0.11.14 @@ -2419,7 +2420,7 @@ declare module "crypto" { getPrivateKey(): Buffer; getPrivateKey(encoding: BinaryToTextEncoding): string; /** - * The `format` argument specifies point encoding and can be `'compressed'` or`'uncompressed'`. If `format` is not specified the point will be returned in`'uncompressed'` format. + * The `format` argument specifies point encoding and can be `'compressed'` or `'uncompressed'`. If `format` is not specified the point will be returned in`'uncompressed'` format. * * If `encoding` is specified, a string is returned; otherwise a `Buffer` is * returned. @@ -2433,7 +2434,7 @@ declare module "crypto" { /** * Sets the EC Diffie-Hellman private key. * If `encoding` is provided, `privateKey` is expected - * to be a string; otherwise `privateKey` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * to be a string; otherwise `privateKey` is expected to be a `Buffer`, `TypedArray`, or `DataView`. * * If `privateKey` is not valid for the curve specified when the `ECDH` object was * created, an error is thrown. Upon setting the private key, the associated @@ -2453,7 +2454,7 @@ declare module "crypto" { */ function createECDH(curveName: string): ECDH; /** - * This function compares the underlying bytes that represent the given`ArrayBuffer`, `TypedArray`, or `DataView` instances using a constant-time + * This function compares the underlying bytes that represent the given `ArrayBuffer`, `TypedArray`, or `DataView` instances using a constant-time * algorithm. * * This function does not leak timing information that @@ -2468,8 +2469,8 @@ declare module "crypto" { * entry, such as `Uint16Array`, the result will be computed using the platform * byte order. * - * **When both of the inputs are `Float32Array`s or`Float64Array`s, this function might return unexpected results due to IEEE 754** - * **encoding of floating-point numbers. In particular, neither `x === y` nor`Object.is(x, y)` implies that the byte representations of two floating-point** + * **When both of the inputs are `Float32Array`s or `Float64Array`s, this function might return unexpected results due to IEEE 754** + * **encoding of floating-point numbers. In particular, neither `x === y` nor `Object.is(x, y)` implies that the byte representations of two floating-point** * **numbers `x` and `y` are equal.** * * Use of `crypto.timingSafeEqual` does not guarantee that the _surrounding_ code @@ -2846,7 +2847,7 @@ declare module "crypto" { * behaves as if `keyObject.export()` had been called on its result. Otherwise, * the respective part of the key is returned as a `KeyObject`. * - * It is recommended to encode public keys as `'spki'` and private keys as`'pkcs8'` with encryption for long-term storage: + * It is recommended to encode public keys as `'spki'` and private keys as `'pkcs8'` with encryption for long-term storage: * * ```js * const { @@ -2870,7 +2871,7 @@ declare module "crypto" { * }); * ``` * - * On completion, `callback` will be called with `err` set to `undefined` and`publicKey` / `privateKey` representing the generated key pair. + * On completion, `callback` will be called with `err` set to `undefined` and `publicKey` / `privateKey` representing the generated key pair. * * If this method is invoked as its `util.promisify()` ed version, it returns * a `Promise` for an `Object` with `publicKey` and `privateKey` properties. @@ -3344,7 +3345,7 @@ declare module "crypto" { callback: (error: Error | null, data: Buffer) => void, ): void; /** - * Verifies the given signature for `data` using the given key and algorithm. If`algorithm` is `null` or `undefined`, then the algorithm is dependent upon the + * Verifies the given signature for `data` using the given key and algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is dependent upon the * key type (especially Ed25519 and Ed448). * * If `key` is not a `KeyObject`, this function behaves as if `key` had been @@ -3374,10 +3375,45 @@ declare module "crypto" { ): void; /** * Computes the Diffie-Hellman secret based on a `privateKey` and a `publicKey`. - * Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'`(for Diffie-Hellman), `'ec'` (for ECDH), `'x448'`, or `'x25519'` (for ECDH-ES). + * Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'` (for Diffie-Hellman), `'ec'` (for ECDH), `'x448'`, or `'x25519'` (for ECDH-ES). * @since v13.9.0, v12.17.0 */ function diffieHellman(options: { privateKey: KeyObject; publicKey: KeyObject }): Buffer; + /** + * A utility for creating one-shot hash digests of data. It can be faster than the object-based `crypto.createHash()` when hashing a smaller amount of data + * (<= 5MB) that's readily available. If the data can be big or if it is streamed, it's still recommended to use `crypto.createHash()` instead. The `algorithm` + * is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. On recent releases + * of OpenSSL, `openssl list -digest-algorithms` will display the available digest algorithms. + * + * Example: + * + * ```js + * const crypto = require('node:crypto'); + * const { Buffer } = require('node:buffer'); + * + * // Hashing a string and return the result as a hex-encoded string. + * const string = 'Node.js'; + * // 10b3493287f831e81a438811a1ffba01f8cec4b7 + * console.log(crypto.hash('sha1', string)); + * + * // Encode a base64-encoded string into a Buffer, hash it and return + * // the result as a buffer. + * const base64 = 'Tm9kZS5qcw=='; + * // + * console.log(crypto.hash('sha1', Buffer.from(base64, 'base64'), 'buffer')); + * ``` + * @since v21.7.0, v20.12.0 + * @param data When `data` is a string, it will be encoded as UTF-8 before being hashed. If a different input encoding is desired for a string input, user + * could encode the string into a `TypedArray` using either `TextEncoder` or `Buffer.from()` and passing the encoded `TypedArray` into this API instead. + * @param [outputEncoding='hex'] [Encoding](https://nodejs.org/docs/latest-v20.x/api/buffer.html#buffers-and-character-encodings) used to encode the returned digest. + */ + function hash(algorithm: string, data: BinaryLike, outputEncoding?: BinaryToTextEncoding): string; + function hash(algorithm: string, data: BinaryLike, outputEncoding: "buffer"): Buffer; + function hash( + algorithm: string, + data: BinaryLike, + outputEncoding?: BinaryToTextEncoding | "buffer", + ): string | Buffer; type CipherMode = "cbc" | "ccm" | "cfb" | "ctr" | "ecb" | "gcm" | "ocb" | "ofb" | "stream" | "wrap" | "xts"; interface CipherInfoOptions { /** @@ -3430,9 +3466,9 @@ declare module "crypto" { */ function getCipherInfo(nameOrNid: string | number, options?: CipherInfoOptions): CipherInfo | undefined; /** - * HKDF is a simple key derivation function defined in RFC 5869\. The given `ikm`,`salt` and `info` are used with the `digest` to derive a key of `keylen` bytes. + * HKDF is a simple key derivation function defined in RFC 5869\. The given `ikm`, `salt` and `info` are used with the `digest` to derive a key of `keylen` bytes. * - * The supplied `callback` function is called with two arguments: `err` and`derivedKey`. If an errors occurs while deriving the key, `err` will be set; + * The supplied `callback` function is called with two arguments: `err` and `derivedKey`. If an errors occurs while deriving the key, `err` will be set; * otherwise `err` will be `null`. The successfully generated `derivedKey` will * be passed to the callback as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). An error will be thrown if any * of the input arguments specify invalid values or types. @@ -3466,7 +3502,7 @@ declare module "crypto" { ): void; /** * Provides a synchronous HKDF key derivation function as defined in RFC 5869\. The - * given `ikm`, `salt` and `info` are used with the `digest` to derive a key of`keylen` bytes. + * given `ikm`, `salt` and `info` are used with the `digest` to derive a key of `keylen` bytes. * * The successfully generated `derivedKey` will be returned as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). * @@ -3795,7 +3831,7 @@ declare module "crypto" { /** * Generates a pseudorandom prime of `size` bits. * - * If `options.safe` is `true`, the prime will be a safe prime -- that is,`(prime - 1) / 2` will also be a prime. + * If `options.safe` is `true`, the prime will be a safe prime -- that is, `(prime - 1) / 2` will also be a prime. * * The `options.add` and `options.rem` parameters can be used to enforce additional * requirements, e.g., for Diffie-Hellman: @@ -3811,7 +3847,7 @@ declare module "crypto" { * * `options.rem` is ignored if `options.add` is not given. * * Both `options.add` and `options.rem` must be encoded as big-endian sequences - * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or`DataView`. + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or `DataView`. * * By default, the prime is encoded as a big-endian sequence of octets * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a @@ -3838,7 +3874,7 @@ declare module "crypto" { /** * Generates a pseudorandom prime of `size` bits. * - * If `options.safe` is `true`, the prime will be a safe prime -- that is,`(prime - 1) / 2` will also be a prime. + * If `options.safe` is `true`, the prime will be a safe prime -- that is, `(prime - 1) / 2` will also be a prime. * * The `options.add` and `options.rem` parameters can be used to enforce additional * requirements, e.g., for Diffie-Hellman: @@ -3854,7 +3890,7 @@ declare module "crypto" { * * `options.rem` is ignored if `options.add` is not given. * * Both `options.add` and `options.rem` must be encoded as big-endian sequences - * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or`DataView`. + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or `DataView`. * * By default, the prime is encoded as a big-endian sequence of octets * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a @@ -3900,7 +3936,7 @@ declare module "crypto" { * * `engine` could be either an id or a path to the engine's shared library. * - * The optional `flags` argument uses `ENGINE_METHOD_ALL` by default. The `flags`is a bit field taking one of or a mix of the following flags (defined in`crypto.constants`): + * The optional `flags` argument uses `ENGINE_METHOD_ALL` by default. The `flags` is a bit field taking one of or a mix of the following flags (defined in `crypto.constants`): * * * `crypto.constants.ENGINE_METHOD_RSA` * * `crypto.constants.ENGINE_METHOD_DSA` @@ -4473,6 +4509,14 @@ declare module "crypto" { ): Promise; } } + + global { + var crypto: typeof globalThis extends { + crypto: infer T; + onmessage: any; + } ? T + : webcrypto.Crypto; + } } declare module "node:crypto" { export * from "crypto"; diff --git a/node_modules/@types/node/dgram.d.ts b/node_modules/@types/node/dgram.d.ts index 0b86ae735a285305d46132651ad38c7cdea67d09..3843f237f3c4a40f635e0cba88ab1eb567a761ce 100644 --- a/node_modules/@types/node/dgram.d.ts +++ b/node_modules/@types/node/dgram.d.ts @@ -23,7 +23,7 @@ * server.bind(41234); * // Prints: server listening 0.0.0.0:41234 * ``` - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/dgram.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/dgram.js) */ declare module "dgram" { import { AddressInfo } from "node:net"; @@ -66,7 +66,7 @@ declare module "dgram" { * (it does the right thing for both `udp4` and `udp6` sockets). The bound address * and port can be retrieved using `socket.address().address` and `socket.address().port`. * - * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.close()` on the socket: + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.close()` on the socket: * * ```js * const controller = new AbortController(); @@ -93,7 +93,7 @@ declare module "dgram" { */ class Socket extends EventEmitter { /** - * Tells the kernel to join a multicast group at the given `multicastAddress` and`multicastInterface` using the `IP_ADD_MEMBERSHIP` socket option. If the`multicastInterface` argument is not + * Tells the kernel to join a multicast group at the given `multicastAddress` and `multicastInterface` using the `IP_ADD_MEMBERSHIP` socket option. If the `multicastInterface` argument is not * specified, the operating system will choose * one interface and will add membership to it. To add membership to every * available interface, call `addMembership` multiple times, once per interface. @@ -122,7 +122,7 @@ declare module "dgram" { addMembership(multicastAddress: string, multicastInterface?: string): void; /** * Returns an object containing the address information for a socket. - * For UDP sockets, this object will contain `address`, `family`, and `port`properties. + * For UDP sockets, this object will contain `address`, `family`, and `port` properties. * * This method throws `EBADF` if called on an unbound socket. * @since v0.1.99 @@ -133,10 +133,10 @@ declare module "dgram" { * messages on a named `port` and optional `address`. If `port` is not * specified or is `0`, the operating system will attempt to bind to a * random port. If `address` is not specified, the operating system will - * attempt to listen on all addresses. Once binding is complete, a`'listening'` event is emitted and the optional `callback` function is + * attempt to listen on all addresses. Once binding is complete, a `'listening'` event is emitted and the optional `callback` function is * called. * - * Specifying both a `'listening'` event listener and passing a`callback` to the `socket.bind()` method is not harmful but not very + * Specifying both a `'listening'` event listener and passing a `callback` to the `socket.bind()` method is not harmful but not very * useful. * * A bound datagram socket keeps the Node.js process running to receive @@ -206,7 +206,7 @@ declare module "dgram" { */ disconnect(): void; /** - * Instructs the kernel to leave a multicast group at `multicastAddress` using the`IP_DROP_MEMBERSHIP` socket option. This method is automatically called by the + * Instructs the kernel to leave a multicast group at `multicastAddress` using the `IP_DROP_MEMBERSHIP` socket option. This method is automatically called by the * kernel when the socket is closed or the process terminates, so most apps will * never have reason to call this. * @@ -269,14 +269,14 @@ declare module "dgram" { * any `TypedArray` or a `DataView`, * the `offset` and `length` specify the offset within the `Buffer` where the * message begins and the number of bytes in the message, respectively. - * If `msg` is a `String`, then it is automatically converted to a `Buffer`with `'utf8'` encoding. With messages that + * If `msg` is a `String`, then it is automatically converted to a `Buffer` with `'utf8'` encoding. With messages that * contain multi-byte characters, `offset` and `length` will be calculated with * respect to `byte length` and not the character position. * If `msg` is an array, `offset` and `length` must not be specified. * * The `address` argument is a string. If the value of `address` is a host name, * DNS will be used to resolve the address of the host. If `address` is not - * provided or otherwise nullish, `'127.0.0.1'` (for `udp4` sockets) or `'::1'`(for `udp6` sockets) will be used by default. + * provided or otherwise nullish, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets) will be used by default. * * If the socket has not been previously bound with a call to `bind`, the socket * is assigned a random port number and is bound to the "all interfaces" address @@ -287,7 +287,7 @@ declare module "dgram" { * DNS lookups delay the time to send for at least one tick of the * Node.js event loop. * - * The only way to know for sure that the datagram has been sent is by using a`callback`. If an error occurs and a `callback` is given, the error will be + * The only way to know for sure that the datagram has been sent is by using a `callback`. If an error occurs and a `callback` is given, the error will be * passed as the first argument to the `callback`. If a `callback` is not given, * the error is emitted as an `'error'` event on the `socket` object. * @@ -329,7 +329,7 @@ declare module "dgram" { * determine the optimal strategy on a case-by-case basis. Generally speaking, * however, sending multiple buffers is faster. * - * Example of sending a UDP packet using a socket connected to a port on`localhost`: + * Example of sending a UDP packet using a socket connected to a port on `localhost`: * * ```js * import dgram from 'node:dgram'; @@ -519,10 +519,10 @@ declare module "dgram" { */ unref(): this; /** - * Tells the kernel to join a source-specific multicast channel at the given`sourceAddress` and `groupAddress`, using the `multicastInterface` with the`IP_ADD_SOURCE_MEMBERSHIP` socket + * Tells the kernel to join a source-specific multicast channel at the given `sourceAddress` and `groupAddress`, using the `multicastInterface` with the `IP_ADD_SOURCE_MEMBERSHIP` socket * option. If the `multicastInterface` argument * is not specified, the operating system will choose one interface and will add - * membership to it. To add membership to every available interface, call`socket.addSourceSpecificMembership()` multiple times, once per interface. + * membership to it. To add membership to every available interface, call `socket.addSourceSpecificMembership()` multiple times, once per interface. * * When called on an unbound socket, this method will implicitly bind to a random * port, listening on all interfaces. @@ -530,7 +530,7 @@ declare module "dgram" { */ addSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; /** - * Instructs the kernel to leave a source-specific multicast channel at the given`sourceAddress` and `groupAddress` using the `IP_DROP_SOURCE_MEMBERSHIP`socket option. This method is + * Instructs the kernel to leave a source-specific multicast channel at the given `sourceAddress` and `groupAddress` using the `IP_DROP_SOURCE_MEMBERSHIP` socket option. This method is * automatically called by the kernel when the * socket is closed or the process terminates, so most apps will never have * reason to call this. diff --git a/node_modules/@types/node/diagnostics_channel.d.ts b/node_modules/@types/node/diagnostics_channel.d.ts index cd4bd71b365a1f4ed4c3f851eb3624a7eb3843b9..e25ca694a2d4f88924af80201363c7ea67758e0d 100644 --- a/node_modules/@types/node/diagnostics_channel.d.ts +++ b/node_modules/@types/node/diagnostics_channel.d.ts @@ -20,7 +20,7 @@ * should generally include the module name to avoid collisions with data from * other modules. * @since v15.1.0, v14.17.0 - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/diagnostics_channel.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/diagnostics_channel.js) */ declare module "diagnostics_channel" { import { AsyncLocalStorage } from "node:async_hooks"; @@ -98,7 +98,7 @@ declare module "diagnostics_channel" { function unsubscribe(name: string | symbol, onMessage: ChannelListener): boolean; /** * Creates a `TracingChannel` wrapper for the given `TracingChannel Channels`. If a name is given, the corresponding tracing - * channels will be created in the form of `tracing:${name}:${eventType}` where`eventType` corresponds to the types of `TracingChannel Channels`. + * channels will be created in the form of `tracing:${name}:${eventType}` where `eventType` corresponds to the types of `TracingChannel Channels`. * * ```js * import diagnostics_channel from 'node:diagnostics_channel'; @@ -335,7 +335,7 @@ declare module "diagnostics_channel" { /** * The class `TracingChannel` is a collection of `TracingChannel Channels` which * together express a single traceable action. It is used to formalize and - * simplify the process of producing events for tracing application flow.{@link tracingChannel} is used to construct a`TracingChannel`. As with `Channel` it is recommended to create and reuse a + * simplify the process of producing events for tracing application flow. {@link tracingChannel} is used to construct a `TracingChannel`. As with `Channel` it is recommended to create and reuse a * single `TracingChannel` at the top-level of the file rather than creating them * dynamically. * @since v19.9.0 @@ -419,6 +419,9 @@ declare module "diagnostics_channel" { * This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all * events should have any bound stores set to match this trace context. * + * To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions + * which are added after the trace begins will not receive future events from that trace, only future traces will be seen. + * * ```js * import diagnostics_channel from 'node:diagnostics_channel'; * @@ -451,6 +454,9 @@ declare module "diagnostics_channel" { * returned promise rejects. This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all * events should have any bound stores set to match this trace context. * + * To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions + * which are added after the trace begins will not receive future events from that trace, only future traces will be seen. + * * ```js * import diagnostics_channel from 'node:diagnostics_channel'; * @@ -502,6 +508,9 @@ declare module "diagnostics_channel" { * The callback will also be run with `channel.runStores(context, ...)` which * enables context loss recovery in some cases. * + * To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions + * which are added after the trace begins will not receive future events from that trace, only future traces will be seen. + * * ```js * import diagnostics_channel from 'node:diagnostics_channel'; * import { AsyncLocalStorage } from 'node:async_hooks'; diff --git a/node_modules/@types/node/dns.d.ts b/node_modules/@types/node/dns.d.ts index 380cf7d7015e33c3fd5d2d1ff8c3f43c5f35a92d..f5b6b74a2e1288936b4779819e8deb60d49ebd54 100644 --- a/node_modules/@types/node/dns.d.ts +++ b/node_modules/@types/node/dns.d.ts @@ -41,13 +41,21 @@ * }); * ``` * - * See the `Implementation considerations section` for more information. - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/dns.js) + * See the [Implementation considerations section](https://nodejs.org/docs/latest-v20.x/api/dns.html#implementation-considerations) for more information. + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/dns.js) */ declare module "dns" { import * as dnsPromises from "node:dns/promises"; // Supported getaddrinfo flags. + /** + * Limits returned address types to the types of non-loopback addresses configured on the system. For example, IPv4 addresses are + * only returned if the current system has at least one IPv4 address configured. + */ export const ADDRCONFIG: number; + /** + * If the IPv6 family was specified, but no IPv6 addresses were found, then return IPv4 mapped IPv6 addresses. It is not supported + * on some operating systems (e.g. FreeBSD 10.1). + */ export const V4MAPPED: number; /** * If `dns.V4MAPPED` is specified, return resolved IPv6 addresses as @@ -55,11 +63,37 @@ declare module "dns" { */ export const ALL: number; export interface LookupOptions { - family?: number | undefined; + /** + * The record family. Must be `4`, `6`, or `0`. For backward compatibility reasons, `'IPv4'` and `'IPv6'` are interpreted + * as `4` and `6` respectively. The value 0 indicates that either an IPv4 or IPv6 address is returned. If the value `0` is used + * with `{ all: true } (see below)`, both IPv4 and IPv6 addresses are returned. + * @default 0 + */ + family?: number | "IPv4" | "IPv6" | undefined; + /** + * One or more [supported `getaddrinfo`](https://nodejs.org/docs/latest-v20.x/api/dns.html#supported-getaddrinfo-flags) flags. Multiple flags may be + * passed by bitwise `OR`ing their values. + */ hints?: number | undefined; + /** + * When `true`, the callback returns all resolved addresses in an array. Otherwise, returns a single address. + * @default false + */ all?: boolean | undefined; /** - * @default true + * When `verbatim`, the resolved addresses are return unsorted. When `ipv4first`, the resolved addresses are sorted + * by placing IPv4 addresses before IPv6 addresses. When `ipv6first`, the resolved addresses are sorted by placing IPv6 + * addresses before IPv4 addresses. Default value is configurable using + * {@link setDefaultResultOrder} or [`--dns-result-order`](https://nodejs.org/docs/latest-v20.x/api/cli.html#--dns-result-orderorder). + * @default `verbatim` (addresses are not reordered) + */ + order?: "ipv4first" | "ipv6first" | "verbatim" | undefined; + /** + * When `true`, the callback receives IPv4 and IPv6 addresses in the order the DNS resolver returned them. When `false`, IPv4 + * addresses are placed before IPv6 addresses. This option will be deprecated in favor of `order`. When both are specified, + * `order` has higher precedence. New code should only use `order`. Default value is configurable using {@link setDefaultResultOrder} + * or [`--dns-result-order`](https://nodejs.org/docs/latest-v20.x/api/cli.html#--dns-result-orderorder). + * @default true (addresses are not reordered) */ verbatim?: boolean | undefined; } @@ -70,7 +104,14 @@ declare module "dns" { all: true; } export interface LookupAddress { + /** + * A string representation of an IPv4 or IPv6 address. + */ address: string; + /** + * `4` or `6`, denoting the family of `address`, or `0` if the address is not an IPv4 or IPv6 address. `0` is a likely indicator of a + * bug in the name resolution service used by the operating system. + */ family: number; } /** @@ -79,7 +120,7 @@ declare module "dns" { * integer, then it must be `4` or `6` – if `options` is `0` or not provided, then * IPv4 and IPv6 addresses are both returned if found. * - * With the `all` option set to `true`, the arguments for `callback` change to`(err, addresses)`, with `addresses` being an array of objects with the + * With the `all` option set to `true`, the arguments for `callback` change to `(err, addresses)`, with `addresses` being an array of objects with the * properties `address` and `family`. * * On error, `err` is an `Error` object, where `err.code` is the error code. @@ -91,7 +132,8 @@ declare module "dns" { * The implementation uses an operating system facility that can associate names * with addresses and vice versa. This implementation can have subtle but * important consequences on the behavior of any Node.js program. Please take some - * time to consult the `Implementation considerations section` before using`dns.lookup()`. + * time to consult the [Implementation considerations section](https://nodejs.org/docs/latest-v20.x/api/dns.html#implementation-considerations) + * before using `dns.lookup()`. * * Example usage: * @@ -112,7 +154,8 @@ declare module "dns" { * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] * ``` * - * If this method is invoked as its `util.promisify()` ed version, and `all`is not set to `true`, it returns a `Promise` for an `Object` with `address` and`family` properties. + * If this method is invoked as its [util.promisify()](https://nodejs.org/docs/latest-v20.x/api/util.html#utilpromisifyoriginal) ed + * version, and `all` is not set to `true`, it returns a `Promise` for an `Object` with `address` and `family` properties. * @since v0.1.90 */ export function lookup( @@ -149,9 +192,10 @@ declare module "dns" { * the operating system's underlying `getnameinfo` implementation. * * If `address` is not a valid IP address, a `TypeError` will be thrown. - * The `port` will be coerced to a number. If it is not a legal port, a `TypeError`will be thrown. + * The `port` will be coerced to a number. If it is not a legal port, a `TypeError` will be thrown. * - * On an error, `err` is an `Error` object, where `err.code` is the error code. + * On an error, `err` is an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, + * where `err.code` is the error code. * * ```js * const dns = require('node:dns'); @@ -161,7 +205,8 @@ declare module "dns" { * }); * ``` * - * If this method is invoked as its `util.promisify()` ed version, it returns a`Promise` for an `Object` with `hostname` and `service` properties. + * If this method is invoked as its [util.promisify()](https://nodejs.org/docs/latest-v20.x/api/util.html#utilpromisifyoriginal) ed + * version, it returns a `Promise` for an `Object` with `hostname` and `service` properties. * @since v0.11.14 */ export function lookupService( @@ -272,12 +317,13 @@ declare module "dns" { | AnyTxtRecord; /** * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array - * of the resource records. The `callback` function has arguments`(err, records)`. When successful, `records` will be an array of resource + * of the resource records. The `callback` function has arguments `(err, records)`. When successful, `records` will be an array of resource * records. The type and structure of individual results varies based on `rrtype`: * * * - * On error, `err` is an `Error` object, where `err.code` is one of the `DNS error codes`. + * On error, `err` is an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, + * where `err.code` is one of the `DNS error codes`. * @since v0.1.27 * @param hostname Host name to resolve. * @param [rrtype='A'] Resource record type. @@ -363,7 +409,7 @@ declare module "dns" { ): Promise; } /** - * Uses the DNS protocol to resolve a IPv4 addresses (`A` records) for the`hostname`. The `addresses` argument passed to the `callback` function + * Uses the DNS protocol to resolve a IPv4 addresses (`A` records) for the `hostname`. The `addresses` argument passed to the `callback` function * will contain an array of IPv4 addresses (e.g.`['74.125.79.104', '74.125.79.105', '74.125.79.106']`). * @since v0.1.16 * @param hostname Host name to resolve. @@ -388,7 +434,7 @@ declare module "dns" { function __promisify__(hostname: string, options?: ResolveOptions): Promise; } /** - * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the`hostname`. The `addresses` argument passed to the `callback` function + * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the `hostname`. The `addresses` argument passed to the `callback` function * will contain an array of IPv6 addresses. * @since v0.1.16 * @param hostname Host name to resolve. @@ -413,8 +459,8 @@ declare module "dns" { function __promisify__(hostname: string, options?: ResolveOptions): Promise; } /** - * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. The`addresses` argument passed to the `callback` function - * will contain an array of canonical name records available for the `hostname`(e.g. `['bar.example.com']`). + * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of canonical name records available for the `hostname` (e.g. `['bar.example.com']`). * @since v0.3.2 */ export function resolveCname( @@ -425,7 +471,7 @@ declare module "dns" { function __promisify__(hostname: string): Promise; } /** - * Uses the DNS protocol to resolve `CAA` records for the `hostname`. The`addresses` argument passed to the `callback` function + * Uses the DNS protocol to resolve `CAA` records for the `hostname`. The `addresses` argument passed to the `callback` function * will contain an array of certification authority authorization records * available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]`). * @since v15.0.0, v14.17.0 @@ -438,8 +484,8 @@ declare module "dns" { function __promisify__(hostname: string): Promise; } /** - * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the`hostname`. The `addresses` argument passed to the `callback` function will - * contain an array of objects containing both a `priority` and `exchange`property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`). + * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * contain an array of objects containing both a `priority` and `exchange` property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`). * @since v0.1.27 */ export function resolveMx( @@ -450,7 +496,7 @@ declare module "dns" { function __promisify__(hostname: string): Promise; } /** - * Uses the DNS protocol to resolve regular expression-based records (`NAPTR`records) for the `hostname`. The `addresses` argument passed to the `callback`function will contain an array of + * Uses the DNS protocol to resolve regular expression-based records (`NAPTR` records) for the `hostname`. The `addresses` argument passed to the `callback` function will contain an array of * objects with the following properties: * * * `flags` @@ -480,8 +526,8 @@ declare module "dns" { function __promisify__(hostname: string): Promise; } /** - * Uses the DNS protocol to resolve name server records (`NS` records) for the`hostname`. The `addresses` argument passed to the `callback` function will - * contain an array of name server records available for `hostname`(e.g. `['ns1.example.com', 'ns2.example.com']`). + * Uses the DNS protocol to resolve name server records (`NS` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * contain an array of name server records available for `hostname` (e.g. `['ns1.example.com', 'ns2.example.com']`). * @since v0.1.90 */ export function resolveNs( @@ -492,7 +538,7 @@ declare module "dns" { function __promisify__(hostname: string): Promise; } /** - * Uses the DNS protocol to resolve pointer records (`PTR` records) for the`hostname`. The `addresses` argument passed to the `callback` function will + * Uses the DNS protocol to resolve pointer records (`PTR` records) for the `hostname`. The `addresses` argument passed to the `callback` function will * be an array of strings containing the reply records. * @since v6.0.0 */ @@ -537,7 +583,7 @@ declare module "dns" { function __promisify__(hostname: string): Promise; } /** - * Uses the DNS protocol to resolve service records (`SRV` records) for the`hostname`. The `addresses` argument passed to the `callback` function will + * Uses the DNS protocol to resolve service records (`SRV` records) for the `hostname`. The `addresses` argument passed to the `callback` function will * be an array of objects with the following properties: * * * `priority` @@ -563,7 +609,7 @@ declare module "dns" { function __promisify__(hostname: string): Promise; } /** - * Uses the DNS protocol to resolve text queries (`TXT` records) for the`hostname`. The `records` argument passed to the `callback` function is a + * Uses the DNS protocol to resolve text queries (`TXT` records) for the `hostname`. The `records` argument passed to the `callback` function is a * two-dimensional array of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of * one record. Depending on the use case, these could be either joined together or * treated separately. @@ -603,8 +649,8 @@ declare module "dns" { * minttl: 60 } ] * ``` * - * DNS server operators may choose not to respond to `ANY`queries. It may be better to call individual methods like {@link resolve4},{@link resolveMx}, and so on. For more details, see [RFC - * 8482](https://tools.ietf.org/html/rfc8482). + * DNS server operators may choose not to respond to `ANY` queries. It may be better to call individual methods like {@link resolve4}, {@link resolveMx}, and so on. For more details, see + * [RFC 8482](https://tools.ietf.org/html/rfc8482). */ export function resolveAny( hostname: string, @@ -617,8 +663,8 @@ declare module "dns" { * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an * array of host names. * - * On error, `err` is an `Error` object, where `err.code` is - * one of the `DNS error codes`. + * On error, `err` is an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` is + * one of the [DNS error codes](https://nodejs.org/docs/latest-v20.x/api/dns.html#error-codes). * @since v0.1.16 */ export function reverse( @@ -626,13 +672,15 @@ declare module "dns" { callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void, ): void; /** - * Get the default value for `verbatim` in {@link lookup} and `dnsPromises.lookup()`. The value could be: + * Get the default value for `order` in {@link lookup} and [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options). + * The value could be: * - * * `ipv4first`: for `verbatim` defaulting to `false`. - * * `verbatim`: for `verbatim` defaulting to `true`. - * @since v20.1.0 + * * `ipv4first`: for `order` defaulting to `ipv4first`. + * * `ipv6first`: for `order` defaulting to `ipv6first`. + * * `verbatim`: for `order` defaulting to `verbatim`. + * @since v18.17.0 */ - export function getDefaultResultOrder(): "ipv4first" | "verbatim"; + export function getDefaultResultOrder(): "ipv4first" | "ipv6first" | "verbatim"; /** * Sets the IP address and port of servers to be used when performing DNS * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted @@ -652,14 +700,14 @@ declare module "dns" { * The `dns.setServers()` method must not be called while a DNS query is in * progress. * - * The {@link setServers} method affects only {@link resolve},`dns.resolve*()` and {@link reverse} (and specifically _not_ {@link lookup}). + * The {@link setServers} method affects only {@link resolve}, `dns.resolve*()` and {@link reverse} (and specifically _not_ {@link lookup}). * * This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). - * That is, if attempting to resolve with the first server provided results in a`NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with + * That is, if attempting to resolve with the first server provided results in a `NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with * subsequent servers provided. Fallback DNS servers will only be used if the * earlier ones time out or result in some other error. * @since v0.11.3 - * @param servers array of `RFC 5952` formatted addresses + * @param servers array of [RFC 5952](https://datatracker.ietf.org/doc/html/rfc5952#section-6) formatted addresses */ export function setServers(servers: readonly string[]): void; /** @@ -679,46 +727,53 @@ declare module "dns" { */ export function getServers(): string[]; /** - * Set the default value of `verbatim` in {@link lookup} and `dnsPromises.lookup()`. The value could be: + * Set the default value of `order` in {@link lookup} and [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options). + * The value could be: * - * * `ipv4first`: sets default `verbatim` `false`. - * * `verbatim`: sets default `verbatim` `true`. + * * `ipv4first`: sets default `order` to `ipv4first`. + * * `ipv6first`: sets default `order` to `ipv6first`. + * * `verbatim`: sets default `order` to `verbatim`. * * The default is `verbatim` and {@link setDefaultResultOrder} have higher - * priority than `--dns-result-order`. When using `worker threads`,{@link setDefaultResultOrder} from the main thread won't affect the default - * dns orders in workers. + * priority than [`--dns-result-order`](https://nodejs.org/docs/latest-v20.x/api/cli.html#--dns-result-orderorder). When using + * [worker threads](https://nodejs.org/docs/latest-v20.x/api/worker_threads.html), {@link setDefaultResultOrder} from the main + * thread won't affect the default dns orders in workers. * @since v16.4.0, v14.18.0 - * @param order must be `'ipv4first'` or `'verbatim'`. + * @param order must be `'ipv4first'`, `'ipv6first'` or `'verbatim'`. */ - export function setDefaultResultOrder(order: "ipv4first" | "verbatim"): void; + export function setDefaultResultOrder(order: "ipv4first" | "ipv6first" | "verbatim"): void; // Error codes - export const NODATA: string; - export const FORMERR: string; - export const SERVFAIL: string; - export const NOTFOUND: string; - export const NOTIMP: string; - export const REFUSED: string; - export const BADQUERY: string; - export const BADNAME: string; - export const BADFAMILY: string; - export const BADRESP: string; - export const CONNREFUSED: string; - export const TIMEOUT: string; - export const EOF: string; - export const FILE: string; - export const NOMEM: string; - export const DESTRUCTION: string; - export const BADSTR: string; - export const BADFLAGS: string; - export const NONAME: string; - export const BADHINTS: string; - export const NOTINITIALIZED: string; - export const LOADIPHLPAPI: string; - export const ADDRGETNETWORKPARAMS: string; - export const CANCELLED: string; + export const NODATA: "ENODATA"; + export const FORMERR: "EFORMERR"; + export const SERVFAIL: "ESERVFAIL"; + export const NOTFOUND: "ENOTFOUND"; + export const NOTIMP: "ENOTIMP"; + export const REFUSED: "EREFUSED"; + export const BADQUERY: "EBADQUERY"; + export const BADNAME: "EBADNAME"; + export const BADFAMILY: "EBADFAMILY"; + export const BADRESP: "EBADRESP"; + export const CONNREFUSED: "ECONNREFUSED"; + export const TIMEOUT: "ETIMEOUT"; + export const EOF: "EOF"; + export const FILE: "EFILE"; + export const NOMEM: "ENOMEM"; + export const DESTRUCTION: "EDESTRUCTION"; + export const BADSTR: "EBADSTR"; + export const BADFLAGS: "EBADFLAGS"; + export const NONAME: "ENONAME"; + export const BADHINTS: "EBADHINTS"; + export const NOTINITIALIZED: "ENOTINITIALIZED"; + export const LOADIPHLPAPI: "ELOADIPHLPAPI"; + export const ADDRGETNETWORKPARAMS: "EADDRGETNETWORKPARAMS"; + export const CANCELLED: "ECANCELLED"; export interface ResolverOptions { + /** + * Query timeout in milliseconds, or `-1` to use the default timeout. + */ timeout?: number | undefined; /** + * The number of tries the resolver will try contacting each name server before giving up. * @default 4 */ tries?: number; @@ -727,7 +782,7 @@ declare module "dns" { * An independent resolver for DNS requests. * * Creating a new resolver uses the default server settings. Setting - * the servers used for a resolver using `resolver.setServers()` does not affect + * the servers used for a resolver using [`resolver.setServers()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnssetserversservers) does not affect * other resolvers: * * ```js diff --git a/node_modules/@types/node/dns/promises.d.ts b/node_modules/@types/node/dns/promises.d.ts index ef9b2228123c3a483363e3c102ab8c30ec9be2dd..cb4c03b8ca4f88135374d3b51651ddc6a1a927bf 100644 --- a/node_modules/@types/node/dns/promises.d.ts +++ b/node_modules/@types/node/dns/promises.d.ts @@ -43,18 +43,18 @@ declare module "dns/promises" { * integer, then it must be `4` or `6` – if `options` is not provided, then IPv4 * and IPv6 addresses are both returned if found. * - * With the `all` option set to `true`, the `Promise` is resolved with `addresses`being an array of objects with the properties `address` and `family`. + * With the `all` option set to `true`, the `Promise` is resolved with `addresses` being an array of objects with the properties `address` and `family`. * - * On error, the `Promise` is rejected with an `Error` object, where `err.code`is the error code. + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` is the error code. * Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when * the host name does not exist but also when the lookup fails in other ways * such as no available file descriptors. * - * `dnsPromises.lookup()` does not necessarily have anything to do with the DNS + * [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options) does not necessarily have anything to do with the DNS * protocol. The implementation uses an operating system facility that can * associate names with addresses and vice versa. This implementation can have * subtle but important consequences on the behavior of any Node.js program. Please - * take some time to consult the `Implementation considerations section` before + * take some time to consult the [Implementation considerations section](https://nodejs.org/docs/latest-v20.x/api/dns.html#implementation-considerations) before * using `dnsPromises.lookup()`. * * Example usage: @@ -91,9 +91,9 @@ declare module "dns/promises" { * the operating system's underlying `getnameinfo` implementation. * * If `address` is not a valid IP address, a `TypeError` will be thrown. - * The `port` will be coerced to a number. If it is not a legal port, a `TypeError`will be thrown. + * The `port` will be coerced to a number. If it is not a legal port, a `TypeError` will be thrown. * - * On error, the `Promise` is rejected with an `Error` object, where `err.code`is the error code. + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` is the error code. * * ```js * const dnsPromises = require('node:dns').promises; @@ -119,7 +119,8 @@ declare module "dns/promises" { * * * - * On error, the `Promise` is rejected with an `Error` object, where `err.code`is one of the `DNS error codes`. + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` + * is one of the [DNS error codes](https://nodejs.org/docs/latest-v20.x/api/dns.html#error-codes). * @since v10.6.0 * @param hostname Host name to resolve. * @param [rrtype='A'] Resource record type. @@ -142,7 +143,7 @@ declare module "dns/promises" { rrtype: string, ): Promise; /** - * Uses the DNS protocol to resolve IPv4 addresses (`A` records) for the`hostname`. On success, the `Promise` is resolved with an array of IPv4 + * Uses the DNS protocol to resolve IPv4 addresses (`A` records) for the `hostname`. On success, the `Promise` is resolved with an array of IPv4 * addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`). * @since v10.6.0 * @param hostname Host name to resolve. @@ -151,7 +152,7 @@ declare module "dns/promises" { function resolve4(hostname: string, options: ResolveWithTtlOptions): Promise; function resolve4(hostname: string, options: ResolveOptions): Promise; /** - * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the`hostname`. On success, the `Promise` is resolved with an array of IPv6 + * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the `hostname`. On success, the `Promise` is resolved with an array of IPv6 * addresses. * @since v10.6.0 * @param hostname Host name to resolve. @@ -191,7 +192,7 @@ declare module "dns/promises" { /** * Uses the DNS protocol to resolve `CAA` records for the `hostname`. On success, * the `Promise` is resolved with an array of objects containing available - * certification authority authorization records available for the `hostname`(e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'},{critical: 128, issue: 'pki.example.com'}]`). + * certification authority authorization records available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'},{critical: 128, issue: 'pki.example.com'}]`). * @since v15.0.0, v14.17.0 */ function resolveCaa(hostname: string): Promise; @@ -203,13 +204,13 @@ declare module "dns/promises" { */ function resolveCname(hostname: string): Promise; /** - * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the`hostname`. On success, the `Promise` is resolved with an array of objects + * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the `hostname`. On success, the `Promise` is resolved with an array of objects * containing both a `priority` and `exchange` property (e.g.`[{priority: 10, exchange: 'mx.example.com'}, ...]`). * @since v10.6.0 */ function resolveMx(hostname: string): Promise; /** - * Uses the DNS protocol to resolve regular expression-based records (`NAPTR`records) for the `hostname`. On success, the `Promise` is resolved with an array + * Uses the DNS protocol to resolve regular expression-based records (`NAPTR` records) for the `hostname`. On success, the `Promise` is resolved with an array * of objects with the following properties: * * * `flags` @@ -233,13 +234,13 @@ declare module "dns/promises" { */ function resolveNaptr(hostname: string): Promise; /** - * Uses the DNS protocol to resolve name server records (`NS` records) for the`hostname`. On success, the `Promise` is resolved with an array of name server + * Uses the DNS protocol to resolve name server records (`NS` records) for the `hostname`. On success, the `Promise` is resolved with an array of name server * records available for `hostname` (e.g.`['ns1.example.com', 'ns2.example.com']`). * @since v10.6.0 */ function resolveNs(hostname: string): Promise; /** - * Uses the DNS protocol to resolve pointer records (`PTR` records) for the`hostname`. On success, the `Promise` is resolved with an array of strings + * Uses the DNS protocol to resolve pointer records (`PTR` records) for the `hostname`. On success, the `Promise` is resolved with an array of strings * containing the reply records. * @since v10.6.0 */ @@ -272,7 +273,7 @@ declare module "dns/promises" { */ function resolveSoa(hostname: string): Promise; /** - * Uses the DNS protocol to resolve service records (`SRV` records) for the`hostname`. On success, the `Promise` is resolved with an array of objects with + * Uses the DNS protocol to resolve service records (`SRV` records) for the `hostname`. On success, the `Promise` is resolved with an array of objects with * the following properties: * * * `priority` @@ -292,7 +293,7 @@ declare module "dns/promises" { */ function resolveSrv(hostname: string): Promise; /** - * Uses the DNS protocol to resolve text queries (`TXT` records) for the`hostname`. On success, the `Promise` is resolved with a two-dimensional array + * Uses the DNS protocol to resolve text queries (`TXT` records) for the `hostname`. On success, the `Promise` is resolved with a two-dimensional array * of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of * one record. Depending on the use case, these could be either joined together or * treated separately. @@ -303,12 +304,14 @@ declare module "dns/promises" { * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an * array of host names. * - * On error, the `Promise` is rejected with an `Error` object, where `err.code`is one of the `DNS error codes`. + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` + * is one of the [DNS error codes](https://nodejs.org/docs/latest-v20.x/api/dns.html#error-codes). * @since v10.6.0 */ function reverse(ip: string): Promise; /** - * Get the default value for `verbatim` in {@link lookup} and `dnsPromises.lookup()`. The value could be: + * Get the default value for `verbatim` in {@link lookup} and [dnsPromises.lookup()](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options). + * The value could be: * * * `ipv4first`: for `verbatim` defaulting to `false`. * * `verbatim`: for `verbatim` defaulting to `true`. @@ -335,7 +338,7 @@ declare module "dns/promises" { * progress. * * This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). - * That is, if attempting to resolve with the first server provided results in a`NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with + * That is, if attempting to resolve with the first server provided results in a `NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with * subsequent servers provided. Fallback DNS servers will only be used if the * earlier ones time out or result in some other error. * @since v10.6.0 @@ -343,23 +346,51 @@ declare module "dns/promises" { */ function setServers(servers: readonly string[]): void; /** - * Set the default value of `verbatim` in `dns.lookup()` and `dnsPromises.lookup()`. The value could be: + * Set the default value of `order` in `dns.lookup()` and `{@link lookup}`. The value could be: * - * * `ipv4first`: sets default `verbatim` `false`. - * * `verbatim`: sets default `verbatim` `true`. + * * `ipv4first`: sets default `order` to `ipv4first`. + * * `ipv6first`: sets default `order` to `ipv6first`. + * * `verbatim`: sets default `order` to `verbatim`. * - * The default is `verbatim` and `dnsPromises.setDefaultResultOrder()` have - * higher priority than `--dns-result-order`. When using `worker threads`,`dnsPromises.setDefaultResultOrder()` from the main thread won't affect the - * default dns orders in workers. + * The default is `verbatim` and [dnsPromises.setDefaultResultOrder()](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetdefaultresultorderorder) + * have higher priority than [`--dns-result-order`](https://nodejs.org/docs/latest-v20.x/api/cli.html#--dns-result-orderorder). + * When using [worker threads](https://nodejs.org/docs/latest-v20.x/api/worker_threads.html), [`dnsPromises.setDefaultResultOrder()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetdefaultresultorderorder) + * from the main thread won't affect the default dns orders in workers. * @since v16.4.0, v14.18.0 - * @param order must be `'ipv4first'` or `'verbatim'`. + * @param order must be `'ipv4first'`, `'ipv6first'` or `'verbatim'`. */ - function setDefaultResultOrder(order: "ipv4first" | "verbatim"): void; + function setDefaultResultOrder(order: "ipv4first" | "ipv6first" | "verbatim"): void; + // Error codes + const NODATA: "ENODATA"; + const FORMERR: "EFORMERR"; + const SERVFAIL: "ESERVFAIL"; + const NOTFOUND: "ENOTFOUND"; + const NOTIMP: "ENOTIMP"; + const REFUSED: "EREFUSED"; + const BADQUERY: "EBADQUERY"; + const BADNAME: "EBADNAME"; + const BADFAMILY: "EBADFAMILY"; + const BADRESP: "EBADRESP"; + const CONNREFUSED: "ECONNREFUSED"; + const TIMEOUT: "ETIMEOUT"; + const EOF: "EOF"; + const FILE: "EFILE"; + const NOMEM: "ENOMEM"; + const DESTRUCTION: "EDESTRUCTION"; + const BADSTR: "EBADSTR"; + const BADFLAGS: "EBADFLAGS"; + const NONAME: "ENONAME"; + const BADHINTS: "EBADHINTS"; + const NOTINITIALIZED: "ENOTINITIALIZED"; + const LOADIPHLPAPI: "ELOADIPHLPAPI"; + const ADDRGETNETWORKPARAMS: "EADDRGETNETWORKPARAMS"; + const CANCELLED: "ECANCELLED"; + /** * An independent resolver for DNS requests. * * Creating a new resolver uses the default server settings. Setting - * the servers used for a resolver using `resolver.setServers()` does not affect + * the servers used for a resolver using [`resolver.setServers()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetserversservers) does not affect * other resolvers: * * ```js @@ -400,6 +431,11 @@ declare module "dns/promises" { */ class Resolver { constructor(options?: ResolverOptions); + /** + * Cancel all outstanding DNS queries made by this resolver. The corresponding + * callbacks will be called with an error with code `ECANCELLED`. + * @since v8.3.0 + */ cancel(): void; getServers: typeof getServers; resolve: typeof resolve; @@ -416,6 +452,21 @@ declare module "dns/promises" { resolveSrv: typeof resolveSrv; resolveTxt: typeof resolveTxt; reverse: typeof reverse; + /** + * The resolver instance will send its requests from the specified IP address. + * This allows programs to specify outbound interfaces when used on multi-homed + * systems. + * + * If a v4 or v6 address is not specified, it is set to the default and the + * operating system will choose a local address automatically. + * + * The resolver will use the v4 local address when making requests to IPv4 DNS + * servers, and the v6 local address when making requests to IPv6 DNS servers. + * The `rrtype` of resolution requests has no impact on the local address used. + * @since v15.1.0, v14.17.0 + * @param [ipv4='0.0.0.0'] A string representation of an IPv4 address. + * @param [ipv6='::0'] A string representation of an IPv6 address. + */ setLocalAddress(ipv4?: string, ipv6?: string): void; setServers: typeof setServers; } diff --git a/node_modules/@types/node/dom-events.d.ts b/node_modules/@types/node/dom-events.d.ts index 147a7b657dfa93431b2724b9e31c05f75cfe230c..f47f71d63866904b6a83bbd68f100db0f96adb00 100644 --- a/node_modules/@types/node/dom-events.d.ts +++ b/node_modules/@types/node/dom-events.d.ts @@ -89,6 +89,8 @@ interface AddEventListenerOptions extends EventListenerOptions { once?: boolean; /** When `true`, serves as a hint that the listener will not call the `Event` object's `preventDefault()` method. Default: false. */ passive?: boolean; + /** The listener will be removed when the given AbortSignal object's `abort()` method is called. */ + signal?: AbortSignal; } interface EventListener { diff --git a/node_modules/@types/node/domain.d.ts b/node_modules/@types/node/domain.d.ts index 72f17bd801e745a3697e684826345fee0d998fcb..d8bc9995221bcea3a0a131aab6bbf2e8d3e1543c 100644 --- a/node_modules/@types/node/domain.d.ts +++ b/node_modules/@types/node/domain.d.ts @@ -9,10 +9,10 @@ * Domains provide a way to handle multiple different IO operations as a * single group. If any of the event emitters or callbacks registered to a * domain emit an `'error'` event, or throw an error, then the domain object - * will be notified, rather than losing the context of the error in the`process.on('uncaughtException')` handler, or causing the program to + * will be notified, rather than losing the context of the error in the `process.on('uncaughtException')` handler, or causing the program to * exit immediately with an error code. * @deprecated Since v1.4.2 - Deprecated - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/domain.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/domain.js) */ declare module "domain" { import EventEmitter = require("node:events"); @@ -29,7 +29,7 @@ declare module "domain" { */ members: Array; /** - * The `enter()` method is plumbing used by the `run()`, `bind()`, and`intercept()` methods to set the active domain. It sets `domain.active` and`process.domain` to the domain, and implicitly + * The `enter()` method is plumbing used by the `run()`, `bind()`, and `intercept()` methods to set the active domain. It sets `domain.active` and `process.domain` to the domain, and implicitly * pushes the domain onto the domain * stack managed by the domain module (see {@link exit} for details on the * domain stack). The call to `enter()` delimits the beginning of a chain of @@ -47,7 +47,7 @@ declare module "domain" { * The call to `exit()` delimits either the end of or an interruption to the chain * of asynchronous calls and I/O operations bound to a domain. * - * If there are multiple, nested domains bound to the current execution context,`exit()` will exit any domains nested within this domain. + * If there are multiple, nested domains bound to the current execution context, `exit()` will exit any domains nested within this domain. * * Calling `exit()` changes only the active domain, and does not alter the domain * itself. `enter()` and `exit()` can be called an arbitrary number of times on a diff --git a/node_modules/@types/node/events.d.ts b/node_modules/@types/node/events.d.ts index 6ed47c53aa9c2a5d6d4d146aaff9855135036631..1d30215e80865ab0453d6c773bbdc7fea2bcbe13 100644 --- a/node_modules/@types/node/events.d.ts +++ b/node_modules/@types/node/events.d.ts @@ -32,7 +32,7 @@ * }); * myEmitter.emit('event'); * ``` - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/events.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/events.js) */ declare module "events" { import { AsyncResource, AsyncResourceOptions } from "node:async_hooks"; @@ -75,24 +75,63 @@ declare module "events" { */ captureRejections?: boolean | undefined; } - // Any EventTarget with a Node-style `once` function - interface _NodeEventTarget { - once(eventName: string | symbol, listener: (...args: any[]) => void): this; - } - // Any EventTarget with a DOM-style `addEventListener` - interface _DOMEventTarget { - addEventListener( - eventName: string, - listener: (...args: any[]) => void, - opts?: { - once: boolean; - }, - ): any; - } interface StaticEventEmitterOptions { + /** + * Can be used to cancel awaiting events. + */ signal?: AbortSignal | undefined; + /** + * Names of events that will end the iteration. + */ + close?: string[] | undefined; + /** + * The high watermark. The emitter is paused every time the size + * of events being buffered is higher than it. Supported only + * on emitters implementing `pause()` and `resume()` methods. + * @default `Number.MAX_SAFE_INTEGER` + */ + highWaterMark?: number | undefined; + /** + * The low watermark. The emitter is resumed every time the size of events being buffered + * is lower than it. Supported only on emitters implementing `pause()` and `resume()` methods. + * @default 1 + */ + lowWaterMark?: number | undefined; } - interface EventEmitter extends NodeJS.EventEmitter {} + interface StaticEventEmitterIteratorOptions extends StaticEventEmitterOptions { + /** + * Names of events that will end the iteration. + */ + close?: string[]; + /** + * The emitter is paused every time the size of events being buffered is higher than it. Supported only on emitters implementing pause() and resume() methods. + * @default Number.MAX_SAFE_INTEGER + */ + highWaterMark?: number; + /** + * The emitter is resumed every time the size of events being buffered is lower than it. Supported only on emitters implementing pause() and resume() methods. + * @default 1 + */ + lowWaterMark?: number; + } + interface EventEmitter = DefaultEventMap> extends NodeJS.EventEmitter {} + type EventMap = Record | DefaultEventMap; + type DefaultEventMap = [never]; + type AnyRest = [...args: any[]]; + type Args = T extends DefaultEventMap ? AnyRest : ( + K extends keyof T ? T[K] : never + ); + type Key = T extends DefaultEventMap ? string | symbol : K | keyof T; + type Key2 = T extends DefaultEventMap ? string | symbol : K & keyof T; + type Listener = T extends DefaultEventMap ? F : ( + K extends keyof T ? ( + T[K] extends unknown[] ? (...args: T[K]) => void : never + ) + : never + ); + type Listener1 = Listener void>; + type Listener2 = Listener; + /** * The `EventEmitter` class is defined and exposed by the `node:events` module: * @@ -106,10 +145,10 @@ declare module "events" { * It supports the following option: * @since v0.1.26 */ - class EventEmitter { + class EventEmitter = DefaultEventMap> { constructor(options?: EventEmitterOptions); - [EventEmitter.captureRejectionSymbol]?(error: Error, event: string, ...args: any[]): void; + [EventEmitter.captureRejectionSymbol]?(error: Error, event: Key, ...args: Args): void; /** * Creates a `Promise` that is fulfilled when the `EventEmitter` emits the given @@ -145,7 +184,7 @@ declare module "events" { * } * ``` * - * The special handling of the `'error'` event is only used when `events.once()`is used to wait for another event. If `events.once()` is used to wait for the + * The special handling of the `'error'` event is only used when `events.once()` is used to wait for another event. If `events.once()` is used to wait for the * '`error'` event itself, then it is treated as any other kind of event without * special handling: * @@ -191,11 +230,11 @@ declare module "events" { * @since v11.13.0, v10.16.0 */ static once( - emitter: _NodeEventTarget, + emitter: NodeJS.EventEmitter, eventName: string | symbol, - options?: StaticEventEmitterOptions, + options?: Pick, ): Promise; - static once(emitter: _DOMEventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise; + static once(emitter: EventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise; /** * ```js * import { on, EventEmitter } from 'node:events'; @@ -251,17 +290,44 @@ declare module "events" { * * process.nextTick(() => ac.abort()); * ``` + * + * Use the `close` option to specify an array of event names that will end the iteration: + * + * ```js + * import { on, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * ee.emit('close'); + * }); + * + * for await (const event of on(ee, 'foo', { close: ['close'] })) { + * console.log(event); // prints ['bar'] [42] + * } + * // the loop will exit after 'close' is emitted + * console.log('done'); // prints 'done' + * ``` * @since v13.6.0, v12.16.0 * @param eventName The name of the event being listened for - * @return that iterates `eventName` events emitted by the `emitter` + * @return An `AsyncIterator` that iterates `eventName` events emitted by the `emitter` */ static on( emitter: NodeJS.EventEmitter, - eventName: string, + eventName: string | symbol, options?: StaticEventEmitterOptions, ): AsyncIterableIterator; + static on( + emitter: EventTarget, + eventName: string, + options?: StaticEventEmitterIteratorOptions, + ): AsyncIterableIterator; /** - * A class method that returns the number of listeners for the given `eventName`registered on the given `emitter`. + * A class method that returns the number of listeners for the given `eventName` registered on the given `emitter`. * * ```js * import { EventEmitter, listenerCount } from 'node:events'; @@ -305,7 +371,7 @@ declare module "events" { * ``` * @since v15.2.0, v14.17.0 */ - static getEventListeners(emitter: _DOMEventTarget | NodeJS.EventEmitter, name: string | symbol): Function[]; + static getEventListeners(emitter: EventTarget | NodeJS.EventEmitter, name: string | symbol): Function[]; /** * Returns the currently set max amount of listeners. * @@ -334,7 +400,7 @@ declare module "events" { * ``` * @since v19.9.0 */ - static getMaxListeners(emitter: _DOMEventTarget | NodeJS.EventEmitter): number; + static getMaxListeners(emitter: EventTarget | NodeJS.EventEmitter): number; /** * ```js * import { setMaxListeners, EventEmitter } from 'node:events'; @@ -349,7 +415,7 @@ declare module "events" { * @param eventsTargets Zero or more {EventTarget} or {EventEmitter} instances. If none are specified, `n` is set as the default max for all newly created {EventTarget} and {EventEmitter} * objects. */ - static setMaxListeners(n?: number, ...eventTargets: Array<_DOMEventTarget | NodeJS.EventEmitter>): void; + static setMaxListeners(n?: number, ...eventTargets: Array): void; /** * Listens once to the `abort` event on the provided `signal`. * @@ -386,9 +452,9 @@ declare module "events" { */ static addAbortListener(signal: AbortSignal, resource: (event: Event) => void): Disposable; /** - * This symbol shall be used to install a listener for only monitoring `'error'`events. Listeners installed using this symbol are called before the regular`'error'` listeners are called. + * This symbol shall be used to install a listener for only monitoring `'error'` events. Listeners installed using this symbol are called before the regular `'error'` listeners are called. * - * Installing a listener using this symbol does not change the behavior once an`'error'` event is emitted. Therefore, the process will still crash if no + * Installing a listener using this symbol does not change the behavior once an `'error'` event is emitted. Therefore, the process will still crash if no * regular `'error'` listener is installed. * @since v13.6.0, v12.17.0 */ @@ -411,16 +477,18 @@ declare module "events" { * By default, a maximum of `10` listeners can be registered for any single * event. This limit can be changed for individual `EventEmitter` instances * using the `emitter.setMaxListeners(n)` method. To change the default - * for _all_`EventEmitter` instances, the `events.defaultMaxListeners`property can be used. If this value is not a positive number, a `RangeError`is thrown. + * for _all_`EventEmitter` instances, the `events.defaultMaxListeners` property + * can be used. If this value is not a positive number, a `RangeError` is thrown. * * Take caution when setting the `events.defaultMaxListeners` because the - * change affects _all_`EventEmitter` instances, including those created before + * change affects _all_ `EventEmitter` instances, including those created before * the change is made. However, calling `emitter.setMaxListeners(n)` still has * precedence over `events.defaultMaxListeners`. * * This is not a hard limit. The `EventEmitter` instance will allow * more listeners to be added but will output a trace warning to stderr indicating - * that a "possible EventEmitter memory leak" has been detected. For any single`EventEmitter`, the `emitter.getMaxListeners()` and `emitter.setMaxListeners()`methods can be used to + * that a "possible EventEmitter memory leak" has been detected. For any single + * `EventEmitter`, the `emitter.getMaxListeners()` and `emitter.setMaxListeners()` methods can be used to * temporarily avoid this warning: * * ```js @@ -536,18 +604,18 @@ declare module "events" { } global { namespace NodeJS { - interface EventEmitter { - [EventEmitter.captureRejectionSymbol]?(error: Error, event: string, ...args: any[]): void; + interface EventEmitter = DefaultEventMap> { + [EventEmitter.captureRejectionSymbol]?(error: Error, event: Key, ...args: Args): void; /** * Alias for `emitter.on(eventName, listener)`. * @since v0.1.26 */ - addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + addListener(eventName: Key, listener: Listener1): this; /** - * Adds the `listener` function to the end of the listeners array for the - * event named `eventName`. No checks are made to see if the `listener` has - * already been added. Multiple calls passing the same combination of `eventName`and `listener` will result in the `listener` being added, and called, multiple - * times. + * Adds the `listener` function to the end of the listeners array for the event + * named `eventName`. No checks are made to see if the `listener` has already + * been added. Multiple calls passing the same combination of `eventName` and + * `listener` will result in the `listener` being added, and called, multiple times. * * ```js * server.on('connection', (stream) => { @@ -557,7 +625,7 @@ declare module "events" { * * Returns a reference to the `EventEmitter`, so that calls can be chained. * - * By default, event listeners are invoked in the order they are added. The`emitter.prependListener()` method can be used as an alternative to add the + * By default, event listeners are invoked in the order they are added. The `emitter.prependListener()` method can be used as an alternative to add the * event listener to the beginning of the listeners array. * * ```js @@ -574,9 +642,9 @@ declare module "events" { * @param eventName The name of the event. * @param listener The callback function */ - on(eventName: string | symbol, listener: (...args: any[]) => void): this; + on(eventName: Key, listener: Listener1): this; /** - * Adds a **one-time**`listener` function for the event named `eventName`. The + * Adds a **one-time** `listener` function for the event named `eventName`. The * next time `eventName` is triggered, this listener is removed and then invoked. * * ```js @@ -587,7 +655,7 @@ declare module "events" { * * Returns a reference to the `EventEmitter`, so that calls can be chained. * - * By default, event listeners are invoked in the order they are added. The`emitter.prependOnceListener()` method can be used as an alternative to add the + * By default, event listeners are invoked in the order they are added. The `emitter.prependOnceListener()` method can be used as an alternative to add the * event listener to the beginning of the listeners array. * * ```js @@ -604,9 +672,9 @@ declare module "events" { * @param eventName The name of the event. * @param listener The callback function */ - once(eventName: string | symbol, listener: (...args: any[]) => void): this; + once(eventName: Key, listener: Listener1): this; /** - * Removes the specified `listener` from the listener array for the event named`eventName`. + * Removes the specified `listener` from the listener array for the event named `eventName`. * * ```js * const callback = (stream) => { @@ -623,7 +691,7 @@ declare module "events" { * called multiple times to remove each instance. * * Once an event is emitted, all listeners attached to it at the - * time of emitting are called in order. This implies that any`removeListener()` or `removeAllListeners()` calls _after_ emitting and _before_ the last listener finishes execution + * time of emitting are called in order. This implies that any `removeListener()` or `removeAllListeners()` calls _after_ emitting and _before_ the last listener finishes execution * will not remove them from`emit()` in progress. Subsequent events behave as expected. * * ```js @@ -666,7 +734,7 @@ declare module "events" { * * When a single function has been added as a handler multiple times for a single * event (as in the example below), `removeListener()` will remove the most - * recently added instance. In the example the `once('ping')`listener is removed: + * recently added instance. In the example the `once('ping')` listener is removed: * * ```js * import { EventEmitter } from 'node:events'; @@ -687,12 +755,12 @@ declare module "events" { * Returns a reference to the `EventEmitter`, so that calls can be chained. * @since v0.1.26 */ - removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + removeListener(eventName: Key, listener: Listener1): this; /** * Alias for `emitter.removeListener()`. * @since v10.0.0 */ - off(eventName: string | symbol, listener: (...args: any[]) => void): this; + off(eventName: Key, listener: Listener1): this; /** * Removes all listeners, or those of the specified `eventName`. * @@ -703,12 +771,12 @@ declare module "events" { * Returns a reference to the `EventEmitter`, so that calls can be chained. * @since v0.1.26 */ - removeAllListeners(event?: string | symbol): this; + removeAllListeners(eventName?: Key): this; /** * By default `EventEmitter`s will print a warning if more than `10` listeners are * added for a particular event. This is a useful default that helps finding * memory leaks. The `emitter.setMaxListeners()` method allows the limit to be - * modified for this specific `EventEmitter` instance. The value can be set to`Infinity` (or `0`) to indicate an unlimited number of listeners. + * modified for this specific `EventEmitter` instance. The value can be set to `Infinity` (or `0`) to indicate an unlimited number of listeners. * * Returns a reference to the `EventEmitter`, so that calls can be chained. * @since v0.3.5 @@ -732,7 +800,7 @@ declare module "events" { * ``` * @since v0.1.26 */ - listeners(eventName: string | symbol): Function[]; + listeners(eventName: Key): Array>; /** * Returns a copy of the array of listeners for the event named `eventName`, * including any wrappers (such as those created by `.once()`). @@ -763,9 +831,9 @@ declare module "events" { * ``` * @since v9.4.0 */ - rawListeners(eventName: string | symbol): Function[]; + rawListeners(eventName: Key): Array>; /** - * Synchronously calls each of the listeners registered for the event named`eventName`, in the order they were registered, passing the supplied arguments + * Synchronously calls each of the listeners registered for the event named `eventName`, in the order they were registered, passing the supplied arguments * to each. * * Returns `true` if the event had listeners, `false` otherwise. @@ -804,7 +872,7 @@ declare module "events" { * ``` * @since v0.1.26 */ - emit(eventName: string | symbol, ...args: any[]): boolean; + emit(eventName: Key, ...args: Args): boolean; /** * Returns the number of listeners listening for the event named `eventName`. * If `listener` is provided, it will return how many times the listener is found @@ -813,12 +881,12 @@ declare module "events" { * @param eventName The name of the event being listened for * @param listener The event handler function */ - listenerCount(eventName: string | symbol, listener?: Function): number; + listenerCount(eventName: Key, listener?: Listener2): number; /** * Adds the `listener` function to the _beginning_ of the listeners array for the * event named `eventName`. No checks are made to see if the `listener` has - * already been added. Multiple calls passing the same combination of `eventName`and `listener` will result in the `listener` being added, and called, multiple - * times. + * already been added. Multiple calls passing the same combination of `eventName` + * and `listener` will result in the `listener` being added, and called, multiple times. * * ```js * server.prependListener('connection', (stream) => { @@ -831,7 +899,7 @@ declare module "events" { * @param eventName The name of the event. * @param listener The callback function */ - prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependListener(eventName: Key, listener: Listener1): this; /** * Adds a **one-time**`listener` function for the event named `eventName` to the _beginning_ of the listeners array. The next time `eventName` is triggered, this * listener is removed, and then invoked. @@ -847,7 +915,7 @@ declare module "events" { * @param eventName The name of the event. * @param listener The callback function */ - prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(eventName: Key, listener: Listener1): this; /** * Returns an array listing the events for which the emitter has registered * listeners. The values in the array are strings or `Symbol`s. @@ -867,7 +935,7 @@ declare module "events" { * ``` * @since v6.0.0 */ - eventNames(): Array; + eventNames(): Array<(string | symbol) & Key2>; } } } diff --git a/node_modules/@types/node/fs.d.ts b/node_modules/@types/node/fs.d.ts index 5cbca12fce3886269ec0648145cb6626be34fdc1..dc1d5da807f4b96d343f7c5372fba28a9730ebd0 100644 --- a/node_modules/@types/node/fs.d.ts +++ b/node_modules/@types/node/fs.d.ts @@ -16,7 +16,7 @@ * * All file system operations have synchronous, callback, and promise-based * forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM). - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/fs.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/fs.js) */ declare module "fs" { import * as stream from "node:stream"; @@ -77,7 +77,7 @@ declare module "fs" { * their synchronous counterparts are of this type. * If `bigint` in the `options` passed to those methods is true, the numeric values * will be `bigint` instead of `number`, and the object will contain additional - * nanosecond-precision properties suffixed with `Ns`. + * nanosecond-precision properties suffixed with `Ns`. `Stat` objects are not to be created directly using the `new` keyword. * * ```console * Stats { @@ -242,7 +242,13 @@ declare module "fs" { name: string; /** * The base path that this `fs.Dirent` object refers to. + * @since v20.12.0 + */ + parentPath: string; + /** + * Alias for `dirent.parentPath`. * @since v20.1.0 + * @deprecated Since v20.12.0 */ path: string; } @@ -296,7 +302,7 @@ declare module "fs" { /** * Asynchronously read the next directory entry via [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) as an `fs.Dirent`. * - * A promise is returned that will be fulfilled with an `fs.Dirent`, or `null`if there are no more directory entries to read. + * A promise is returned that will be fulfilled with an `fs.Dirent`, or `null` if there are no more directory entries to read. * * Directory entries returned by this function are in no particular order as * provided by the operating system's underlying directory mechanisms. @@ -1439,7 +1445,7 @@ declare module "fs" { * 2. The maximum number of symbolic links is platform-independent and generally * (much) higher than what the native [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html) implementation supports. * - * The `callback` gets two arguments `(err, resolvedPath)`. May use `process.cwd`to resolve relative paths. + * The `callback` gets two arguments `(err, resolvedPath)`. May use `process.cwd` to resolve relative paths. * * Only paths that can be converted to UTF8 strings are supported. * @@ -1683,7 +1689,7 @@ declare module "fs" { retryDelay?: number | undefined; } /** - * Asynchronously removes files and directories (modeled on the standard POSIX `rm`utility). No arguments other than a possible exception are given to the + * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). No arguments other than a possible exception are given to the * completion callback. * @since v14.14.0 */ @@ -1696,7 +1702,7 @@ declare module "fs" { function __promisify__(path: PathLike, options?: RmOptions): Promise; } /** - * Synchronously removes files and directories (modeled on the standard POSIX `rm`utility). Returns `undefined`. + * Synchronously removes files and directories (modeled on the standard POSIX `rm` utility). Returns `undefined`. * @since v14.14.0 */ export function rmSync(path: PathLike, options?: RmOptions): void; @@ -1721,7 +1727,7 @@ declare module "fs" { * created (for instance, if it was previously created). * * The optional `options` argument can be an integer specifying `mode` (permission - * and sticky bits), or an object with a `mode` property and a `recursive`property indicating whether parent directories should be created. Calling`fs.mkdir()` when `path` is a directory that + * and sticky bits), or an object with a `mode` property and a `recursive` property indicating whether parent directories should be created. Calling `fs.mkdir()` when `path` is a directory that * exists results in an error only * when `recursive` is false. If `recursive` is false and the directory exists, * an `EEXIST` error occurs. @@ -1829,7 +1835,7 @@ declare module "fs" { ): Promise; } /** - * Synchronously creates a directory. Returns `undefined`, or if `recursive` is`true`, the first directory path created. + * Synchronously creates a directory. Returns `undefined`, or if `recursive` is `true`, the first directory path created. * This is the synchronous version of {@link mkdir}. * * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. @@ -1866,7 +1872,7 @@ declare module "fs" { /** * Creates a unique temporary directory. * - * Generates six random characters to be appended behind a required`prefix` to create a unique temporary directory. Due to platform + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. Due to platform * inconsistencies, avoid trailing `X` characters in `prefix`. Some platforms, * notably the BSDs, can return more than six random characters, and replace * trailing `X` characters in `prefix` with random characters. @@ -2003,7 +2009,7 @@ declare module "fs" { */ export function mkdtempSync(prefix: string, options?: EncodingOption): string | Buffer; /** - * Reads the contents of a directory. The callback gets two arguments `(err, files)`where `files` is an array of the names of the files in the directory excluding`'.'` and `'..'`. + * Reads the contents of a directory. The callback gets two arguments `(err, files)` where `files` is an array of the names of the files in the directory excluding `'.'` and `'..'`. * * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. * @@ -2297,8 +2303,8 @@ declare module "fs" { * * The `atime` and `mtime` arguments follow these rules: * - * * Values can be either numbers representing Unix epoch time in seconds,`Date`s, or a numeric string like `'123456789.0'`. - * * If the value can not be converted to a number, or is `NaN`, `Infinity`, or`-Infinity`, an `Error` will be thrown. + * * Values can be either numbers representing Unix epoch time in seconds, `Date`s, or a numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity`, or `-Infinity`, an `Error` will be thrown. * @since v0.4.2 */ export function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; @@ -2371,7 +2377,7 @@ declare module "fs" { * should be written. If `typeof position !== 'number'`, the data will be written * at the current position. See [`pwrite(2)`](http://man7.org/linux/man-pages/man2/pwrite.2.html). * - * The callback will be given three arguments `(err, bytesWritten, buffer)` where`bytesWritten` specifies how many _bytes_ were written from `buffer`. + * The callback will be given three arguments `(err, bytesWritten, buffer)` where `bytesWritten` specifies how many _bytes_ were written from `buffer`. * * If this method is invoked as its `util.promisify()` ed version, it returns * a promise for an `Object` with `bytesWritten` and `buffer` properties. @@ -2820,7 +2826,7 @@ declare module "fs" { * If the `encoding` option is specified then this function returns a * string. Otherwise it returns a buffer. * - * Similar to {@link readFile}, when the path is a directory, the behavior of`fs.readFileSync()` is platform-specific. + * Similar to {@link readFile}, when the path is a directory, the behavior of `fs.readFileSync()` is platform-specific. * * ```js * import { readFileSync } from 'node:fs'; @@ -2890,7 +2896,7 @@ declare module "fs" { * When `file` is a filename, asynchronously writes data to the file, replacing the * file if it already exists. `data` can be a string or a buffer. * - * When `file` is a file descriptor, the behavior is similar to calling`fs.write()` directly (which is recommended). See the notes below on using + * When `file` is a file descriptor, the behavior is similar to calling `fs.write()` directly (which is recommended). See the notes below on using * a file descriptor. * * The `encoding` option is ignored if `data` is a buffer. @@ -3139,7 +3145,7 @@ declare module "fs" { * Watch for changes on `filename`. The callback `listener` will be called each * time the file is accessed. * - * The `options` argument may be omitted. If provided, it should be an object. The`options` object may contain a boolean named `persistent` that indicates + * The `options` argument may be omitted. If provided, it should be an object. The `options` object may contain a boolean named `persistent` that indicates * whether the process should continue to run as long as files are being watched. * The `options` object may specify an `interval` property indicating how often the * target should be polled in milliseconds. @@ -3168,7 +3174,7 @@ declare module "fs" { * again, with the latest stat objects. This is a change in functionality since * v0.10. * - * Using {@link watch} is more efficient than `fs.watchFile` and`fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and`fs.unwatchFile` when possible. + * Using {@link watch} is more efficient than `fs.watchFile` and `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` when possible. * * When a file being watched by `fs.watchFile()` disappears and reappears, * then the contents of `previous` in the second callback event (the file's @@ -3190,7 +3196,7 @@ declare module "fs" { * Watch for changes on `filename`. The callback `listener` will be called each * time the file is accessed. * - * The `options` argument may be omitted. If provided, it should be an object. The`options` object may contain a boolean named `persistent` that indicates + * The `options` argument may be omitted. If provided, it should be an object. The `options` object may contain a boolean named `persistent` that indicates * whether the process should continue to run as long as files are being watched. * The `options` object may specify an `interval` property indicating how often the * target should be polled in milliseconds. @@ -3219,7 +3225,7 @@ declare module "fs" { * again, with the latest stat objects. This is a change in functionality since * v0.10. * - * Using {@link watch} is more efficient than `fs.watchFile` and`fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and`fs.unwatchFile` when possible. + * Using {@link watch} is more efficient than `fs.watchFile` and `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` when possible. * * When a file being watched by `fs.watchFile()` disappears and reappears, * then the contents of `previous` in the second callback event (the file's @@ -3263,7 +3269,7 @@ declare module "fs" { * Calling `fs.unwatchFile()` with a filename that is not being watched is a * no-op, not an error. * - * Using {@link watch} is more efficient than `fs.watchFile()` and`fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()`and `fs.unwatchFile()` when possible. + * Using {@link watch} is more efficient than `fs.watchFile()` and `fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()` and `fs.unwatchFile()` when possible. * @since v0.1.31 * @param listener Optional, a listener previously attached using `fs.watchFile()` */ @@ -3291,7 +3297,7 @@ declare module "fs" { * On most platforms, `'rename'` is emitted whenever a filename appears or * disappears in the directory. * - * The listener callback is attached to the `'change'` event fired by `fs.FSWatcher`, but it is not the same thing as the `'change'` value of`eventType`. + * The listener callback is attached to the `'change'` event fired by `fs.FSWatcher`, but it is not the same thing as the `'change'` value of `eventType`. * * If a `signal` is passed, aborting the corresponding AbortController will close * the returned `fs.FSWatcher`. @@ -3351,11 +3357,11 @@ declare module "fs" { * ``` * * **The parameters for this callback are not consistent with other Node.js** - * **callbacks.** Normally, the first parameter to a Node.js callback is an `err`parameter, optionally followed by other parameters. The `fs.exists()` callback + * **callbacks.** Normally, the first parameter to a Node.js callback is an `err` parameter, optionally followed by other parameters. The `fs.exists()` callback * has only one boolean parameter. This is one reason `fs.access()` is recommended * instead of `fs.exists()`. * - * Using `fs.exists()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. Doing + * Using `fs.exists()` to check for the existence of a file before calling `fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. Doing * so introduces a race condition, since other processes may change the file's * state between the two calls. Instead, user code should open/read/write the * file directly and handle the error raised if the file does not exist. @@ -3482,7 +3488,7 @@ declare module "fs" { * For detailed information, see the documentation of the asynchronous version of * this API: {@link exists}. * - * `fs.exists()` is deprecated, but `fs.existsSync()` is not. The `callback`parameter to `fs.exists()` accepts parameters that are inconsistent with other + * `fs.exists()` is deprecated, but `fs.existsSync()` is not. The `callback` parameter to `fs.exists()` accepts parameters that are inconsistent with other * Node.js callbacks. `fs.existsSync()` does not use a callback. * * ```js @@ -3611,13 +3617,13 @@ declare module "fs" { /** * Tests a user's permissions for the file or directory specified by `path`. * The `mode` argument is an optional integer that specifies the accessibility - * checks to be performed. `mode` should be either the value `fs.constants.F_OK`or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`,`fs.constants.W_OK`, and `fs.constants.X_OK` + * checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and `fs.constants.X_OK` * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for * possible values of `mode`. * * The final argument, `callback`, is a callback function that is invoked with * a possible error argument. If any of the accessibility checks fail, the error - * argument will be an `Error` object. The following examples check if`package.json` exists, and if it is readable or writable. + * argument will be an `Error` object. The following examples check if `package.json` exists, and if it is readable or writable. * * ```js * import { access, constants } from 'node:fs'; @@ -3645,7 +3651,7 @@ declare module "fs" { * }); * ``` * - * Do not use `fs.access()` to check for the accessibility of a file before calling`fs.open()`, `fs.readFile()`, or `fs.writeFile()`. Doing + * Do not use `fs.access()` to check for the accessibility of a file before calling `fs.open()`, `fs.readFile()`, or `fs.writeFile()`. Doing * so introduces a race condition, since other processes may change the file's * state between the two calls. Instead, user code should open/read/write the * file directly and handle the error raised if the file is not accessible. @@ -3785,7 +3791,7 @@ declare module "fs" { /** * Synchronously tests a user's permissions for the file or directory specified * by `path`. The `mode` argument is an optional integer that specifies the - * accessibility checks to be performed. `mode` should be either the value`fs.constants.F_OK` or a mask consisting of the bitwise OR of any of`fs.constants.R_OK`, `fs.constants.W_OK`, and + * accessibility checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and * `fs.constants.X_OK` (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for * possible values of `mode`. * @@ -3859,8 +3865,8 @@ declare module "fs" { * By default, the stream will emit a `'close'` event after it has been * destroyed. Set the `emitClose` option to `false` to change this behavior. * - * By providing the `fs` option, it is possible to override the corresponding `fs`implementations for `open`, `read`, and `close`. When providing the `fs` option, - * an override for `read` is required. If no `fd` is provided, an override for`open` is also required. If `autoClose` is `true`, an override for `close` is + * By providing the `fs` option, it is possible to override the corresponding `fs` implementations for `open`, `read`, and `close`. When providing the `fs` option, + * an override for `read` is required. If no `fd` is provided, an override for `open` is also required. If `autoClose` is `true`, an override for `close` is * also required. * * ```js @@ -3908,7 +3914,7 @@ declare module "fs" { * replacing it may require the `flags` option to be set to `r+` rather than the * default `w`. The `encoding` can be any one of those accepted by `Buffer`. * - * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'`the file descriptor will be closed automatically. If `autoClose` is false, + * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'` the file descriptor will be closed automatically. If `autoClose` is false, * then the file descriptor won't be closed, even if there's an error. * It is the application's responsibility to close it and make sure there's no * file descriptor leak. @@ -3916,12 +3922,12 @@ declare module "fs" { * By default, the stream will emit a `'close'` event after it has been * destroyed. Set the `emitClose` option to `false` to change this behavior. * - * By providing the `fs` option it is possible to override the corresponding `fs`implementations for `open`, `write`, `writev`, and `close`. Overriding `write()`without `writev()` can reduce + * By providing the `fs` option it is possible to override the corresponding `fs` implementations for `open`, `write`, `writev`, and `close`. Overriding `write()` without `writev()` can reduce * performance as some optimizations (`_writev()`) - * will be disabled. When providing the `fs` option, overrides for at least one of`write` and `writev` are required. If no `fd` option is supplied, an override - * for `open` is also required. If `autoClose` is `true`, an override for `close`is also required. + * will be disabled. When providing the `fs` option, overrides for at least one of `write` and `writev` are required. If no `fd` option is supplied, an override + * for `open` is also required. If `autoClose` is `true`, an override for `close` is also required. * - * Like `fs.ReadStream`, if `fd` is specified, `fs.WriteStream` will ignore the`path` argument and will use the specified file descriptor. This means that no`'open'` event will be + * Like `fs.ReadStream`, if `fd` is specified, `fs.WriteStream` will ignore the `path` argument and will use the specified file descriptor. This means that no `'open'` event will be * emitted. `fd` should be blocking; non-blocking `fd`s * should be passed to `net.Socket`. * @@ -4030,15 +4036,15 @@ declare module "fs" { */ export function copyFileSync(src: PathLike, dest: PathLike, mode?: number): void; /** - * Write an array of `ArrayBufferView`s to the file specified by `fd` using`writev()`. + * Write an array of `ArrayBufferView`s to the file specified by `fd` using `writev()`. * * `position` is the offset from the beginning of the file where this data * should be written. If `typeof position !== 'number'`, the data will be written * at the current position. * - * The callback will be given three arguments: `err`, `bytesWritten`, and`buffers`. `bytesWritten` is how many bytes were written from `buffers`. + * The callback will be given three arguments: `err`, `bytesWritten`, and `buffers`. `bytesWritten` is how many bytes were written from `buffers`. * - * If this method is `util.promisify()` ed, it returns a promise for an`Object` with `bytesWritten` and `buffers` properties. + * If this method is `util.promisify()` ed, it returns a promise for an `Object` with `bytesWritten` and `buffers` properties. * * It is unsafe to use `fs.writev()` multiple times on the same file without * waiting for the callback. For this scenario, use {@link createWriteStream}. @@ -4087,7 +4093,7 @@ declare module "fs" { * should be read. If `typeof position !== 'number'`, the data will be read * from the current position. * - * The callback will be given three arguments: `err`, `bytesRead`, and`buffers`. `bytesRead` is how many bytes were read from the file. + * The callback will be given three arguments: `err`, `bytesRead`, and `buffers`. `bytesRead` is how many bytes were read from the file. * * If this method is invoked as its `util.promisify()` ed version, it returns * a promise for an `Object` with `bytesRead` and `buffers` properties. diff --git a/node_modules/@types/node/fs/promises.d.ts b/node_modules/@types/node/fs/promises.d.ts index 88a9fc33e91344c14cf676cb9317eda1f1cb96f7..31990635396e635b66fa3863e0c03a5c304f412b 100644 --- a/node_modules/@types/node/fs/promises.d.ts +++ b/node_modules/@types/node/fs/promises.d.ts @@ -189,7 +189,7 @@ declare module "fs/promises" { * replacing it may require the `flags` `open` option to be set to `r+` rather than * the default `r`. The `encoding` can be any one of those accepted by `Buffer`. * - * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'`the file descriptor will be closed automatically. If `autoClose` is false, + * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'` the file descriptor will be closed automatically. If `autoClose` is false, * then the file descriptor won't be closed, even if there's an error. * It is the application's responsibility to close it and make sure there's no * file descriptor leak. @@ -268,7 +268,7 @@ declare module "fs/promises" { * * The `FileHandle` has to support reading. * - * If one or more `filehandle.read()` calls are made on a file handle and then a`filehandle.readFile()` call is made, the data will be read from the current + * If one or more `filehandle.read()` calls are made on a file handle and then a `filehandle.readFile()` call is made, the data will be read from the current * position till the end of the file. It doesn't always read from the beginning * of the file. * @since v10.0.0 @@ -375,7 +375,7 @@ declare module "fs/promises" { */ utimes(atime: TimeLike, mtime: TimeLike): Promise; /** - * Asynchronously writes data to a file, replacing the file if it already exists.`data` can be a string, a buffer, an + * Asynchronously writes data to a file, replacing the file if it already exists. `data` can be a string, a buffer, an * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. * The promise is fulfilled with no arguments upon success. @@ -485,7 +485,7 @@ declare module "fs/promises" { /** * Tests a user's permissions for the file or directory specified by `path`. * The `mode` argument is an optional integer that specifies the accessibility - * checks to be performed. `mode` should be either the value `fs.constants.F_OK`or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`,`fs.constants.W_OK`, and `fs.constants.X_OK` + * checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and `fs.constants.X_OK` * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for * possible values of `mode`. * @@ -570,7 +570,7 @@ declare module "fs/promises" { */ function rename(oldPath: PathLike, newPath: PathLike): Promise; /** - * Truncates (shortens or extends the length) of the content at `path` to `len`bytes. + * Truncates (shortens or extends the length) of the content at `path` to `len` bytes. * @since v10.0.0 * @param [len=0] * @return Fulfills with `undefined` upon success. @@ -580,7 +580,7 @@ declare module "fs/promises" { * Removes the directory identified by `path`. * * Using `fsPromises.rmdir()` on a file (not a directory) results in the - * promise being rejected with an `ENOENT` error on Windows and an `ENOTDIR`error on POSIX. + * promise being rejected with an `ENOENT` error on Windows and an `ENOTDIR` error on POSIX. * * To get a behavior similar to the `rm -rf` Unix command, use `fsPromises.rm()` with options `{ recursive: true, force: true }`. * @since v10.0.0 @@ -597,7 +597,7 @@ declare module "fs/promises" { * Asynchronously creates a directory. * * The optional `options` argument can be an integer specifying `mode` (permission - * and sticky bits), or an object with a `mode` property and a `recursive`property indicating whether parent directories should be created. Calling`fsPromises.mkdir()` when `path` is a directory + * and sticky bits), or an object with a `mode` property and a `recursive` property indicating whether parent directories should be created. Calling `fsPromises.mkdir()` when `path` is a directory * that exists results in a * rejection only when `recursive` is false. * @@ -747,7 +747,7 @@ declare module "fs/promises" { /** * Creates a symbolic link. * - * The `type` argument is only used on Windows platforms and can be one of `'dir'`,`'file'`, or `'junction'`. If the `type` argument is not a string, Node.js will + * The `type` argument is only used on Windows platforms and can be one of `'dir'`, `'file'`, or `'junction'`. If the `type` argument is not a string, Node.js will * autodetect `target` type and use `'file'` or `'dir'`. If the `target` does not * exist, `'file'` will be used. Windows junction points require the destination * path to be absolute. When using `'junction'`, the `target` argument will @@ -867,13 +867,13 @@ declare module "fs/promises" { * * * Values can be either numbers representing Unix epoch time, `Date`s, or a * numeric string like `'123456789.0'`. - * * If the value can not be converted to a number, or is `NaN`, `Infinity`, or`-Infinity`, an `Error` will be thrown. + * * If the value can not be converted to a number, or is `NaN`, `Infinity`, or `-Infinity`, an `Error` will be thrown. * @since v10.0.0 * @return Fulfills with `undefined` upon success. */ function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; /** - * Determines the actual location of `path` using the same semantics as the`fs.realpath.native()` function. + * Determines the actual location of `path` using the same semantics as the `fs.realpath.native()` function. * * Only paths that can be converted to UTF8 strings are supported. * @@ -927,7 +927,7 @@ declare module "fs/promises" { * ``` * * The `fsPromises.mkdtemp()` method will append the six randomly selected - * characters directly to the `prefix` string. For instance, given a directory`/tmp`, if the intention is to create a temporary directory _within_`/tmp`, the`prefix` must end with a trailing + * characters directly to the `prefix` string. For instance, given a directory `/tmp`, if the intention is to create a temporary directory _within_ `/tmp`, the `prefix` must end with a trailing * platform-specific path separator * (`require('node:path').sep`). * @since v10.0.0 @@ -947,7 +947,7 @@ declare module "fs/promises" { */ function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; /** - * Asynchronously writes data to a file, replacing the file if it already exists.`data` can be a string, a buffer, an + * Asynchronously writes data to a file, replacing the file if it already exists. `data` can be a string, a buffer, an * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. * @@ -1008,6 +1008,12 @@ declare module "fs/promises" { | (ObjectEncodingOptions & { mode?: Mode | undefined; flag?: OpenMode | undefined; + /** + * If all data is successfully written to the file, and `flush` + * is `true`, `filehandle.sync()` is used to flush the data. + * @default false + */ + flush?: boolean | undefined; } & Abortable) | BufferEncoding | null, diff --git a/node_modules/@types/node/globals.d.ts b/node_modules/@types/node/globals.d.ts index 5f250062b0295a95916ad2acd6ae8141ff2b5e71..a425b0732e1cfe1da9d95ab03cb2a12e1c2b86ea 100644 --- a/node_modules/@types/node/globals.d.ts +++ b/node_modules/@types/node/globals.d.ts @@ -96,6 +96,7 @@ declare global { new(): AbortSignal; abort(reason?: any): AbortSignal; timeout(milliseconds: number): AbortSignal; + any(signals: AbortSignal[]): AbortSignal; }; // #endregion borrowed diff --git a/node_modules/@types/node/http.d.ts b/node_modules/@types/node/http.d.ts index 710fe59423d657b7b7ea26113a8c41d97ec47134..a1018eee68e60f60b1f7e59e08dc690562f2b97c 100644 --- a/node_modules/@types/node/http.d.ts +++ b/node_modules/@types/node/http.d.ts @@ -26,8 +26,8 @@ * * See `message.headers` for details on how duplicate headers are handled. * - * The raw headers as they were received are retained in the `rawHeaders`property, which is an array of `[key, value, key2, value2, ...]`. For - * example, the previous message header object might have a `rawHeaders`list like the following: + * The raw headers as they were received are retained in the `rawHeaders` property, which is an array of `[key, value, key2, value2, ...]`. For + * example, the previous message header object might have a `rawHeaders` list like the following: * * ```js * [ 'ConTent-Length', '123456', @@ -37,7 +37,7 @@ * 'Host', 'example.com', * 'accepT', '*' ] * ``` - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/http.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/http.js) */ declare module "http" { import * as stream from "node:stream"; @@ -198,9 +198,11 @@ declare module "http" { _defaultAgent?: Agent | undefined; agent?: Agent | boolean | undefined; auth?: string | null | undefined; - // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L278 createConnection?: - | ((options: ClientRequestArgs, oncreate: (err: Error, socket: Socket) => void) => Socket) + | (( + options: ClientRequestArgs, + oncreate: (err: Error | null, socket: stream.Duplex) => void, + ) => stream.Duplex | null | undefined) | undefined; defaultPort?: number | string | undefined; family?: number | undefined; @@ -280,9 +282,8 @@ declare module "http" { */ insecureHTTPParser?: boolean | undefined; /** - * Optionally overrides the value of - * `--max-http-header-size` for requests received by this server, i.e. - * the maximum length of request headers in bytes. + * Optionally overrides the value of `--max-http-header-size` for requests received by + * this server, i.e. the maximum length of request headers in bytes. * @default 16384 * @since v13.3.0 */ @@ -386,7 +387,7 @@ declare module "http" { * The number of milliseconds of inactivity a server needs to wait for additional * incoming data, after it has finished writing the last response, before a socket * will be destroyed. If the server receives new data before the keep-alive - * timeout has fired, it will reset the regular inactivity timeout, i.e.,`server.timeout`. + * timeout has fired, it will reset the regular inactivity timeout, i.e., `server.timeout`. * * A value of `0` will disable the keep-alive timeout behavior on incoming * connections. @@ -573,7 +574,7 @@ declare module "http" { readonly socket: Socket | null; constructor(); /** - * Once a socket is associated with the message and is connected,`socket.setTimeout()` will be called with `msecs` as the first parameter. + * Once a socket is associated with the message and is connected, `socket.setTimeout()` will be called with `msecs` as the first parameter. * @since v0.9.12 * @param callback Optional function to be called when a timeout occurs. Same as binding to the `timeout` event. */ @@ -588,12 +589,12 @@ declare module "http" { */ setHeader(name: string, value: number | string | readonly string[]): this; /** - * Append a single header value for the header object. + * Append a single header value to the header object. * - * If the value is an array, this is equivalent of calling this method multiple + * If the value is an array, this is equivalent to calling this method multiple * times. * - * If there were no previous value for the header, this is equivalent of calling `outgoingMessage.setHeader(name, value)`. + * If there were no previous values for the header, this is equivalent to calling `outgoingMessage.setHeader(name, value)`. * * Depending of the value of `options.uniqueHeaders` when the client request or the * server were created, this will end up in the header being sent multiple times or @@ -689,7 +690,7 @@ declare module "http" { * packet. * * It is usually desired (it saves a TCP round-trip), but not when the first - * data is not sent until possibly much later. `outgoingMessage.flushHeaders()`bypasses the optimization and kickstarts the message. + * data is not sent until possibly much later. `outgoingMessage.flushHeaders()` bypasses the optimization and kickstarts the message. * @since v1.6.0 */ flushHeaders(): void; @@ -730,7 +731,7 @@ declare module "http" { */ statusMessage: string; /** - * If set to `true`, Node.js will check whether the `Content-Length`header value and the size of the body, in bytes, are equal. + * If set to `true`, Node.js will check whether the `Content-Length` header value and the size of the body, in bytes, are equal. * Mismatching the `Content-Length` header value will result * in an `Error` being thrown, identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`. * @since v18.10.0, v16.18.0 @@ -741,7 +742,7 @@ declare module "http" { detachSocket(socket: Socket): void; /** * Sends an HTTP/1.1 100 Continue message to the client, indicating that - * the request body should be sent. See the `'checkContinue'` event on`Server`. + * the request body should be sent. See the `'checkContinue'` event on `Server`. * @since v0.3.0 */ writeContinue(callback?: () => void): void; @@ -861,10 +862,10 @@ declare module "http" { /** * This object is created internally and returned from {@link request}. It * represents an _in-progress_ request whose header has already been queued. The - * header is still mutable using the `setHeader(name, value)`,`getHeader(name)`, `removeHeader(name)` API. The actual header will + * header is still mutable using the `setHeader(name, value)`, `getHeader(name)`, `removeHeader(name)` API. The actual header will * be sent along with the first data chunk or when calling `request.end()`. * - * To get the response, add a listener for `'response'` to the request object.`'response'` will be emitted from the request object when the response + * To get the response, add a listener for `'response'` to the request object. `'response'` will be emitted from the request object when the response * headers have been received. The `'response'` event is executed with one * argument which is an instance of {@link IncomingMessage}. * @@ -880,10 +881,10 @@ declare module "http" { * the data is read it will consume memory that can eventually lead to a * 'process out of memory' error. * - * For backward compatibility, `res` will only emit `'error'` if there is an`'error'` listener registered. + * For backward compatibility, `res` will only emit `'error'` if there is an `'error'` listener registered. * * Set `Content-Length` header to limit the response body size. - * If `response.strictContentLength` is set to `true`, mismatching the`Content-Length` header value will result in an `Error` being thrown, + * If `response.strictContentLength` is set to `true`, mismatching the `Content-Length` header value will result in an `Error` being thrown, * identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`. * * `Content-Length` value should be in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. @@ -894,7 +895,7 @@ declare module "http" { * The `request.aborted` property will be `true` if the request has * been aborted. * @since v0.11.14 - * @deprecated Since v17.0.0,v16.12.0 - Check `destroyed` instead. + * @deprecated Since v17.0.0, v16.12.0 - Check `destroyed` instead. */ aborted: boolean; /** @@ -1126,7 +1127,7 @@ declare module "http" { * access response * status, headers, and data. * - * Different from its `socket` value which is a subclass of `stream.Duplex`, the`IncomingMessage` itself extends `stream.Readable` and is created separately to + * Different from its `socket` value which is a subclass of `stream.Duplex`, the `IncomingMessage` itself extends `stream.Readable` and is created separately to * parse and emit the incoming HTTP headers and payload, as the underlying socket * may be reused multiple times in case of keep-alive. * @since v0.1.17 @@ -1145,7 +1146,7 @@ declare module "http" { * client response, the HTTP version of the connected-to server. * Probably either `'1.1'` or `'1.0'`. * - * Also `message.httpVersionMajor` is the first integer and`message.httpVersionMinor` is the second. + * Also `message.httpVersionMajor` is the first integer and `message.httpVersionMinor` is the second. * @since v0.1.1 */ httpVersion: string; @@ -1210,8 +1211,8 @@ declare module "http" { * Duplicates in raw headers are handled in the following ways, depending on the * header name: * - * * Duplicates of `age`, `authorization`, `content-length`, `content-type`,`etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`,`last-modified`, `location`, - * `max-forwards`, `proxy-authorization`, `referer`,`retry-after`, `server`, or `user-agent` are discarded. + * * Duplicates of `age`, `authorization`, `content-length`, `content-type`, `etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`, `last-modified`, `location`, + * `max-forwards`, `proxy-authorization`, `referer`, `retry-after`, `server`, or `user-agent` are discarded. * To allow duplicate values of the headers listed above to be joined, * use the option `joinDuplicateHeaders` in {@link request} and {@link createServer}. See RFC 9110 Section 5.3 for more * information. @@ -1305,29 +1306,32 @@ declare module "http" { * To parse the URL into its parts: * * ```js - * new URL(request.url, `http://${request.headers.host}`); + * new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`); * ``` * - * When `request.url` is `'/status?name=ryan'` and `request.headers.host` is`'localhost:3000'`: + * When `request.url` is `'/status?name=ryan'` and `process.env.HOST` is undefined: * * ```console * $ node - * > new URL(request.url, `http://${request.headers.host}`) + * > new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`); * URL { - * href: 'http://localhost:3000/status?name=ryan', - * origin: 'http://localhost:3000', + * href: 'http://localhost/status?name=ryan', + * origin: 'http://localhost', * protocol: 'http:', * username: '', * password: '', - * host: 'localhost:3000', + * host: 'localhost', * hostname: 'localhost', - * port: '3000', + * port: '', * pathname: '/status', * search: '?name=ryan', * searchParams: URLSearchParams { 'name' => 'ryan' }, * hash: '' * } * ``` + * + * Ensure that you set `process.env.HOST` to the server's host name, or consider replacing this part entirely. If using `req.headers.host`, ensure proper + * validation is used, as clients may specify a custom `Host` header. * @since v0.1.90 */ url?: string | undefined; @@ -1346,7 +1350,7 @@ declare module "http" { */ statusMessage?: string | undefined; /** - * Calls `destroy()` on the socket that received the `IncomingMessage`. If `error`is provided, an `'error'` event is emitted on the socket and `error` is passed + * Calls `destroy()` on the socket that received the `IncomingMessage`. If `error` is provided, an `'error'` event is emitted on the socket and `error` is passed * as an argument to any listeners on the event. * @since v0.3.0 */ @@ -1390,7 +1394,7 @@ declare module "http" { * for a given host and port, reusing a single socket connection for each * until the queue is empty, at which time the socket is either destroyed * or put into a pool where it is kept to be used again for requests to the - * same host and port. Whether it is destroyed or pooled depends on the`keepAlive` `option`. + * same host and port. Whether it is destroyed or pooled depends on the `keepAlive` `option`. * * Pooled connections have TCP Keep-Alive enabled for them, but servers may * still close idle connections, in which case they will be removed from the @@ -1421,7 +1425,7 @@ declare module "http" { * }); * ``` * - * An agent may also be used for an individual request. By providing`{agent: false}` as an option to the `http.get()` or `http.request()`functions, a one-time use `Agent` with default options + * An agent may also be used for an individual request. By providing `{agent: false}` as an option to the `http.get()` or `http.request()` functions, a one-time use `Agent` with default options * will be used * for the client connection. * @@ -1437,6 +1441,17 @@ declare module "http" { * // Do stuff with response * }); * ``` + * + * `options` in [`socket.connect()`](https://nodejs.org/docs/latest-v20.x/api/net.html#socketconnectoptions-connectlistener) are also supported. + * + * To configure any of them, a custom {@link Agent} instance must be created. + * + * ```js + * const http = require('node:http'); + * const keepAliveAgent = new http.Agent({ keepAlive: true }); + * options.agent = keepAliveAgent; + * http.request(options, onResponseCallback) + * ``` * @since v0.3.4 */ class Agent extends EventEmitter { @@ -1559,7 +1574,7 @@ declare module "http" { * `url` can be a string or a `URL` object. If `url` is a * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. * - * If both `url` and `options` are specified, the objects are merged, with the`options` properties taking precedence. + * If both `url` and `options` are specified, the objects are merged, with the `options` properties taking precedence. * * The optional `callback` parameter will be added as a one-time listener for * the `'response'` event. @@ -1659,7 +1674,7 @@ declare module "http" { * the following events will be emitted in the following order: * * * `'socket'` - * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'` * * `'close'` * * In the case of a premature connection close after the response is received, @@ -1670,15 +1685,15 @@ declare module "http" { * * `'data'` any number of times, on the `res` object * * (connection closed here) * * `'aborted'` on the `res` object - * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'` * * `'close'` + * * `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'` * * `'close'` on the `res` object * * If `req.destroy()` is called before a socket is assigned, the following * events will be emitted in the following order: * * * (`req.destroy()` called here) - * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'`, or the error with which `req.destroy()` was called + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called * * `'close'` * * If `req.destroy()` is called before the connection succeeds, the following @@ -1686,7 +1701,7 @@ declare module "http" { * * * `'socket'` * * (`req.destroy()` called here) - * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'`, or the error with which `req.destroy()` was called + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called * * `'close'` * * If `req.destroy()` is called after the response is received, the following @@ -1697,8 +1712,8 @@ declare module "http" { * * `'data'` any number of times, on the `res` object * * (`req.destroy()` called here) * * `'aborted'` on the `res` object - * * `'error'` on the `res` object with an error with message `'Error: aborted'`and code `'ECONNRESET'`, or the error with which `req.destroy()` was called * * `'close'` + * * `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called * * `'close'` on the `res` object * * If `req.abort()` is called before a socket is assigned, the following @@ -1714,7 +1729,7 @@ declare module "http" { * * `'socket'` * * (`req.abort()` called here) * * `'abort'` - * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'` * * `'close'` * * If `req.abort()` is called after the response is received, the following @@ -1726,16 +1741,16 @@ declare module "http" { * * (`req.abort()` called here) * * `'abort'` * * `'aborted'` on the `res` object - * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'`. * * `'close'` * * `'close'` on the `res` object * * Setting the `timeout` option or using the `setTimeout()` function will * not abort the request or do anything besides add a `'timeout'` event. * - * Passing an `AbortSignal` and then calling `abort()` on the corresponding`AbortController` will behave the same way as calling `.destroy()` on the + * Passing an `AbortSignal` and then calling `abort()` on the corresponding `AbortController` will behave the same way as calling `.destroy()` on the * request. Specifically, the `'error'` event will be emitted with an error with - * the message `'AbortError: The operation was aborted'`, the code `'ABORT_ERR'`and the `cause`, if one was provided. + * the message `'AbortError: The operation was aborted'`, the code `'ABORT_ERR'` and the `cause`, if one was provided. * @since v0.3.6 */ function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; @@ -1746,7 +1761,7 @@ declare module "http" { ): ClientRequest; /** * Since most requests are GET requests without bodies, Node.js provides this - * convenience method. The only difference between this method and {@link request} is that it sets the method to GET by default and calls `req.end()`automatically. The callback must take care to + * convenience method. The only difference between this method and {@link request} is that it sets the method to GET by default and calls `req.end()` automatically. The callback must take care to * consume the response * data for reasons stated in {@link ClientRequest} section. * @@ -1807,7 +1822,7 @@ declare module "http" { function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; /** - * Performs the low-level validations on the provided `name` that are done when`res.setHeader(name, value)` is called. + * Performs the low-level validations on the provided `name` that are done when `res.setHeader(name, value)` is called. * * Passing illegal value as `name` will result in a `TypeError` being thrown, * identified by `code: 'ERR_INVALID_HTTP_TOKEN'`. @@ -1833,7 +1848,7 @@ declare module "http" { */ function validateHeaderName(name: string): void; /** - * Performs the low-level validations on the provided `value` that are done when`res.setHeader(name, value)` is called. + * Performs the low-level validations on the provided `value` that are done when `res.setHeader(name, value)` is called. * * Passing illegal value as `value` will result in a `TypeError` being thrown. * @@ -1875,6 +1890,12 @@ declare module "http" { * @param [max=1000] */ function setMaxIdleHTTPParsers(max: number): void; + /** + * Global instance of `Agent` which is used as the default for all HTTP client + * requests. Diverges from a default `Agent` configuration by having `keepAlive` + * enabled and a `timeout` of 5 seconds. + * @since v0.5.9 + */ let globalAgent: Agent; /** * Read-only property specifying the maximum allowed size of HTTP headers in bytes. diff --git a/node_modules/@types/node/http2.d.ts b/node_modules/@types/node/http2.d.ts index c3b3e8ec4fe80a643325e3b37c287bcdb4c9e2f5..5212c9b6d8c65c2a9e0aa35051b15ac1c07854d3 100644 --- a/node_modules/@types/node/http2.d.ts +++ b/node_modules/@types/node/http2.d.ts @@ -6,7 +6,7 @@ * const http2 = require('node:http2'); * ``` * @since v8.4.0 - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/http2.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/http2.js) */ declare module "http2" { import EventEmitter = require("node:events"); @@ -96,7 +96,7 @@ declare module "http2" { */ readonly endAfterHeaders: boolean; /** - * The numeric stream identifier of this `Http2Stream` instance. Set to `undefined`if the stream identifier has not yet been assigned. + * The numeric stream identifier of this `Http2Stream` instance. Set to `undefined` if the stream identifier has not yet been assigned. * @since v8.4.0 */ readonly id?: number | undefined; @@ -109,7 +109,7 @@ declare module "http2" { /** * Set to the `RST_STREAM` `error code` reported when the `Http2Stream` is * destroyed after either receiving an `RST_STREAM` frame from the connected peer, - * calling `http2stream.close()`, or `http2stream.destroy()`. Will be`undefined` if the `Http2Stream` has not been closed. + * calling `http2stream.close()`, or `http2stream.destroy()`. Will be `undefined` if the `Http2Stream` has not been closed. * @since v8.4.0 */ readonly rstCode: number; @@ -136,7 +136,7 @@ declare module "http2" { */ readonly session: Http2Session | undefined; /** - * Provides miscellaneous information about the current state of the`Http2Stream`. + * Provides miscellaneous information about the current state of the `Http2Stream`. * * A current state of this `Http2Stream`. * @since v8.4.0 @@ -355,7 +355,7 @@ declare module "http2" { /** * Read-only property mapped to the `SETTINGS_ENABLE_PUSH` flag of the remote * client's most recent `SETTINGS` frame. Will be `true` if the remote peer - * accepts push streams, `false` otherwise. Settings are the same for every`Http2Stream` in the same `Http2Session`. + * accepts push streams, `false` otherwise. Settings are the same for every `Http2Stream` in the same `Http2Session`. * @since v8.4.0 */ readonly pushAllowed: boolean; @@ -365,7 +365,7 @@ declare module "http2" { */ additionalHeaders(headers: OutgoingHttpHeaders): void; /** - * Initiates a push stream. The callback is invoked with the new `Http2Stream`instance created for the push stream passed as the second argument, or an`Error` passed as the first argument. + * Initiates a push stream. The callback is invoked with the new `Http2Stream` instance created for the push stream passed as the second argument, or an `Error` passed as the first argument. * * ```js * const http2 = require('node:http2'); @@ -382,7 +382,7 @@ declare module "http2" { * ``` * * Setting the weight of a push stream is not allowed in the `HEADERS` frame. Pass - * a `weight` value to `http2stream.priority` with the `silent` option set to`true` to enable server-side bandwidth balancing between concurrent streams. + * a `weight` value to `http2stream.priority` with the `silent` option set to `true` to enable server-side bandwidth balancing between concurrent streams. * * Calling `http2stream.pushStream()` from within a pushed stream is not permitted * and will throw an error. @@ -413,7 +413,7 @@ declare module "http2" { * used to sent trailing header fields to the peer. * * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically - * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * close when the final `DATA` frame is transmitted. User code must call either `http2stream.sendTrailers()` or `http2stream.close()` to close the `Http2Stream`. * * ```js * const http2 = require('node:http2'); @@ -459,7 +459,7 @@ declare module "http2" { * * The optional `options.statCheck` function may be specified to give user code * an opportunity to set additional content headers based on the `fs.Stat` details - * of the given fd. If the `statCheck` function is provided, the`http2stream.respondWithFD()` method will perform an `fs.fstat()` call to + * of the given fd. If the `statCheck` function is provided, the `http2stream.respondWithFD()` method will perform an `fs.fstat()` call to * collect details on the provided file descriptor. * * The `offset` and `length` options may be used to limit the response to a @@ -478,7 +478,7 @@ declare module "http2" { * header fields to the peer. * * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically - * close when the final `DATA` frame is transmitted. User code _must_ call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * close when the final `DATA` frame is transmitted. User code _must_ call either `http2stream.sendTrailers()` or `http2stream.close()` to close the `Http2Stream`. * * ```js * const http2 = require('node:http2'); @@ -521,7 +521,7 @@ declare module "http2" { * an opportunity to set additional content headers based on the `fs.Stat` details * of the given file: * - * If an error occurs while attempting to read the file data, the `Http2Stream`will be closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR`code. If the `onError` callback is + * If an error occurs while attempting to read the file data, the `Http2Stream` will be closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR` code. If the `onError` callback is * defined, then it will be called. Otherwise * the stream will be destroyed. * @@ -559,7 +559,7 @@ declare module "http2" { * * The `options.statCheck` function may also be used to cancel the send operation * by returning `false`. For instance, a conditional request may check the stat - * results to determine if the file has been modified to return an appropriate`304` response: + * results to determine if the file has been modified to return an appropriate `304` response: * * ```js * const http2 = require('node:http2'); @@ -647,18 +647,18 @@ declare module "http2" { /** * Value will be `undefined` if the `Http2Session` is not yet connected to a * socket, `h2c` if the `Http2Session` is not connected to a `TLSSocket`, or - * will return the value of the connected `TLSSocket`'s own `alpnProtocol`property. + * will return the value of the connected `TLSSocket`'s own `alpnProtocol` property. * @since v9.4.0 */ readonly alpnProtocol?: string | undefined; /** - * Will be `true` if this `Http2Session` instance has been closed, otherwise`false`. + * Will be `true` if this `Http2Session` instance has been closed, otherwise `false`. * @since v9.4.0 */ readonly closed: boolean; /** * Will be `true` if this `Http2Session` instance is still connecting, will be set - * to `false` before emitting `connect` event and/or calling the `http2.connect`callback. + * to `false` before emitting `connect` event and/or calling the `http2.connect` callback. * @since v10.0.0 */ readonly connecting: boolean; @@ -677,7 +677,7 @@ declare module "http2" { */ readonly encrypted?: boolean | undefined; /** - * A prototype-less object describing the current local settings of this`Http2Session`. The local settings are local to _this_`Http2Session` instance. + * A prototype-less object describing the current local settings of this `Http2Session`. The local settings are local to _this_`Http2Session` instance. * @since v8.4.0 */ readonly localSettings: Settings; @@ -692,7 +692,7 @@ declare module "http2" { readonly originSet?: string[] | undefined; /** * Indicates whether the `Http2Session` is currently waiting for acknowledgment of - * a sent `SETTINGS` frame. Will be `true` after calling the`http2session.settings()` method. Will be `false` once all sent `SETTINGS`frames have been acknowledged. + * a sent `SETTINGS` frame. Will be `true` after calling the `http2session.settings()` method. Will be `false` once all sent `SETTINGS` frames have been acknowledged. * @since v8.4.0 */ readonly pendingSettingsAck: boolean; @@ -722,7 +722,7 @@ declare module "http2" { */ readonly state: SessionState; /** - * The `http2session.type` will be equal to`http2.constants.NGHTTP2_SESSION_SERVER` if this `Http2Session` instance is a + * The `http2session.type` will be equal to `http2.constants.NGHTTP2_SESSION_SERVER` if this `Http2Session` instance is a * server, and `http2.constants.NGHTTP2_SESSION_CLIENT` if the instance is a * client. * @since v8.4.0 @@ -739,11 +739,11 @@ declare module "http2" { */ close(callback?: () => void): void; /** - * Immediately terminates the `Http2Session` and the associated `net.Socket` or`tls.TLSSocket`. + * Immediately terminates the `Http2Session` and the associated `net.Socket` or `tls.TLSSocket`. * - * Once destroyed, the `Http2Session` will emit the `'close'` event. If `error`is not undefined, an `'error'` event will be emitted immediately before the`'close'` event. + * Once destroyed, the `Http2Session` will emit the `'close'` event. If `error` is not undefined, an `'error'` event will be emitted immediately before the `'close'` event. * - * If there are any remaining open `Http2Streams` associated with the`Http2Session`, those will also be destroyed. + * If there are any remaining open `Http2Streams` associated with the `Http2Session`, those will also be destroyed. * @since v8.4.0 * @param error An `Error` object if the `Http2Session` is being destroyed due to an error. * @param code The HTTP/2 error code to send in the final `GOAWAY` frame. If unspecified, and `error` is not undefined, the default is `INTERNAL_ERROR`, otherwise defaults to `NO_ERROR`. @@ -759,17 +759,17 @@ declare module "http2" { goaway(code?: number, lastStreamID?: number, opaqueData?: NodeJS.ArrayBufferView): void; /** * Sends a `PING` frame to the connected HTTP/2 peer. A `callback` function must - * be provided. The method will return `true` if the `PING` was sent, `false`otherwise. + * be provided. The method will return `true` if the `PING` was sent, `false` otherwise. * - * The maximum number of outstanding (unacknowledged) pings is determined by the`maxOutstandingPings` configuration option. The default maximum is 10. + * The maximum number of outstanding (unacknowledged) pings is determined by the `maxOutstandingPings` configuration option. The default maximum is 10. * - * If provided, the `payload` must be a `Buffer`, `TypedArray`, or `DataView`containing 8 bytes of data that will be transmitted with the `PING` and + * If provided, the `payload` must be a `Buffer`, `TypedArray`, or `DataView` containing 8 bytes of data that will be transmitted with the `PING` and * returned with the ping acknowledgment. * * The callback will be invoked with three arguments: an error argument that will * be `null` if the `PING` was successfully acknowledged, a `duration` argument * that reports the number of milliseconds elapsed since the ping was sent and the - * acknowledgment was received, and a `Buffer` containing the 8-byte `PING`payload. + * acknowledgment was received, and a `Buffer` containing the 8-byte `PING` payload. * * ```js * session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => { @@ -791,7 +791,7 @@ declare module "http2" { callback: (err: Error | null, duration: number, payload: Buffer) => void, ): boolean; /** - * Calls `ref()` on this `Http2Session`instance's underlying `net.Socket`. + * Calls `ref()` on this `Http2Session` instance's underlying `net.Socket`. * @since v9.4.0 */ ref(): void; @@ -822,9 +822,9 @@ declare module "http2" { */ setTimeout(msecs: number, callback?: () => void): void; /** - * Updates the current local settings for this `Http2Session` and sends a new`SETTINGS` frame to the connected HTTP/2 peer. + * Updates the current local settings for this `Http2Session` and sends a new `SETTINGS` frame to the connected HTTP/2 peer. * - * Once called, the `http2session.pendingSettingsAck` property will be `true`while the session is waiting for the remote peer to acknowledge the new + * Once called, the `http2session.pendingSettingsAck` property will be `true` while the session is waiting for the remote peer to acknowledge the new * settings. * * The new settings will not become effective until the `SETTINGS` acknowledgment @@ -917,15 +917,15 @@ declare module "http2" { } export interface ClientHttp2Session extends Http2Session { /** - * For HTTP/2 Client `Http2Session` instances only, the `http2session.request()`creates and returns an `Http2Stream` instance that can be used to send an + * For HTTP/2 Client `Http2Session` instances only, the `http2session.request()` creates and returns an `Http2Stream` instance that can be used to send an * HTTP/2 request to the connected server. * * When a `ClientHttp2Session` is first created, the socket may not yet be * connected. if `clienthttp2session.request()` is called during this time, the * actual request will be deferred until the socket is ready to go. - * If the `session` is closed before the actual request be executed, an`ERR_HTTP2_GOAWAY_SESSION` is thrown. + * If the `session` is closed before the actual request be executed, an `ERR_HTTP2_GOAWAY_SESSION` is thrown. * - * This method is only available if `http2session.type` is equal to`http2.constants.NGHTTP2_SESSION_CLIENT`. + * This method is only available if `http2session.type` is equal to `http2.constants.NGHTTP2_SESSION_CLIENT`. * * ```js * const http2 = require('node:http2'); @@ -1108,7 +1108,7 @@ declare module "http2" { * ``` * * When a string is passed as an `origin`, it will be parsed as a URL and the - * origin will be derived. For instance, the origin for the HTTP URL`'https://example.org/foo/bar'` is the ASCII string`'https://example.org'`. An error will be thrown if either the given + * origin will be derived. For instance, the origin for the HTTP URL `'https://example.org/foo/bar'` is the ASCII string` 'https://example.org'`. An error will be thrown if either the given * string * cannot be parsed as a URL or if a valid origin cannot be derived. * @@ -1198,6 +1198,7 @@ declare module "http2" { paddingStrategy?: number | undefined; peerMaxConcurrentStreams?: number | undefined; settings?: Settings | undefined; + remoteCustomSettings?: number[] | undefined; /** * Specifies a timeout in milliseconds that * a server should wait when an [`'unknownProtocol'`][] is emitted. If the @@ -1426,7 +1427,7 @@ declare module "http2" { readonly aborted: boolean; /** * The request authority pseudo header field. Because HTTP/2 allows requests - * to set either `:authority` or `host`, this value is derived from`req.headers[':authority']` if present. Otherwise, it is derived from`req.headers['host']`. + * to set either `:authority` or `host`, this value is derived from `req.headers[':authority']` if present. Otherwise, it is derived from `req.headers['host']`. * @since v8.4.0 */ readonly authority: string; @@ -1473,9 +1474,9 @@ declare module "http2" { readonly headers: IncomingHttpHeaders; /** * In case of server request, the HTTP version sent by the client. In the case of - * client response, the HTTP version of the connected-to server. Returns`'2.0'`. + * client response, the HTTP version of the connected-to server. Returns `'2.0'`. * - * Also `message.httpVersionMajor` is the first integer and`message.httpVersionMinor` is the second. + * Also `message.httpVersionMajor` is the first integer and `message.httpVersionMinor` is the second. * @since v8.4.0 */ readonly httpVersion: string; @@ -1530,11 +1531,11 @@ declare module "http2" { * `destroyed`, `readable`, and `writable` properties will be retrieved from and * set on `request.stream`. * - * `destroy`, `emit`, `end`, `on` and `once` methods will be called on`request.stream`. + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on `request.stream`. * * `setTimeout` method will be called on `request.stream.session`. * - * `pause`, `read`, `resume`, and `write` will throw an error with code`ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * `pause`, `read`, `resume`, and `write` will throw an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for * more information. * * All other interactions will be routed directly to the socket. With TLS support, @@ -1597,7 +1598,7 @@ declare module "http2" { * the response object. * * If no `'timeout'` listener is added to the request, the response, or - * the server, then `Http2Stream` s are destroyed when they time out. If a + * the server, then `Http2Stream`s are destroyed when they time out. If a * handler is assigned to the request, the response, or the server's `'timeout'`events, timed out sockets must be handled explicitly. * @since v8.4.0 */ @@ -1659,6 +1660,28 @@ declare module "http2" { * @deprecated Since v13.0.0 - Use `socket`. */ readonly connection: net.Socket | tls.TLSSocket; + /** + * Append a single header value to the header object. + * + * If the value is an array, this is equivalent to calling this method multiple times. + * + * If there were no previous values for the header, this is equivalent to calling {@link setHeader}. + * + * Attempting to set a header field name or value that contains invalid characters will result in a + * [TypeError](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-typeerror) being thrown. + * + * ```js + * // Returns headers including "set-cookie: a" and "set-cookie: b" + * const server = http2.createServer((req, res) => { + * res.setHeader('set-cookie', 'a'); + * res.appendHeader('set-cookie', 'b'); + * res.writeHead(200); + * res.end('ok'); + * }); + * ``` + * @since v20.12.0 + */ + appendHeader(name: string, value: string | string[]): void; /** * Boolean value that indicates whether the response has completed. Starts * as `false`. After `response.end()` executes, the value will be `true`. @@ -1683,11 +1706,11 @@ declare module "http2" { * `destroyed`, `readable`, and `writable` properties will be retrieved from and * set on `response.stream`. * - * `destroy`, `emit`, `end`, `on` and `once` methods will be called on`response.stream`. + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on `response.stream`. * * `setTimeout` method will be called on `response.stream.session`. * - * `pause`, `read`, `resume`, and `write` will throw an error with code`ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * `pause`, `read`, `resume`, and `write` will throw an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for * more information. * * All other interactions will be routed directly to the socket. @@ -1791,7 +1814,7 @@ declare module "http2" { * header names and the values are the respective header values. All header names * are lowercase. * - * The object returned by the `response.getHeaders()` method _does not_prototypically inherit from the JavaScript `Object`. This means that typical`Object` methods such as `obj.toString()`, + * The object returned by the `response.getHeaders()` method _does not_ prototypically inherit from the JavaScript `Object`. This means that typical `Object` methods such as `obj.toString()`, * `obj.hasOwnProperty()`, and others * are not defined and _will not work_. * @@ -1865,7 +1888,7 @@ declare module "http2" { * * If no `'timeout'` listener is added to the request, the response, or * the server, then `Http2Stream` s are destroyed when they time out. If a - * handler is assigned to the request, the response, or the server's `'timeout'`events, timed out sockets must be handled explicitly. + * handler is assigned to the request, the response, or the server's `'timeout'` events, timed out sockets must be handled explicitly. * @since v8.4.0 */ setTimeout(msecs: number, callback?: () => void): void; @@ -1901,7 +1924,7 @@ declare module "http2" { write(chunk: string | Uint8Array, encoding: BufferEncoding, callback?: (err: Error) => void): boolean; /** * Sends a status `100 Continue` to the client, indicating that the request body - * should be sent. See the `'checkContinue'` event on `Http2Server` and`Http2SecureServer`. + * should be sent. See the `'checkContinue'` event on `Http2Server` and `Http2SecureServer`. * @since v8.4.0 */ writeContinue(): void; @@ -1952,7 +1975,7 @@ declare module "http2" { * `Content-Length` is given in bytes not characters. The`Buffer.byteLength()` API may be used to determine the number of bytes in a * given encoding. On outbound messages, Node.js does not check if Content-Length * and the length of the body being transmitted are equal or not. However, when - * receiving messages, Node.js will automatically reject messages when the`Content-Length` does not match the actual payload size. + * receiving messages, Node.js will automatically reject messages when the `Content-Length` does not match the actual payload size. * * This method may be called at most one time on a message before `response.end()` is called. * @@ -2094,7 +2117,13 @@ declare module "http2" { const HTTP2_HEADER_ACCEPT_LANGUAGE: string; const HTTP2_HEADER_ACCEPT_RANGES: string; const HTTP2_HEADER_ACCEPT: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_METHODS: string; const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string; + const HTTP2_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_REQUEST_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_REQUEST_METHOD: string; const HTTP2_HEADER_AGE: string; const HTTP2_HEADER_ALLOW: string; const HTTP2_HEADER_AUTHORIZATION: string; @@ -2252,7 +2281,7 @@ declare module "http2" { */ export const sensitiveHeaders: symbol; /** - * Returns an object containing the default settings for an `Http2Session`instance. This method returns a new object instance every time it is called + * Returns an object containing the default settings for an `Http2Session` instance. This method returns a new object instance every time it is called * so instances returned may be safely modified for use. * @since v8.4.0 */ @@ -2281,7 +2310,7 @@ declare module "http2" { */ export function getUnpackedSettings(buf: Uint8Array): Settings; /** - * Returns a `net.Server` instance that creates and manages `Http2Session`instances. + * Returns a `net.Server` instance that creates and manages `Http2Session` instances. * * Since there are no browsers known that support [unencrypted HTTP/2](https://http2.github.io/faq/#does-http2-require-encryption), the use of {@link createSecureServer} is necessary when * communicating @@ -2317,7 +2346,7 @@ declare module "http2" { onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, ): Http2Server; /** - * Returns a `tls.Server` instance that creates and manages `Http2Session`instances. + * Returns a `tls.Server` instance that creates and manages `Http2Session` instances. * * ```js * const http2 = require('node:http2'); @@ -2376,6 +2405,13 @@ declare module "http2" { options?: ClientSessionOptions | SecureClientSessionOptions, listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, ): ClientHttp2Session; + /** + * Create an HTTP/2 server session from an existing socket. + * @param socket A Duplex Stream + * @param options Any `{@link createServer}` options can be provided. + * @since v20.12.0 + */ + export function performServerHandshake(socket: stream.Duplex, options?: ServerOptions): ServerHttp2Session; } declare module "node:http2" { export * from "http2"; diff --git a/node_modules/@types/node/https.d.ts b/node_modules/@types/node/https.d.ts index 36ae5b2f52eb9b643b32e59346df07b40758cd1f..76c6d73f915528903f04a8ad64f0a44b2001bf08 100644 --- a/node_modules/@types/node/https.d.ts +++ b/node_modules/@types/node/https.d.ts @@ -1,7 +1,7 @@ /** * HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a * separate module. - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/https.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/https.js) */ declare module "https" { import { Duplex } from "node:stream"; @@ -324,8 +324,8 @@ declare module "https" { /** * Makes a request to a secure web server. * - * The following additional `options` from `tls.connect()` are also accepted:`ca`, `cert`, `ciphers`, `clientCertEngine`, `crl`, `dhparam`, `ecdhCurve`,`honorCipherOrder`, `key`, `passphrase`, - * `pfx`, `rejectUnauthorized`,`secureOptions`, `secureProtocol`, `servername`, `sessionIdContext`,`highWaterMark`. + * The following additional `options` from `tls.connect()` are also accepted: `ca`, `cert`, `ciphers`, `clientCertEngine`, `crl`, `dhparam`, `ecdhCurve`, `honorCipherOrder`, `key`, `passphrase`, + * `pfx`, `rejectUnauthorized`, `secureOptions`, `secureProtocol`, `servername`, `sessionIdContext`, `highWaterMark`. * * `options` can be an object, a string, or a `URL` object. If `options` is a * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. diff --git a/node_modules/@types/node/index.d.ts b/node_modules/@types/node/index.d.ts index a596cad0219b59bd4a762eec62f85818b94409dd..f043abe376b36199d80332e06e3c00d96aeea5a7 100644 --- a/node_modules/@types/node/index.d.ts +++ b/node_modules/@types/node/index.d.ts @@ -66,6 +66,7 @@ /// /// /// +/// /// /// /// diff --git a/node_modules/@types/node/inspector.d.ts b/node_modules/@types/node/inspector.d.ts index 3927b81603d1ed6b7185b943e8cef65102f8dfca..012eb74f8f86487ab531eccb0422ea15ebf62ead 100644 --- a/node_modules/@types/node/inspector.d.ts +++ b/node_modules/@types/node/inspector.d.ts @@ -20,7 +20,7 @@ * ```js * import * as inspector from 'node:inspector'; * ``` - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/inspector.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/inspector.js) */ declare module 'inspector' { import EventEmitter = require('node:events'); @@ -2694,13 +2694,13 @@ declare module 'inspector' { prependOnceListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; } /** - * Activate inspector on host and port. Equivalent to`node --inspect=[[host:]port]`, but can be done programmatically after node has + * Activate inspector on host and port. Equivalent to `node --inspect=[[host:]port]`, but can be done programmatically after node has * started. * * If wait is `true`, will block until a client has connected to the inspect port * and flow control has been passed to the debugger client. * - * See the `security warning` regarding the `host`parameter usage. + * See the `security warning` regarding the `host` parameter usage. * @param [port='what was specified on the CLI'] Port to listen on for inspector connections. Optional. * @param [host='what was specified on the CLI'] Host to listen on for inspector connections. Optional. * @param [wait=false] Block until a client has connected. Optional. @@ -2731,7 +2731,7 @@ declare module 'inspector' { */ function url(): string | undefined; /** - * Blocks until a client (existing or connected later) has sent`Runtime.runIfWaitingForDebugger` command. + * Blocks until a client (existing or connected later) has sent `Runtime.runIfWaitingForDebugger` command. * * An exception will be thrown if there is no active inspector. * @since v12.7.0 @@ -2742,6 +2742,5 @@ declare module 'inspector' { * The inspector module provides an API for interacting with the V8 inspector. */ declare module 'node:inspector' { - import inspector = require('inspector'); - export = inspector; + export * from 'inspector'; } diff --git a/node_modules/@types/node/net.d.ts b/node_modules/@types/node/net.d.ts index 70789e1ba1c71d917006acfa4cca7769ea1c705e..238c6a63a4d51d4a4a03cce94640d86379a4d11f 100644 --- a/node_modules/@types/node/net.d.ts +++ b/node_modules/@types/node/net.d.ts @@ -10,7 +10,7 @@ * ```js * const net = require('node:net'); * ``` - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/net.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/net.js) */ declare module "net" { import * as stream from "node:stream"; @@ -18,8 +18,8 @@ declare module "net" { import * as dns from "node:dns"; type LookupFunction = ( hostname: string, - options: dns.LookupAllOptions, - callback: (err: NodeJS.ErrnoException | null, addresses: dns.LookupAddress[]) => void, + options: dns.LookupOptions, + callback: (err: NodeJS.ErrnoException | null, address: string | dns.LookupAddress[], family?: number) => void, ) => void; interface AddressInfo { address: string; @@ -278,7 +278,7 @@ declare module "net" { */ readonly bytesWritten: number; /** - * If `true`,`socket.connect(options[, connectListener])` was + * If `true`, `socket.connect(options[, connectListener])` was * called and has not yet finished. It will stay `true` until the socket becomes * connected, then it is set to `false` and the `'connect'` event is emitted. Note * that the `socket.connect(options[, connectListener])` callback is a listener for the `'connect'` event. @@ -363,17 +363,29 @@ declare module "net" { * events.EventEmitter * 1. close * 2. connect - * 3. data - * 4. drain - * 5. end - * 6. error - * 7. lookup - * 8. ready - * 9. timeout + * 3. connectionAttempt + * 4. connectionAttemptFailed + * 5. connectionAttemptTimeout + * 6. data + * 7. drain + * 8. end + * 9. error + * 10. lookup + * 11. ready + * 12. timeout */ addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "close", listener: (hadError: boolean) => void): this; addListener(event: "connect", listener: () => void): this; + addListener(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + addListener( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number) => void, + ): this; + addListener( + event: "connectionAttemptTimeout", + listener: (ip: string, port: number, family: number) => void, + ): this; addListener(event: "data", listener: (data: Buffer) => void): this; addListener(event: "drain", listener: () => void): this; addListener(event: "end", listener: () => void): this; @@ -387,6 +399,9 @@ declare module "net" { emit(event: string | symbol, ...args: any[]): boolean; emit(event: "close", hadError: boolean): boolean; emit(event: "connect"): boolean; + emit(event: "connectionAttempt", ip: string, port: number, family: number): boolean; + emit(event: "connectionAttemptFailed", ip: string, port: number, family: number): boolean; + emit(event: "connectionAttemptTimeout", ip: string, port: number, family: number): boolean; emit(event: "data", data: Buffer): boolean; emit(event: "drain"): boolean; emit(event: "end"): boolean; @@ -397,6 +412,9 @@ declare module "net" { on(event: string, listener: (...args: any[]) => void): this; on(event: "close", listener: (hadError: boolean) => void): this; on(event: "connect", listener: () => void): this; + on(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + on(event: "connectionAttemptFailed", listener: (ip: string, port: number, family: number) => void): this; + on(event: "connectionAttemptTimeout", listener: (ip: string, port: number, family: number) => void): this; on(event: "data", listener: (data: Buffer) => void): this; on(event: "drain", listener: () => void): this; on(event: "end", listener: () => void): this; @@ -409,6 +427,9 @@ declare module "net" { on(event: "timeout", listener: () => void): this; once(event: string, listener: (...args: any[]) => void): this; once(event: "close", listener: (hadError: boolean) => void): this; + once(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + once(event: "connectionAttemptFailed", listener: (ip: string, port: number, family: number) => void): this; + once(event: "connectionAttemptTimeout", listener: (ip: string, port: number, family: number) => void): this; once(event: "connect", listener: () => void): this; once(event: "data", listener: (data: Buffer) => void): this; once(event: "drain", listener: () => void): this; @@ -423,6 +444,15 @@ declare module "net" { prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "close", listener: (hadError: boolean) => void): this; prependListener(event: "connect", listener: () => void): this; + prependListener(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + prependListener( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependListener( + event: "connectionAttemptTimeout", + listener: (ip: string, port: number, family: number) => void, + ): this; prependListener(event: "data", listener: (data: Buffer) => void): this; prependListener(event: "drain", listener: () => void): this; prependListener(event: "end", listener: () => void): this; @@ -436,6 +466,18 @@ declare module "net" { prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "close", listener: (hadError: boolean) => void): this; prependOnceListener(event: "connect", listener: () => void): this; + prependOnceListener( + event: "connectionAttempt", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependOnceListener( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependOnceListener( + event: "connectionAttemptTimeout", + listener: (ip: string, port: number, family: number) => void, + ): this; prependOnceListener(event: "data", listener: (data: Buffer) => void): this; prependOnceListener(event: "drain", listener: () => void): this; prependOnceListener(event: "end", listener: () => void): this; @@ -522,7 +564,7 @@ declare module "net" { * * All `listen()` methods can take a `backlog` parameter to specify the maximum * length of the queue of pending connections. The actual length will be determined - * by the OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn`on Linux. The default value of this parameter is 511 (not 512). + * by the OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn` on Linux. The default value of this parameter is 511 (not 512). * * All {@link Socket} are set to `SO_REUSEADDR` (see [`socket(7)`](https://man7.org/linux/man-pages/man7/socket.7.html) for * details). @@ -628,7 +670,7 @@ declare module "net" { * Indicates whether or not the server is listening for connections. * @since v5.7.0 */ - listening: boolean; + readonly listening: boolean; /** * events.EventEmitter * 1. close @@ -736,6 +778,11 @@ declare module "net" { */ check(address: SocketAddress): boolean; check(address: string, type?: IPVersion): boolean; + /** + * The list of rules added to the blocklist. + * @since v15.0.0, v14.18.0 + */ + rules: readonly string[]; } interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts { timeout?: number | undefined; @@ -852,13 +899,16 @@ declare module "net" { function setDefaultAutoSelectFamily(value: boolean): void; /** * Gets the current default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`. - * The initial default value is `250`. - * @since v19.8.0 + * The initial default value is `250` or the value specified via the command line option `--network-family-autoselection-attempt-timeout`. + * @returns The current default value of the `autoSelectFamilyAttemptTimeout` option. + * @since v19.8.0, v18.8.0 */ function getDefaultAutoSelectFamilyAttemptTimeout(): number; /** * Sets the default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`. - * @since v19.8.0 + * @param value The new default value, which must be a positive number. If the number is less than `10`, the value `10` is used instead. The initial default value is `250` or the value specified via the command line + * option `--network-family-autoselection-attempt-timeout`. + * @since v19.8.0, v18.8.0 */ function setDefaultAutoSelectFamilyAttemptTimeout(value: number): void; /** diff --git a/node_modules/@types/node/os.d.ts b/node_modules/@types/node/os.d.ts index 39a33f7fd5b960970c3eb3946ceea8766eb1989d..0b9a68cf5ece32400803dfa376f5dc0966b092d1 100644 --- a/node_modules/@types/node/os.d.ts +++ b/node_modules/@types/node/os.d.ts @@ -5,17 +5,22 @@ * ```js * const os = require('node:os'); * ``` - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/os.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/os.js) */ declare module "os" { interface CpuInfo { model: string; speed: number; times: { + /** The number of milliseconds the CPU has spent in user mode. */ user: number; + /** The number of milliseconds the CPU has spent in nice mode. */ nice: number; + /** The number of milliseconds the CPU has spent in sys mode. */ sys: number; + /** The number of milliseconds the CPU has spent in idle mode. */ idle: number; + /** The number of milliseconds the CPU has spent in irq mode. */ irq: number; }; } @@ -75,7 +80,7 @@ declare module "os" { function totalmem(): number; /** * Returns an array of objects containing information about each logical CPU core. - * The array will be empty if no CPU information is available, such as if the`/proc` file system is unavailable. + * The array will be empty if no CPU information is available, such as if the `/proc` file system is unavailable. * * The properties included on each object include: * @@ -229,14 +234,14 @@ declare module "os" { /** * Returns information about the currently effective user. On POSIX platforms, * this is typically a subset of the password file. The returned object includes - * the `username`, `uid`, `gid`, `shell`, and `homedir`. On Windows, the `uid` and`gid` fields are `-1`, and `shell` is `null`. + * the `username`, `uid`, `gid`, `shell`, and `homedir`. On Windows, the `uid` and `gid` fields are `-1`, and `shell` is `null`. * * The value of `homedir` returned by `os.userInfo()` is provided by the operating * system. This differs from the result of `os.homedir()`, which queries * environment variables for the home directory before falling back to the * operating system response. * - * Throws a `SystemError` if a user has no `username` or `homedir`. + * Throws a [`SystemError`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-systemerror) if a user has no `username` or `homedir`. * @since v6.0.0 */ function userInfo(options: { encoding: "buffer" }): UserInfo; @@ -387,6 +392,13 @@ declare module "os" { const WSA_E_CANCELLED: number; const WSAEREFUSED: number; } + namespace dlopen { + const RTLD_LAZY: number; + const RTLD_NOW: number; + const RTLD_GLOBAL: number; + const RTLD_LOCAL: number; + const RTLD_DEEPBIND: number; + } namespace priority { const PRIORITY_LOW: number; const PRIORITY_BELOW_NORMAL: number; @@ -397,13 +409,18 @@ declare module "os" { } } const devNull: string; + /** + * The operating system-specific end-of-line marker. + * * `\n` on POSIX + * * `\r\n` on Windows + */ const EOL: string; /** * Returns the operating system CPU architecture for which the Node.js binary was - * compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`,`'mips'`, `'mipsel'`, `'ppc'`, `'ppc64'`, `'riscv64'`, `'s390'`, `'s390x'`, + * compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`, `'mips'`, `'mipsel'`, `'ppc'`, `'ppc64'`, `'riscv64'`, `'s390'`, `'s390x'`, * and `'x64'`. * - * The return value is equivalent to `process.arch`. + * The return value is equivalent to [process.arch](https://nodejs.org/docs/latest-v20.x/api/process.html#processarch). * @since v0.5.0 */ function arch(): string; @@ -418,7 +435,7 @@ declare module "os" { /** * Returns a string identifying the operating system platform for which * the Node.js binary was compiled. The value is set at compile time. - * Possible values are `'aix'`, `'darwin'`, `'freebsd'`,`'linux'`,`'openbsd'`, `'sunos'`, and `'win32'`. + * Possible values are `'aix'`, `'darwin'`, `'freebsd'`, `'linux'`, `'openbsd'`, `'sunos'`, and `'win32'`. * * The return value is equivalent to `process.platform`. * @@ -428,7 +445,7 @@ declare module "os" { */ function platform(): NodeJS.Platform; /** - * Returns the machine type as a string, such as `arm`, `arm64`, `aarch64`,`mips`, `mips64`, `ppc64`, `ppc64le`, `s390`, `s390x`, `i386`, `i686`, `x86_64`. + * Returns the machine type as a string, such as `arm`, `arm64`, `aarch64`, `mips`, `mips64`, `ppc64`, `ppc64le`, `s390`, `s390x`, `i386`, `i686`, `x86_64`. * * On POSIX systems, the machine type is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not * available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. @@ -457,15 +474,15 @@ declare module "os" { */ function getPriority(pid?: number): number; /** - * Attempts to set the scheduling priority for the process specified by `pid`. If`pid` is not provided or is `0`, the process ID of the current process is used. + * Attempts to set the scheduling priority for the process specified by `pid`. If `pid` is not provided or is `0`, the process ID of the current process is used. * - * The `priority` input must be an integer between `-20` (high priority) and `19`(low priority). Due to differences between Unix priority levels and Windows - * priority classes, `priority` is mapped to one of six priority constants in`os.constants.priority`. When retrieving a process priority level, this range + * The `priority` input must be an integer between `-20` (high priority) and `19` (low priority). Due to differences between Unix priority levels and Windows + * priority classes, `priority` is mapped to one of six priority constants in `os.constants.priority`. When retrieving a process priority level, this range * mapping may cause the return value to be slightly different on Windows. To avoid * confusion, set `priority` to one of the priority constants. * * On Windows, setting priority to `PRIORITY_HIGHEST` requires elevated user - * privileges. Otherwise the set priority will be silently reduced to`PRIORITY_HIGH`. + * privileges. Otherwise the set priority will be silently reduced to `PRIORITY_HIGH`. * @since v10.10.0 * @param [pid=0] The process ID to set scheduling priority for. * @param priority The scheduling priority to assign to the process. diff --git a/node_modules/@types/node/package.json b/node_modules/@types/node/package.json index 21ee85071511586141e3850730b86e6cd35e50b6..6537cb3ca1a3a97502ae84a675f6914c5dbdce1c 100644 --- a/node_modules/@types/node/package.json +++ b/node_modules/@types/node/package.json @@ -1,230 +1,208 @@ { + "_from": "@types/node@>=10.0.0", + "_id": "@types/node@20.14.8", + "_inBundle": false, + "_integrity": "sha512-DO+2/jZinXfROG7j7WKFn/3C6nFwxy2lLpgLjEXJz+0XKphZlTLJ14mo8Vfg8X5BWN6XjyESXq+LcYdT7tR3bA==", + "_location": "/@types/node", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@types/node@>=10.0.0", "name": "@types/node", - "version": "20.11.6", - "description": "TypeScript definitions for node", - "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node", - "license": "MIT", - "contributors": [ - { - "name": "Microsoft TypeScript", - "githubUsername": "Microsoft", - "url": "https://github.com/Microsoft" - }, - { - "name": "Alberto Schiabel", - "githubUsername": "jkomyno", - "url": "https://github.com/jkomyno" - }, - { - "name": "Alvis HT Tang", - "githubUsername": "alvis", - "url": "https://github.com/alvis" - }, - { - "name": "Andrew Makarov", - "githubUsername": "r3nya", - "url": "https://github.com/r3nya" - }, - { - "name": "Benjamin Toueg", - "githubUsername": "btoueg", - "url": "https://github.com/btoueg" - }, - { - "name": "Chigozirim C.", - "githubUsername": "smac89", - "url": "https://github.com/smac89" - }, - { - "name": "David Junger", - "githubUsername": "touffy", - "url": "https://github.com/touffy" - }, - { - "name": "Deividas Bakanas", - "githubUsername": "DeividasBakanas", - "url": "https://github.com/DeividasBakanas" - }, - { - "name": "Eugene Y. Q. Shen", - "githubUsername": "eyqs", - "url": "https://github.com/eyqs" - }, - { - "name": "Hannes Magnusson", - "githubUsername": "Hannes-Magnusson-CK", - "url": "https://github.com/Hannes-Magnusson-CK" - }, - { - "name": "Huw", - "githubUsername": "hoo29", - "url": "https://github.com/hoo29" - }, - { - "name": "Kelvin Jin", - "githubUsername": "kjin", - "url": "https://github.com/kjin" - }, - { - "name": "Klaus Meinhardt", - "githubUsername": "ajafff", - "url": "https://github.com/ajafff" - }, - { - "name": "Lishude", - "githubUsername": "islishude", - "url": "https://github.com/islishude" - }, - { - "name": "Mariusz Wiktorczyk", - "githubUsername": "mwiktorczyk", - "url": "https://github.com/mwiktorczyk" - }, - { - "name": "Mohsen Azimi", - "githubUsername": "mohsen1", - "url": "https://github.com/mohsen1" - }, - { - "name": "Nicolas Even", - "githubUsername": "n-e", - "url": "https://github.com/n-e" - }, - { - "name": "Nikita Galkin", - "githubUsername": "galkin", - "url": "https://github.com/galkin" - }, - { - "name": "Parambir Singh", - "githubUsername": "parambirs", - "url": "https://github.com/parambirs" - }, - { - "name": "Sebastian Silbermann", - "githubUsername": "eps1lon", - "url": "https://github.com/eps1lon" - }, - { - "name": "Thomas den Hollander", - "githubUsername": "ThomasdenH", - "url": "https://github.com/ThomasdenH" - }, - { - "name": "Wilco Bakker", - "githubUsername": "WilcoBakker", - "url": "https://github.com/WilcoBakker" - }, - { - "name": "wwwy3y3", - "githubUsername": "wwwy3y3", - "url": "https://github.com/wwwy3y3" - }, - { - "name": "Samuel Ainsworth", - "githubUsername": "samuela", - "url": "https://github.com/samuela" - }, - { - "name": "Kyle Uehlein", - "githubUsername": "kuehlein", - "url": "https://github.com/kuehlein" - }, - { - "name": "Thanik Bhongbhibhat", - "githubUsername": "bhongy", - "url": "https://github.com/bhongy" - }, - { - "name": "Marcin Kopacz", - "githubUsername": "chyzwar", - "url": "https://github.com/chyzwar" - }, - { - "name": "Trivikram Kamat", - "githubUsername": "trivikr", - "url": "https://github.com/trivikr" - }, - { - "name": "Junxiao Shi", - "githubUsername": "yoursunny", - "url": "https://github.com/yoursunny" - }, - { - "name": "Ilia Baryshnikov", - "githubUsername": "qwelias", - "url": "https://github.com/qwelias" - }, - { - "name": "ExE Boss", - "githubUsername": "ExE-Boss", - "url": "https://github.com/ExE-Boss" - }, - { - "name": "Piotr Błażejewicz", - "githubUsername": "peterblazejewicz", - "url": "https://github.com/peterblazejewicz" - }, - { - "name": "Anna Henningsen", - "githubUsername": "addaleax", - "url": "https://github.com/addaleax" - }, - { - "name": "Victor Perin", - "githubUsername": "victorperin", - "url": "https://github.com/victorperin" - }, - { - "name": "Yongsheng Zhang", - "githubUsername": "ZYSzys", - "url": "https://github.com/ZYSzys" - }, - { - "name": "NodeJS Contributors", - "githubUsername": "NodeJS", - "url": "https://github.com/NodeJS" - }, - { - "name": "Linus Unnebäck", - "githubUsername": "LinusU", - "url": "https://github.com/LinusU" - }, - { - "name": "wafuwafu13", - "githubUsername": "wafuwafu13", - "url": "https://github.com/wafuwafu13" - }, - { - "name": "Matteo Collina", - "githubUsername": "mcollina", - "url": "https://github.com/mcollina" - }, - { - "name": "Dmitry Semigradsky", - "githubUsername": "Semigradsky", - "url": "https://github.com/Semigradsky" - } - ], - "main": "", - "types": "index.d.ts", - "typesVersions": { - "<=4.8": { - "*": [ - "ts4.8/*" - ] - } - }, - "repository": { - "type": "git", - "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", - "directory": "types/node" - }, - "scripts": {}, - "dependencies": { - "undici-types": "~5.26.4" - }, - "typesPublisherContentHash": "4672df994f41fe8261bb8674f0ae453a191329e23938a5bf005572caa3a878fc", - "typeScriptVersion": "4.6", - "nonNpm": true -} \ No newline at end of file + "escapedName": "@types%2fnode", + "scope": "@types", + "rawSpec": ">=10.0.0", + "saveSpec": null, + "fetchSpec": ">=10.0.0" + }, + "_requiredBy": [ + "/@types/cors", + "/engine.io" + ], + "_resolved": "https://registry.npmjs.org/@types/node/-/node-20.14.8.tgz", + "_shasum": "45c26a2a5de26c3534a9504530ddb3b27ce031ac", + "_spec": "@types/node@>=10.0.0", + "_where": "/Users/sylvainfiloni/Documents/HuggingFace_Projects/live-vision/node_modules/engine.io", + "bugs": { + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Microsoft TypeScript", + "url": "https://github.com/Microsoft" + }, + { + "name": "Alberto Schiabel", + "url": "https://github.com/jkomyno" + }, + { + "name": "Alvis HT Tang", + "url": "https://github.com/alvis" + }, + { + "name": "Andrew Makarov", + "url": "https://github.com/r3nya" + }, + { + "name": "Benjamin Toueg", + "url": "https://github.com/btoueg" + }, + { + "name": "Chigozirim C.", + "url": "https://github.com/smac89" + }, + { + "name": "David Junger", + "url": "https://github.com/touffy" + }, + { + "name": "Deividas Bakanas", + "url": "https://github.com/DeividasBakanas" + }, + { + "name": "Eugene Y. Q. Shen", + "url": "https://github.com/eyqs" + }, + { + "name": "Hannes Magnusson", + "url": "https://github.com/Hannes-Magnusson-CK" + }, + { + "name": "Huw", + "url": "https://github.com/hoo29" + }, + { + "name": "Kelvin Jin", + "url": "https://github.com/kjin" + }, + { + "name": "Klaus Meinhardt", + "url": "https://github.com/ajafff" + }, + { + "name": "Lishude", + "url": "https://github.com/islishude" + }, + { + "name": "Mariusz Wiktorczyk", + "url": "https://github.com/mwiktorczyk" + }, + { + "name": "Mohsen Azimi", + "url": "https://github.com/mohsen1" + }, + { + "name": "Nikita Galkin", + "url": "https://github.com/galkin" + }, + { + "name": "Parambir Singh", + "url": "https://github.com/parambirs" + }, + { + "name": "Sebastian Silbermann", + "url": "https://github.com/eps1lon" + }, + { + "name": "Thomas den Hollander", + "url": "https://github.com/ThomasdenH" + }, + { + "name": "Wilco Bakker", + "url": "https://github.com/WilcoBakker" + }, + { + "name": "wwwy3y3", + "url": "https://github.com/wwwy3y3" + }, + { + "name": "Samuel Ainsworth", + "url": "https://github.com/samuela" + }, + { + "name": "Kyle Uehlein", + "url": "https://github.com/kuehlein" + }, + { + "name": "Thanik Bhongbhibhat", + "url": "https://github.com/bhongy" + }, + { + "name": "Marcin Kopacz", + "url": "https://github.com/chyzwar" + }, + { + "name": "Trivikram Kamat", + "url": "https://github.com/trivikr" + }, + { + "name": "Junxiao Shi", + "url": "https://github.com/yoursunny" + }, + { + "name": "Ilia Baryshnikov", + "url": "https://github.com/qwelias" + }, + { + "name": "ExE Boss", + "url": "https://github.com/ExE-Boss" + }, + { + "name": "Piotr Błażejewicz", + "url": "https://github.com/peterblazejewicz" + }, + { + "name": "Anna Henningsen", + "url": "https://github.com/addaleax" + }, + { + "name": "Victor Perin", + "url": "https://github.com/victorperin" + }, + { + "name": "Yongsheng Zhang", + "url": "https://github.com/ZYSzys" + }, + { + "name": "NodeJS Contributors", + "url": "https://github.com/NodeJS" + }, + { + "name": "Linus Unnebäck", + "url": "https://github.com/LinusU" + }, + { + "name": "wafuwafu13", + "url": "https://github.com/wafuwafu13" + }, + { + "name": "Matteo Collina", + "url": "https://github.com/mcollina" + }, + { + "name": "Dmitry Semigradsky", + "url": "https://github.com/Semigradsky" + } + ], + "dependencies": { + "undici-types": "~5.26.4" + }, + "deprecated": false, + "description": "TypeScript definitions for node", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node", + "license": "MIT", + "main": "", + "name": "@types/node", + "repository": { + "type": "git", + "url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/node" + }, + "scripts": {}, + "typeScriptVersion": "4.7", + "types": "index.d.ts", + "typesPublisherContentHash": "7f1c7cbbd4b01202220b325496b6a96822975f892d3eb44558ea7ffcf74ae32c", + "version": "20.14.8" +} diff --git a/node_modules/@types/node/path.d.ts b/node_modules/@types/node/path.d.ts index 6f07681ac6460e05a2b23515d13d45e1a0714b6c..0c6b46dd66d47ed96f48e2c139c1562c279d41ea 100644 --- a/node_modules/@types/node/path.d.ts +++ b/node_modules/@types/node/path.d.ts @@ -13,7 +13,7 @@ declare module "path/win32" { * ```js * const path = require('node:path'); * ``` - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/path.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/path.js) */ declare module "path" { namespace path { diff --git a/node_modules/@types/node/perf_hooks.d.ts b/node_modules/@types/node/perf_hooks.d.ts index c0ce852a97b28560a5f8e4643a793b5c904deb56..5ce7fca21d8ff561220770263d227a8349973ed1 100644 --- a/node_modules/@types/node/perf_hooks.d.ts +++ b/node_modules/@types/node/perf_hooks.d.ts @@ -27,14 +27,14 @@ * performance.measure('A to B', 'A', 'B'); * }); * ``` - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/perf_hooks.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/perf_hooks.js) */ declare module "perf_hooks" { import { AsyncResource } from "node:async_hooks"; type EntryType = "node" | "mark" | "measure" | "gc" | "function" | "http2" | "http" | "dns" | "net"; interface NodeGCPerformanceDetail { /** - * When `performanceEntry.entryType` is equal to 'gc', `the performance.kind` property identifies + * When `performanceEntry.entryType` is equal to 'gc', the `performance.kind` property identifies * the type of garbage collection operation that occurred. * See perf_hooks.constants for valid values. */ @@ -150,6 +150,11 @@ declare module "perf_hooks" { * @since v8.5.0 */ readonly loopStart: number; + /** + * The high resolution millisecond timestamp at which the Node.js process was initialized. + * @since v8.5.0 + */ + readonly nodeStart: number; /** * The high resolution millisecond timestamp at which the V8 platform was * initialized. @@ -163,12 +168,12 @@ declare module "perf_hooks" { utilization: number; } /** - * @param util1 The result of a previous call to eventLoopUtilization() - * @param util2 The result of a previous call to eventLoopUtilization() prior to util1 + * @param utilization1 The result of a previous call to `eventLoopUtilization()`. + * @param utilization2 The result of a previous call to `eventLoopUtilization()` prior to `utilization1`. */ type EventLoopUtilityFunction = ( - util1?: EventLoopUtilization, - util2?: EventLoopUtilization, + utilization1?: EventLoopUtilization, + utilization2?: EventLoopUtilization, ) => EventLoopUtilization; interface MarkOptions { /** @@ -177,7 +182,7 @@ declare module "perf_hooks" { detail?: unknown | undefined; /** * An optional timestamp to be used as the mark time. - * @default `performance.now()`. + * @default `performance.now()` */ startTime?: number | undefined; } @@ -201,26 +206,36 @@ declare module "perf_hooks" { } interface TimerifyOptions { /** - * A histogram object created using - * `perf_hooks.createHistogram()` that will record runtime durations in - * nanoseconds. + * A histogram object created using `perf_hooks.createHistogram()` that will record runtime + * durations in nanoseconds. */ histogram?: RecordableHistogram | undefined; } interface Performance { /** - * If name is not provided, removes all PerformanceMark objects from the Performance Timeline. - * If name is provided, removes only the named mark. - * @param name + * If `name` is not provided, removes all `PerformanceMark` objects from the Performance Timeline. + * If `name` is provided, removes only the named mark. + * @since v8.5.0 */ clearMarks(name?: string): void; /** - * If name is not provided, removes all PerformanceMeasure objects from the Performance Timeline. - * If name is provided, removes only the named measure. - * @param name + * If `name` is not provided, removes all `PerformanceMeasure` objects from the Performance Timeline. + * If `name` is provided, removes only the named measure. * @since v16.7.0 */ clearMeasures(name?: string): void; + /** + * If `name` is not provided, removes all `PerformanceResourceTiming` objects from the Resource Timeline. + * If `name` is provided, removes only the named resource. + * @since v18.2.0, v16.17.0 + */ + clearResourceTimings(name?: string): void; + /** + * eventLoopUtilization is similar to CPU utilization except that it is calculated using high precision wall-clock time. + * It represents the percentage of time the event loop has spent outside the event loop's event provider (e.g. epoll_wait). + * No other CPU idle time is taken into consideration. + */ + eventLoopUtilization: EventLoopUtilityFunction; /** * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime`. * If you are only interested in performance entries of certain types or that have certain names, see @@ -244,14 +259,17 @@ declare module "perf_hooks" { */ getEntriesByType(type: EntryType): PerformanceEntry[]; /** - * Creates a new PerformanceMark entry in the Performance Timeline. - * A PerformanceMark is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'mark', - * and whose performanceEntry.duration is always 0. + * Creates a new `PerformanceMark` entry in the Performance Timeline. + * A `PerformanceMark` is a subclass of `PerformanceEntry` whose `performanceEntry.entryType` is always `'mark'`, + * and whose `performanceEntry.duration` is always `0`. * Performance marks are used to mark specific significant moments in the Performance Timeline. + * + * The created `PerformanceMark` entry is put in the global Performance Timeline and can be queried with + * `performance.getEntries`, `performance.getEntriesByName`, and `performance.getEntriesByType`. When the observation is + * performed, the entries should be cleared from the global Performance Timeline manually with `performance.clearMarks`. * @param name - * @return The PerformanceMark entry that was created */ - mark(name?: string, options?: MarkOptions): PerformanceMark; + mark(name: string, options?: MarkOptions): PerformanceMark; /** * Creates a new PerformanceMeasure entry in the Performance Timeline. * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', @@ -271,31 +289,74 @@ declare module "perf_hooks" { measure(name: string, startMark?: string, endMark?: string): PerformanceMeasure; measure(name: string, options: MeasureOptions): PerformanceMeasure; /** - * An instance of the PerformanceNodeTiming class that provides performance metrics for specific Node.js operational milestones. + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * An instance of the `PerformanceNodeTiming` class that provides performance metrics for specific Node.js operational milestones. + * @since v8.5.0 */ readonly nodeTiming: PerformanceNodeTiming; /** - * @return the current high resolution millisecond timestamp + * Returns the current high resolution millisecond timestamp, where 0 represents the start of the current `node` process. + * @since v8.5.0 */ now(): number; /** - * The timeOrigin specifies the high resolution millisecond timestamp from which all performance metric durations are measured. + * Sets the global performance resource timing buffer size to the specified number of "resource" type performance entry objects. + * + * By default the max buffer size is set to 250. + * @since v18.8.0 + */ + setResourceTimingBufferSize(maxSize: number): void; + /** + * The [`timeOrigin`](https://w3c.github.io/hr-time/#dom-performance-timeorigin) specifies the high resolution millisecond timestamp + * at which the current `node` process began, measured in Unix time. + * @since v8.5.0 */ readonly timeOrigin: number; /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * * Wraps a function within a new function that measures the running time of the wrapped function. - * A PerformanceObserver must be subscribed to the 'function' event type in order for the timing details to be accessed. + * A `PerformanceObserver` must be subscribed to the `'function'` event type in order for the timing details to be accessed. + * + * ```js + * const { + * performance, + * PerformanceObserver, + * } = require('node:perf_hooks'); + * + * function someFunction() { + * console.log('hello world'); + * } + * + * const wrapped = performance.timerify(someFunction); + * + * const obs = new PerformanceObserver((list) => { + * console.log(list.getEntries()[0].duration); + * + * performance.clearMarks(); + * performance.clearMeasures(); + * obs.disconnect(); + * }); + * obs.observe({ entryTypes: ['function'] }); + * + * // A performance timeline entry will be created + * wrapped(); + * ``` + * + * If the wrapped function returns a promise, a finally handler will be attached to the promise and the duration will be reported + * once the finally handler is invoked. * @param fn */ timerify any>(fn: T, options?: TimerifyOptions): T; /** - * eventLoopUtilization is similar to CPU utilization except that it is calculated using high precision wall-clock time. - * It represents the percentage of time the event loop has spent outside the event loop's event provider (e.g. epoll_wait). - * No other CPU idle time is taken into consideration. + * An object which is JSON representation of the performance object. It is similar to + * [`window.performance.toJSON`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/toJSON) in browsers. + * @since v16.1.0 */ - eventLoopUtilization: EventLoopUtilityFunction; + toJSON(): any; } - interface PerformanceObserverEntryList { + class PerformanceObserverEntryList { /** * Returns a list of `PerformanceEntry` objects in chronological order * with respect to `performanceEntry.startTime`. @@ -392,7 +453,7 @@ declare module "perf_hooks" { getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; /** * Returns a list of `PerformanceEntry` objects in chronological order - * with respect to `performanceEntry.startTime` whose `performanceEntry.entryType`is equal to `type`. + * with respect to `performanceEntry.startTime` whose `performanceEntry.entryType` is equal to `type`. * * ```js * const { @@ -445,7 +506,7 @@ declare module "perf_hooks" { */ disconnect(): void; /** - * Subscribes the `PerformanceObserver` instance to notifications of new `PerformanceEntry` instances identified either by `options.entryTypes`or `options.type`: + * Subscribes the `PerformanceObserver` instance to notifications of new `PerformanceEntry` instances identified either by `options.entryTypes` or `options.type`: * * ```js * const { @@ -475,6 +536,103 @@ declare module "perf_hooks" { }, ): void; } + /** + * Provides detailed network timing data regarding the loading of an application's resources. + * + * The constructor of this class is not exposed to users directly. + * @since v18.2.0, v16.17.0 + */ + class PerformanceResourceTiming extends PerformanceEntry { + protected constructor(); + /** + * The high resolution millisecond timestamp at immediately before dispatching the `fetch` + * request. If the resource is not intercepted by a worker the property will always return 0. + * @since v18.2.0, v16.17.0 + */ + readonly workerStart: number; + /** + * The high resolution millisecond timestamp that represents the start time of the fetch which + * initiates the redirect. + * @since v18.2.0, v16.17.0 + */ + readonly redirectStart: number; + /** + * The high resolution millisecond timestamp that will be created immediately after receiving + * the last byte of the response of the last redirect. + * @since v18.2.0, v16.17.0 + */ + readonly redirectEnd: number; + /** + * The high resolution millisecond timestamp immediately before the Node.js starts to fetch the resource. + * @since v18.2.0, v16.17.0 + */ + readonly fetchStart: number; + /** + * The high resolution millisecond timestamp immediately before the Node.js starts the domain name lookup + * for the resource. + * @since v18.2.0, v16.17.0 + */ + readonly domainLookupStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately after the Node.js finished + * the domain name lookup for the resource. + * @since v18.2.0, v16.17.0 + */ + readonly domainLookupEnd: number; + /** + * The high resolution millisecond timestamp representing the time immediately before Node.js starts to + * establish the connection to the server to retrieve the resource. + * @since v18.2.0, v16.17.0 + */ + readonly connectStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately after Node.js finishes + * establishing the connection to the server to retrieve the resource. + * @since v18.2.0, v16.17.0 + */ + readonly connectEnd: number; + /** + * The high resolution millisecond timestamp representing the time immediately before Node.js starts the + * handshake process to secure the current connection. + * @since v18.2.0, v16.17.0 + */ + readonly secureConnectionStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately before Node.js receives the + * first byte of the response from the server. + * @since v18.2.0, v16.17.0 + */ + readonly requestStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately after Node.js receives the + * last byte of the resource or immediately before the transport connection is closed, whichever comes first. + * @since v18.2.0, v16.17.0 + */ + readonly responseEnd: number; + /** + * A number representing the size (in octets) of the fetched resource. The size includes the response header + * fields plus the response payload body. + * @since v18.2.0, v16.17.0 + */ + readonly transferSize: number; + /** + * A number representing the size (in octets) received from the fetch (HTTP or cache), of the payload body, before + * removing any applied content-codings. + * @since v18.2.0, v16.17.0 + */ + readonly encodedBodySize: number; + /** + * A number representing the size (in octets) received from the fetch (HTTP or cache), of the message body, after + * removing any applied content-codings. + * @since v18.2.0, v16.17.0 + */ + readonly decodedBodySize: number; + /** + * Returns a `object` that is the JSON representation of the `PerformanceResourceTiming` object + * @since v18.2.0, v16.17.0 + */ + toJSON(): any; + } namespace constants { const NODE_PERFORMANCE_GC_MAJOR: number; const NODE_PERFORMANCE_GC_MINOR: number; @@ -499,10 +657,15 @@ declare module "perf_hooks" { } interface Histogram { /** - * Returns a `Map` object detailing the accumulated percentile distribution. - * @since v11.10.0 + * The number of samples recorded by the histogram. + * @since v17.4.0, v16.14.0 */ - readonly percentiles: Map; + readonly count: number; + /** + * The number of samples recorded by the histogram. + * v17.4.0, v16.14.0 + */ + readonly countBigInt: bigint; /** * The number of times the event loop delay exceeded the maximum 1 hour event * loop delay threshold. @@ -510,36 +673,67 @@ declare module "perf_hooks" { */ readonly exceeds: number; /** - * The minimum recorded event loop delay. - * @since v11.10.0 + * The number of times the event loop delay exceeded the maximum 1 hour event loop delay threshold. + * @since v17.4.0, v16.14.0 */ - readonly min: number; + readonly exceedsBigInt: bigint; /** * The maximum recorded event loop delay. * @since v11.10.0 */ readonly max: number; + /** + * The maximum recorded event loop delay. + * v17.4.0, v16.14.0 + */ + readonly maxBigInt: number; /** * The mean of the recorded event loop delays. * @since v11.10.0 */ readonly mean: number; /** - * The standard deviation of the recorded event loop delays. + * The minimum recorded event loop delay. * @since v11.10.0 */ - readonly stddev: number; + readonly min: number; /** - * Resets the collected histogram data. - * @since v11.10.0 + * The minimum recorded event loop delay. + * v17.4.0, v16.14.0 */ - reset(): void; + readonly minBigInt: bigint; /** * Returns the value at the given percentile. * @since v11.10.0 * @param percentile A percentile value in the range (0, 100]. */ percentile(percentile: number): number; + /** + * Returns the value at the given percentile. + * @since v17.4.0, v16.14.0 + * @param percentile A percentile value in the range (0, 100]. + */ + percentileBigInt(percentile: number): bigint; + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v11.10.0 + */ + readonly percentiles: Map; + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v17.4.0, v16.14.0 + */ + readonly percentilesBigInt: Map; + /** + * Resets the collected histogram data. + * @since v11.10.0 + */ + reset(): void; + /** + * The standard deviation of the recorded event loop delays. + * @since v11.10.0 + */ + readonly stddev: number; } interface IntervalHistogram extends Histogram { /** @@ -564,8 +758,6 @@ declare module "perf_hooks" { /** * Calculates the amount of time (in nanoseconds) that has passed since the * previous call to `recordDelta()` and records that amount in the histogram. - * - * ## Examples * @since v15.9.0, v14.18.0 */ recordDelta(): void; @@ -626,11 +818,79 @@ declare module "perf_hooks" { * @since v15.9.0, v14.18.0 */ function createHistogram(options?: CreateHistogramOptions): RecordableHistogram; - import { performance as _performance } from "perf_hooks"; + import { + performance as _performance, + PerformanceEntry as _PerformanceEntry, + PerformanceMark as _PerformanceMark, + PerformanceMeasure as _PerformanceMeasure, + PerformanceObserver as _PerformanceObserver, + PerformanceObserverEntryList as _PerformanceObserverEntryList, + PerformanceResourceTiming as _PerformanceResourceTiming, + } from "perf_hooks"; global { /** - * `performance` is a global reference for `require('perf_hooks').performance` - * https://nodejs.org/api/globals.html#performance + * `PerformanceEntry` is a global reference for `require('node:perf_hooks').PerformanceEntry` + * @see https://nodejs.org/docs/latest-v20.x/api/globals.html#performanceentry + * @since v19.0.0 + */ + var PerformanceEntry: typeof globalThis extends { + onmessage: any; + PerformanceEntry: infer T; + } ? T + : typeof _PerformanceEntry; + /** + * `PerformanceMark` is a global reference for `require('node:perf_hooks').PerformanceMark` + * @see https://nodejs.org/docs/latest-v20.x/api/globals.html#performancemark + * @since v19.0.0 + */ + var PerformanceMark: typeof globalThis extends { + onmessage: any; + PerformanceMark: infer T; + } ? T + : typeof _PerformanceMark; + /** + * `PerformanceMeasure` is a global reference for `require('node:perf_hooks').PerformanceMeasure` + * @see https://nodejs.org/docs/latest-v20.x/api/globals.html#performancemeasure + * @since v19.0.0 + */ + var PerformanceMeasure: typeof globalThis extends { + onmessage: any; + PerformanceMeasure: infer T; + } ? T + : typeof _PerformanceMeasure; + /** + * `PerformanceObserver` is a global reference for `require('node:perf_hooks').PerformanceObserver` + * @see https://nodejs.org/docs/latest-v20.x/api/globals.html#performanceobserver + * @since v19.0.0 + */ + var PerformanceObserver: typeof globalThis extends { + onmessage: any; + PerformanceObserver: infer T; + } ? T + : typeof _PerformanceObserver; + /** + * `PerformanceObserverEntryList` is a global reference for `require('node:perf_hooks').PerformanceObserverEntryList` + * @see https://nodejs.org/docs/latest-v20.x/api/globals.html#performanceobserverentrylist + * @since v19.0.0 + */ + var PerformanceObserverEntryList: typeof globalThis extends { + onmessage: any; + PerformanceObserverEntryList: infer T; + } ? T + : typeof _PerformanceObserverEntryList; + /** + * `PerformanceResourceTiming` is a global reference for `require('node:perf_hooks').PerformanceResourceTiming` + * @see https://nodejs.org/docs/latest-v20.x/api/globals.html#performanceresourcetiming + * @since v19.0.0 + */ + var PerformanceResourceTiming: typeof globalThis extends { + onmessage: any; + PerformanceResourceTiming: infer T; + } ? T + : typeof _PerformanceResourceTiming; + /** + * `performance` is a global reference for `require('node:perf_hooks').performance` + * @see https://nodejs.org/docs/latest-v20.x/api/globals.html#performance * @since v16.0.0 */ var performance: typeof globalThis extends { diff --git a/node_modules/@types/node/process.d.ts b/node_modules/@types/node/process.d.ts index d22308f6cba9971f38badf9f9706933d7350c446..5f84863f9b4824dd1bd753726e6cbb3813fe358e 100644 --- a/node_modules/@types/node/process.d.ts +++ b/node_modules/@types/node/process.d.ts @@ -1,4 +1,6 @@ declare module "process" { + import * as net from "node:net"; + import * as os from "node:os"; import * as tty from "node:tty"; import { Worker } from "node:worker_threads"; global { @@ -21,10 +23,25 @@ declare module "process" { rss(): number; } interface MemoryUsage { + /** + * Resident Set Size, is the amount of space occupied in the main memory device (that is a subset of the total allocated memory) for the + * process, including all C++ and JavaScript objects and code. + */ rss: number; + /** + * Refers to V8's memory usage. + */ heapTotal: number; + /** + * Refers to V8's memory usage. + */ heapUsed: number; external: number; + /** + * Refers to memory allocated for `ArrayBuffer`s and `SharedArrayBuffer`s, including all Node.js Buffers. This is also included + * in the external value. When Node.js is used as an embedded library, this value may be `0` because allocations for `ArrayBuffer`s + * may not be tracked in that case. + */ arrayBuffers: number; } interface CpuUsage { @@ -64,6 +81,7 @@ declare module "process" { | "arm" | "arm64" | "ia32" + | "loong64" | "mips" | "mipsel" | "ppc" @@ -143,8 +161,53 @@ declare module "process" { } interface HRTime { (time?: [number, number]): [number, number]; + /** + * The `bigint` version of the `{@link hrtime()}` method returning the current high-resolution real time in nanoseconds as a `bigint`. + * + * Unlike `{@link hrtime()}`, it does not support an additional time argument since the difference can just be computed directly by subtraction of the two `bigint`s. + * ```js + * import { hrtime } from 'node:process'; + * + * const start = hrtime.bigint(); + * // 191051479007711n + * + * setTimeout(() => { + * const end = hrtime.bigint(); + * // 191052633396993n + * + * console.log(`Benchmark took ${end - start} nanoseconds`); + * // Benchmark took 1154389282 nanoseconds + * }, 1000); + * ``` + */ bigint(): bigint; } + interface ProcessPermission { + /** + * Verifies that the process is able to access the given scope and reference. + * If no reference is provided, a global scope is assumed, for instance, `process.permission.has('fs.read')` + * will check if the process has ALL file system read permissions. + * + * The reference has a meaning based on the provided scope. For example, the reference when the scope is File System means files and folders. + * + * The available scopes are: + * + * * `fs` - All File System + * * `fs.read` - File System read operations + * * `fs.write` - File System write operations + * * `child` - Child process spawning operations + * * `worker` - Worker thread spawning operation + * + * ```js + * // Check if the process has permission to read the README file + * process.permission.has('fs.read', './README.md'); + * // Check if the process has read permission operations + * process.permission.has('fs.read'); + * ``` + * @since v20.0.0 + */ + has(scope: string, reference?: string): boolean; + } interface ProcessReport { /** * Directory where the report is written. @@ -306,12 +369,11 @@ declare module "process" { * For more information see `Stream compatibility`. * * In "old" streams mode the `stdin` stream is paused by default, so one - * must call `process.stdin.resume()` to read from it. Note also that calling`process.stdin.resume()` itself would switch stream to "old" mode. + * must call `process.stdin.resume()` to read from it. Note also that calling `process.stdin.resume()` itself would switch stream to "old" mode. */ stdin: ReadStream & { fd: 0; }; - openStdin(): Socket; /** * The `process.argv` property returns an array containing the command-line * arguments passed when the Node.js process was launched. The first element will @@ -371,13 +433,13 @@ declare module "process" { * the same execution environment as the parent. * * ```bash - * node --harmony script.js --version + * node --icu-data-dir=./foo --require ./bar.js script.js --version * ``` * * Results in `process.execArgv`: * * ```js - * ['--harmony'] + * ["--icu-data-dir=./foo", "--require", "./bar.js"] * ``` * * And `process.argv`: @@ -453,6 +515,32 @@ declare module "process" { * @since v0.7.2 */ debugPort: number; + /** + * The `process.dlopen()` method allows dynamically loading shared objects. It is primarily used by `require()` to load C++ Addons, and + * should not be used directly, except in special cases. In other words, `require()` should be preferred over `process.dlopen()` + * unless there are specific reasons such as custom dlopen flags or loading from ES modules. + * + * The `flags` argument is an integer that allows to specify dlopen behavior. See the `[os.constants.dlopen](https://nodejs.org/docs/latest-v20.x/api/os.html#dlopen-constants)` + * documentation for details. + * + * An important requirement when calling `process.dlopen()` is that the `module` instance must be passed. Functions exported by the C++ Addon + * are then accessible via `module.exports`. + * + * The example below shows how to load a C++ Addon, named `local.node`, that exports a `foo` function. All the symbols are loaded before the call returns, by passing the `RTLD_NOW` constant. + * In this example the constant is assumed to be available. + * + * ```js + * import { dlopen } from 'node:process'; + * import { constants } from 'node:os'; + * import { fileURLToPath } from 'node:url'; + * + * const module = { exports: {} }; + * dlopen(module, fileURLToPath(new URL('local.node', import.meta.url)), + * constants.dlopen.RTLD_NOW); + * module.exports.foo(); + * ``` + */ + dlopen(module: object, filename: string, flags?: number): void; /** * The `process.emitWarning()` method can be used to emit custom or application * specific process warnings. These can be listened for by adding a handler to the `'warning'` event. @@ -460,17 +548,27 @@ declare module "process" { * ```js * import { emitWarning } from 'node:process'; * - * // Emit a warning with a code and additional detail. - * emitWarning('Something happened!', { - * code: 'MY_WARNING', - * detail: 'This is some additional information', - * }); - * // Emits: - * // (node:56338) [MY_WARNING] Warning: Something happened! - * // This is some additional information + * // Emit a warning using a string. + * emitWarning('Something happened!'); + * // Emits: (node: 56338) Warning: Something happened! * ``` * - * In this example, an `Error` object is generated internally by`process.emitWarning()` and passed through to the `'warning'` handler. + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using a string and a type. + * emitWarning('Something Happened!', 'CustomWarning'); + * // Emits: (node:56338) CustomWarning: Something Happened! + * ``` + * + * ```js + * import { emitWarning } from 'node:process'; + * + * emitWarning('Something happened!', 'CustomWarning', 'WARN001'); + * // Emits: (node:56338) [WARN001] CustomWarning: Something happened! + * ```js + * + * In each of the previous examples, an `Error` object is generated internally by `process.emitWarning()` and passed through to the `'warning'` handler. * * ```js * import process from 'node:process'; @@ -484,7 +582,30 @@ declare module "process" { * }); * ``` * - * If `warning` is passed as an `Error` object, the `options` argument is ignored. + * If `warning` is passed as an `Error` object, it will be passed through to the `'warning'` event handler + * unmodified (and the optional `type`, `code` and `ctor` arguments will be ignored): + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using an Error object. + * const myWarning = new Error('Something happened!'); + * // Use the Error name property to specify the type name + * myWarning.name = 'CustomWarning'; + * myWarning.code = 'WARN001'; + * + * emitWarning(myWarning); + * // Emits: (node:56338) [WARN001] CustomWarning: Something happened! + * ``` + * + * A `TypeError` is thrown if `warning` is anything other than a string or `Error` object. + * + * While process warnings use `Error` objects, the process warning mechanism is not a replacement for normal error handling mechanisms. + * + * The following additional handling is implemented if the warning `type` is `'DeprecationWarning'`: + * * If the `--throw-deprecation` command-line flag is used, the deprecation warning is thrown as an exception rather than being emitted as an event. + * * If the `--no-deprecation` command-line flag is used, the deprecation warning is suppressed. + * * If the `--trace-deprecation` command-line flag is used, the deprecation warning is printed to `stderr` along with the full stack trace. * @since v8.0.0 * @param warning The warning to emit. */ @@ -572,7 +693,7 @@ declare module "process" { * parent thread's `process.env`, or whatever was specified as the `env` option * to the `Worker` constructor. Changes to `process.env` will not be visible * across `Worker` threads, and only the main thread can make changes that - * are visible to the operating system or to native add-ons. On Windows, a copy of`process.env` on a `Worker` instance operates in a case-sensitive manner + * are visible to the operating system or to native add-ons. On Windows, a copy of `process.env` on a `Worker` instance operates in a case-sensitive manner * unlike the main thread. * @since v0.1.27 */ @@ -596,13 +717,13 @@ declare module "process" { * * Calling `process.exit()` will force the process to exit as quickly as possible * even if there are still asynchronous operations pending that have not yet - * completed fully, including I/O operations to `process.stdout` and`process.stderr`. + * completed fully, including I/O operations to `process.stdout` and `process.stderr`. * - * In most situations, it is not actually necessary to call `process.exit()`explicitly. The Node.js process will exit on its own _if there is no additional_ + * In most situations, it is not actually necessary to call `process.exit()` explicitly. The Node.js process will exit on its own _if there is no additional_ * _work pending_ in the event loop. The `process.exitCode` property can be set to * tell the process which exit code to use when the process exits gracefully. * - * For instance, the following example illustrates a _misuse_ of the`process.exit()` method that could lead to data printed to stdout being + * For instance, the following example illustrates a _misuse_ of the `process.exit()` method that could lead to data printed to stdout being * truncated and lost: * * ```js @@ -619,7 +740,7 @@ declare module "process" { * are sometimes _asynchronous_ and may occur over multiple ticks of the Node.js * event loop. Calling `process.exit()`, however, forces the process to exit _before_ those additional writes to `stdout` can be performed. * - * Rather than calling `process.exit()` directly, the code _should_ set the`process.exitCode` and allow the process to exit naturally by avoiding + * Rather than calling `process.exit()` directly, the code _should_ set the `process.exitCode` and allow the process to exit naturally by avoiding * scheduling any additional work for the event loop: * * ```js @@ -642,7 +763,7 @@ declare module "process" { * @since v0.1.13 * @param [code=0] The exit code. For string type, only integer strings (e.g.,'1') are allowed. */ - exit(code?: number): never; + exit(code?: number | string | null | undefined): never; /** * A number which will be the process exit code, when the process either * exits gracefully, or is exited via {@link exit} without specifying @@ -650,15 +771,34 @@ declare module "process" { * * Specifying a code to {@link exit} will override any * previous setting of `process.exitCode`. + * @default undefined * @since v0.11.8 */ - exitCode?: number | undefined; + exitCode?: number | string | number | undefined; + /** + * The `process.getActiveResourcesInfo()` method returns an array of strings containing + * the types of the active resources that are currently keeping the event loop alive. + * + * ```js + * import { getActiveResourcesInfo } from 'node:process'; + * import { setTimeout } from 'node:timers'; + + * console.log('Before:', getActiveResourcesInfo()); + * setTimeout(() => {}, 1000); + * console.log('After:', getActiveResourcesInfo()); + * // Prints: + * // Before: [ 'TTYWrap', 'TTYWrap', 'TTYWrap' ] + * // After: [ 'TTYWrap', 'TTYWrap', 'TTYWrap', 'Timeout' ] + * ``` + * @since v17.3.0, v16.14.0 + */ + getActiveResourcesInfo(): string[]; /** * The `process.getgid()` method returns the numerical group identity of the * process. (See [`getgid(2)`](http://man7.org/linux/man-pages/man2/getgid.2.html).) * * ```js - * import process from 'process'; + * import process from 'node:process'; * * if (process.getgid) { * console.log(`Current gid: ${process.getgid()}`); @@ -677,7 +817,7 @@ declare module "process" { * associated numeric ID. * * ```js - * import process from 'process'; + * import process from 'node:process'; * * if (process.getgid && process.setgid) { * console.log(`Current gid: ${process.getgid()}`); @@ -702,7 +842,7 @@ declare module "process" { * (See [`getuid(2)`](http://man7.org/linux/man-pages/man2/getuid.2.html).) * * ```js - * import process from 'process'; + * import process from 'node:process'; * * if (process.getuid) { * console.log(`Current uid: ${process.getuid()}`); @@ -721,7 +861,7 @@ declare module "process" { * numeric ID. * * ```js - * import process from 'process'; + * import process from 'node:process'; * * if (process.getuid && process.setuid) { * console.log(`Current uid: ${process.getuid()}`); @@ -745,7 +885,7 @@ declare module "process" { * the process. (See [`geteuid(2)`](http://man7.org/linux/man-pages/man2/geteuid.2.html).) * * ```js - * import process from 'process'; + * import process from 'node:process'; * * if (process.geteuid) { * console.log(`Current uid: ${process.geteuid()}`); @@ -764,7 +904,7 @@ declare module "process" { * associated numeric ID. * * ```js - * import process from 'process'; + * import process from 'node:process'; * * if (process.geteuid && process.seteuid) { * console.log(`Current uid: ${process.geteuid()}`); @@ -789,7 +929,7 @@ declare module "process" { * of the Node.js process. (See [`getegid(2)`](http://man7.org/linux/man-pages/man2/getegid.2.html).) * * ```js - * import process from 'process'; + * import process from 'node:process'; * * if (process.getegid) { * console.log(`Current gid: ${process.getegid()}`); @@ -808,7 +948,7 @@ declare module "process" { * the associated a numeric ID. * * ```js - * import process from 'process'; + * import process from 'node:process'; * * if (process.getegid && process.setegid) { * console.log(`Current gid: ${process.getegid()}`); @@ -834,7 +974,7 @@ declare module "process" { * Node.js ensures it always is. * * ```js - * import process from 'process'; + * import process from 'node:process'; * * if (process.getgroups) { * console.log(process.getgroups()); // [ 16, 21, 297 ] @@ -854,7 +994,7 @@ declare module "process" { * The `groups` array can contain numeric group IDs, group names, or both. * * ```js - * import process from 'process'; + * import process from 'node:process'; * * if (process.getgroups && process.setgroups) { * try { @@ -883,7 +1023,7 @@ declare module "process" { * not abort. Actions configured to take place on exceptions such as report * generations will be affected too * - * To unset the capture function,`process.setUncaughtExceptionCaptureCallback(null)` may be used. Calling this + * To unset the capture function, `process.setUncaughtExceptionCaptureCallback(null)` may be used. Calling this * method with a non-`null` argument while another capture function is set will * throw an error. * @@ -906,7 +1046,7 @@ declare module "process" { * This function enables or disables the [Source Map v3](https://sourcemaps.info/spec.html) support for * stack traces. * - * It provides same features as launching Node.js process with commandline options`--enable-source-maps`. + * It provides same features as launching Node.js process with commandline options `--enable-source-maps`. * * Only source maps in JavaScript files that are loaded after source maps has been * enabled will be parsed and loaded. @@ -1044,6 +1184,21 @@ declare module "process" { * @param [signal='SIGTERM'] The signal to send, either as a string or number. */ kill(pid: number, signal?: string | number): true; + /** + * Loads the environment configuration from a `.env` file into `process.env`. If + * the file is not found, error will be thrown. + * + * To load a specific .env file by specifying its path, use the following code: + * + * ```js + * import { loadEnvFile } from 'node:process'; + * + * loadEnvFile('./development.env') + * ``` + * @since v20.12.0 + * @param path The path to the .env file + */ + loadEnvFile(path?: string | URL | Buffer): void; /** * The `process.pid` property returns the PID of the process. * @@ -1075,8 +1230,8 @@ declare module "process" { * When a new value is assigned, different platforms will impose different maximum * length restrictions on the title. Usually such restrictions are quite limited. * For instance, on Linux and macOS, `process.title` is limited to the size of the - * binary name plus the length of the command-line arguments because setting the`process.title` overwrites the `argv` memory of the process. Node.js v0.8 - * allowed for longer process title strings by also overwriting the `environ`memory but that was potentially insecure and confusing in some (rather obscure) + * binary name plus the length of the command-line arguments because setting the `process.title` overwrites the `argv` memory of the process. Node.js v0.8 + * allowed for longer process title strings by also overwriting the `environ` memory but that was potentially insecure and confusing in some (rather obscure) * cases. * * Assigning a value to `process.title` might not result in an accurate label @@ -1087,7 +1242,7 @@ declare module "process" { title: string; /** * The operating system CPU architecture for which the Node.js binary was compiled. - * Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`, `'mips'`,`'mipsel'`, `'ppc'`, `'ppc64'`, `'riscv64'`, `'s390'`, `'s390x'`, and `'x64'`. + * Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`, `'mips'`, `'mipsel'`, `'ppc'`, `'ppc64'`, `'riscv64'`, `'s390'`, `'s390x'`, and `'x64'`. * * ```js * import { arch } from 'node:process'; @@ -1138,14 +1293,21 @@ declare module "process" { /** * Gets the amount of memory available to the process (in bytes) based on * limits imposed by the OS. If there is no such constraint, or the constraint - * is unknown, `undefined` is returned. + * is unknown, `0` is returned. * * See [`uv_get_constrained_memory`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_get_constrained_memory) for more * information. * @since v19.6.0, v18.15.0 * @experimental */ - constrainedMemory(): number | undefined; + constrainedMemory(): number; + /** + * Gets the amount of free memory that is still available to the process (in bytes). + * See [`uv_get_available_memory`](https://nodejs.org/docs/latest-v20.x/api/process.html#processavailablememory) for more information. + * @experimental + * @since v20.13.0 + */ + availableMemory(): number; /** * The `process.cpuUsage()` method returns the user and system CPU time usage of * the current process, in an object with properties `user` and `system`, whose @@ -1262,6 +1424,14 @@ declare module "process" { * @param args Additional arguments to pass when invoking the `callback` */ nextTick(callback: Function, ...args: any[]): void; + /** + * This API is available through the [--experimental-permission](https://nodejs.org/api/cli.html#--experimental-permission) flag. + * + * `process.permission` is an object whose methods are used to manage permissions for the current process. + * Additional documentation is available in the [Permission Model](https://nodejs.org/api/permissions.html#permission-model). + * @since v20.0.0 + */ + permission: ProcessPermission; /** * The `process.release` property returns an `Object` containing metadata related * to the current release, including URLs for the source tarball and headers-only @@ -1279,7 +1449,7 @@ declare module "process" { * } * ``` * - * In custom builds from non-release versions of the source tree, only the`name` property may be present. The additional properties should not be + * In custom builds from non-release versions of the source tree, only the `name` property may be present. The additional properties should not be * relied upon to exist. * @since v3.0.0 */ @@ -1298,7 +1468,7 @@ declare module "process" { * `process.umask()` returns the Node.js process's file mode creation mask. Child * processes inherit the mask from the parent process. * @since v0.1.19 - * @deprecated Calling `process.umask()` with no argument causes the process-wide umask to be written twice. This introduces a race condition between threads, and is a potential * + * @deprecated Calling `process.umask()` with no argument causes the process-wide umask to be written twice. This introduces a race condition between threads, and is a potential * security vulnerability. There is no safe, cross-platform alternative API. */ umask(): number; @@ -1342,13 +1512,13 @@ declare module "process" { * The message goes through serialization and parsing. The resulting message might * not be the same as what is originally sent. * @since v0.5.9 - * @param options used to parameterize the sending of certain types of handles.`options` supports the following properties: + * @param options used to parameterize the sending of certain types of handles. `options` supports the following properties: */ send?( message: any, sendHandle?: any, options?: { - swallowErrors?: boolean | undefined; + keepOpen?: boolean | undefined; }, callback?: (error: Error | null) => void, ): boolean; @@ -1359,13 +1529,13 @@ declare module "process" { * * The effect of calling `process.disconnect()` is the same as calling `ChildProcess.disconnect()` from the parent process. * - * If the Node.js process was not spawned with an IPC channel,`process.disconnect()` will be `undefined`. + * If the Node.js process was not spawned with an IPC channel, `process.disconnect()` will be `undefined`. * @since v0.7.2 */ disconnect(): void; /** - * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.connected` property will return`true` so long as the IPC - * channel is connected and will return `false` after`process.disconnect()` is called. + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.connected` property will return `true` so long as the IPC + * channel is connected and will return `false` after `process.disconnect()` is called. * * Once `process.connected` is `false`, it is no longer possible to send messages * over the IPC channel using `process.send()`. @@ -1376,11 +1546,11 @@ declare module "process" { * The `process.allowedNodeEnvironmentFlags` property is a special, * read-only `Set` of flags allowable within the `NODE_OPTIONS` environment variable. * - * `process.allowedNodeEnvironmentFlags` extends `Set`, but overrides`Set.prototype.has` to recognize several different possible flag + * `process.allowedNodeEnvironmentFlags` extends `Set`, but overrides `Set.prototype.has` to recognize several different possible flag * representations. `process.allowedNodeEnvironmentFlags.has()` will * return `true` in the following cases: * - * * Flags may omit leading single (`-`) or double (`--`) dashes; e.g.,`inspect-brk` for `--inspect-brk`, or `r` for `-r`. + * * Flags may omit leading single (`-`) or double (`--`) dashes; e.g., `inspect-brk` for `--inspect-brk`, or `r` for `-r`. * * Flags passed through to V8 (as listed in `--v8-options`) may replace * one or more _non-leading_ dashes for an underscore, or vice-versa; * e.g., `--perf_basic_prof`, `--perf-basic-prof`, `--perf_basic-prof`, @@ -1452,7 +1622,30 @@ declare module "process" { */ resourceUsage(): ResourceUsage; /** - * The `process.traceDeprecation` property indicates whether the`--trace-deprecation` flag is set on the current Node.js process. See the + * The initial value of `process.throwDeprecation` indicates whether the `--throw-deprecation` flag is set on the current Node.js process. `process.throwDeprecation` + * is mutable, so whether or not deprecation warnings result in errors may be altered at runtime. See the documentation for the 'warning' event and the emitWarning() + * method for more information. + * + * ```bash + * $ node --throw-deprecation -p "process.throwDeprecation" + * true + * $ node -p "process.throwDeprecation" + * undefined + * $ node + * > process.emitWarning('test', 'DeprecationWarning'); + * undefined + * > (node:26598) DeprecationWarning: test + * > process.throwDeprecation = true; + * true + * > process.emitWarning('test', 'DeprecationWarning'); + * Thrown: + * [DeprecationWarning: test] { name: 'DeprecationWarning' } + * ``` + * @since v0.9.12 + */ + throwDeprecation: boolean; + /** + * The `process.traceDeprecation` property indicates whether the `--trace-deprecation` flag is set on the current Node.js process. See the * documentation for the `'warning' event` and the `emitWarning() method` for more information about this * flag's behavior. * @since v0.8.0 diff --git a/node_modules/@types/node/punycode.d.ts b/node_modules/@types/node/punycode.d.ts index d2fc9f9a8ffbcffd5d9e966ef1d2b75fce902017..137441d96fae7c4a5fd23f4d9b80f430d63fbfe3 100644 --- a/node_modules/@types/node/punycode.d.ts +++ b/node_modules/@types/node/punycode.d.ts @@ -1,5 +1,5 @@ /** - * **The version of the punycode module bundled in Node.js is being deprecated.**In a future major version of Node.js this module will be removed. Users + * **The version of the punycode module bundled in Node.js is being deprecated. **In a future major version of Node.js this module will be removed. Users * currently depending on the `punycode` module should switch to using the * userland-provided [Punycode.js](https://github.com/bestiejs/punycode.js) module instead. For punycode-based URL * encoding, see `url.domainToASCII` or, more generally, the `WHATWG URL API`. @@ -15,8 +15,8 @@ * primarily intended for use in Internationalized Domain Names. Because host * names in URLs are limited to ASCII characters only, Domain Names that contain * non-ASCII characters must be converted into ASCII using the Punycode scheme. - * For instance, the Japanese character that translates into the English word,`'example'` is `'例'`. The Internationalized Domain Name, `'例.com'` (equivalent - * to `'example.com'`) is represented by Punycode as the ASCII string`'xn--fsq.com'`. + * For instance, the Japanese character that translates into the English word, `'example'` is `'例'`. The Internationalized Domain Name, `'例.com'` (equivalent + * to `'example.com'`) is represented by Punycode as the ASCII string `'xn--fsq.com'`. * * The `punycode` module provides a simple implementation of the Punycode standard. * @@ -24,7 +24,7 @@ * made available to developers as a convenience. Fixes or other modifications to * the module must be directed to the [Punycode.js](https://github.com/bestiejs/punycode.js) project. * @deprecated Since v7.0.0 - Deprecated - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/punycode.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/punycode.js) */ declare module "punycode" { /** diff --git a/node_modules/@types/node/querystring.d.ts b/node_modules/@types/node/querystring.d.ts index b36ea2c13014b641baf04669dc15bd40c928fbee..bd494a6b838c3bd064675249ed6f2daffd3bdac2 100644 --- a/node_modules/@types/node/querystring.d.ts +++ b/node_modules/@types/node/querystring.d.ts @@ -9,14 +9,26 @@ * `querystring` is more performant than `URLSearchParams` but is not a * standardized API. Use `URLSearchParams` when performance is not critical or * when compatibility with browser code is desirable. - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/querystring.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/querystring.js) */ declare module "querystring" { interface StringifyOptions { + /** + * The function to use when converting URL-unsafe characters to percent-encoding in the query string. + * @default `querystring.escape()` + */ encodeURIComponent?: ((str: string) => string) | undefined; } interface ParseOptions { + /** + * Specifies the maximum number of keys to parse. Specify `0` to remove key counting limitations. + * @default 1000 + */ maxKeys?: number | undefined; + /** + * The function to use when decoding percent-encoded characters in the query string. + * @default `querystring.unescape()` + */ decodeURIComponent?: ((str: string) => string) | undefined; } interface ParsedUrlQuery extends NodeJS.Dict {} @@ -35,7 +47,7 @@ declare module "querystring" { * The `querystring.stringify()` method produces a URL query string from a * given `obj` by iterating through the object's "own properties". * - * It serializes the following types of values passed in `obj`:[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * It serializes the following types of values passed in `obj`: [string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | * [number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | * [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | @@ -54,7 +66,7 @@ declare module "querystring" { * ``` * * By default, characters requiring percent-encoding within the query string will - * be encoded as UTF-8\. If an alternative encoding is required, then an alternative`encodeURIComponent` option will need to be specified: + * be encoded as UTF-8\. If an alternative encoding is required, then an alternative `encodeURIComponent` option will need to be specified: * * ```js * // Assuming gbkEncodeURIComponent function already exists, @@ -81,7 +93,7 @@ declare module "querystring" { * } * ``` * - * The object returned by the `querystring.parse()` method _does not_prototypically inherit from the JavaScript `Object`. This means that typical`Object` methods such as `obj.toString()`, + * The object returned by the `querystring.parse()` method _does not_ prototypically inherit from the JavaScript `Object`. This means that typical `Object` methods such as `obj.toString()`, * `obj.hasOwnProperty()`, and others * are not defined and _will not work_. * @@ -98,7 +110,7 @@ declare module "querystring" { * @since v0.1.25 * @param str The URL query string to parse * @param [sep='&'] The substring used to delimit key and value pairs in the query string. - * @param [eq='='] . The substring used to delimit keys and values in the query string. + * @param [eq='='] The substring used to delimit keys and values in the query string. */ function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery; /** @@ -110,7 +122,7 @@ declare module "querystring" { */ const decode: typeof parse; /** - * The `querystring.escape()` method performs URL percent-encoding on the given`str` in a manner that is optimized for the specific requirements of URL + * The `querystring.escape()` method performs URL percent-encoding on the given `str` in a manner that is optimized for the specific requirements of URL * query strings. * * The `querystring.escape()` method is used by `querystring.stringify()` and is diff --git a/node_modules/@types/node/readline.d.ts b/node_modules/@types/node/readline.d.ts index b06d58b85e62c03ff7d388177c9dce7bdde86569..06e1705a211de79d5b396a455c6888e42c275303 100644 --- a/node_modules/@types/node/readline.d.ts +++ b/node_modules/@types/node/readline.d.ts @@ -1,5 +1,6 @@ /** - * The `node:readline` module provides an interface for reading data from a `Readable` stream (such as `process.stdin`) one line at a time. + * The `node:readline` module provides an interface for reading data from a [Readable](https://nodejs.org/docs/latest-v20.x/api/stream.html#readable-streams) stream + * (such as [`process.stdin`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdin)) one line at a time. * * To use the promise-based APIs: * @@ -13,7 +14,7 @@ * import * as readline from 'node:readline'; * ``` * - * The following simple example illustrates the basic use of the `node:readline`module. + * The following simple example illustrates the basic use of the `node:readline` module. * * ```js * import * as readline from 'node:readline/promises'; @@ -28,9 +29,9 @@ * rl.close(); * ``` * - * Once this code is invoked, the Node.js application will not terminate until the`readline.Interface` is closed because the interface waits for data to be + * Once this code is invoked, the Node.js application will not terminate until the `readline.Interface` is closed because the interface waits for data to be * received on the `input` stream. - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/readline.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/readline.js) */ declare module "readline" { import { Abortable, EventEmitter } from "node:events"; @@ -44,8 +45,8 @@ declare module "readline" { shift?: boolean | undefined; } /** - * Instances of the `readline.Interface` class are constructed using the`readline.createInterface()` method. Every instance is associated with a - * single `input` `Readable` stream and a single `output` `Writable` stream. + * Instances of the `readline.Interface` class are constructed using the `readline.createInterface()` method. Every instance is associated with a + * single `input` [Readable](https://nodejs.org/docs/latest-v20.x/api/stream.html#readable-streams) stream and a single `output` [Writable](https://nodejs.org/docs/latest-v20.x/api/stream.html#writable-streams) stream. * The `output` stream is used to print prompts for user input that arrives on, * and is read from, the `input` stream. * @since v0.1.104 @@ -123,7 +124,7 @@ declare module "readline" { */ getPrompt(): string; /** - * The `rl.setPrompt()` method sets the prompt that will be written to `output`whenever `rl.prompt()` is called. + * The `rl.setPrompt()` method sets the prompt that will be written to `output` whenever `rl.prompt()` is called. * @since v0.1.98 */ setPrompt(prompt: string): void; @@ -134,19 +135,19 @@ declare module "readline" { * When called, `rl.prompt()` will resume the `input` stream if it has been * paused. * - * If the `Interface` was created with `output` set to `null` or`undefined` the prompt is not written. + * If the `Interface` was created with `output` set to `null` or `undefined` the prompt is not written. * @since v0.1.98 * @param preserveCursor If `true`, prevents the cursor placement from being reset to `0`. */ prompt(preserveCursor?: boolean): void; /** * The `rl.question()` method displays the `query` by writing it to the `output`, - * waits for user input to be provided on `input`, then invokes the `callback`function passing the provided input as the first argument. + * waits for user input to be provided on `input`, then invokes the `callback` function passing the provided input as the first argument. * * When called, `rl.question()` will resume the `input` stream if it has been * paused. * - * If the `Interface` was created with `output` set to `null` or`undefined` the `query` is not written. + * If the `Interface` was created with `output` set to `null` or `undefined` the `query` is not written. * * The `callback` function passed to `rl.question()` does not follow the typical * pattern of accepting an `Error` object or `null` as the first argument. @@ -188,7 +189,7 @@ declare module "readline" { * The `rl.pause()` method pauses the `input` stream, allowing it to be resumed * later if necessary. * - * Calling `rl.pause()` does not immediately pause other events (including`'line'`) from being emitted by the `Interface` instance. + * Calling `rl.pause()` does not immediately pause other events (including `'line'`) from being emitted by the `Interface` instance. * @since v0.3.4 */ pause(): this; @@ -218,7 +219,7 @@ declare module "readline" { * When called, `rl.write()` will resume the `input` stream if it has been * paused. * - * If the `Interface` was created with `output` set to `null` or`undefined` the `data` and `key` are not written. + * If the `Interface` was created with `output` set to `null` or `undefined` the `data` and `key` are not written. * * ```js * rl.write('Delete this!'); @@ -226,7 +227,7 @@ declare module "readline" { * rl.write(null, { ctrl: true, name: 'u' }); * ``` * - * The `rl.write()` method will write the data to the `readline` `Interface`'s`input`_as if it were provided by the user_. + * The `rl.write()` method will write the data to the `readline` `Interface`'s `input` _as if it were provided by the user_. * @since v0.1.98 */ write(data: string | Buffer, key?: Key): void; @@ -338,7 +339,7 @@ declare module "readline" { tabSize?: number | undefined; } /** - * The `readline.createInterface()` method creates a new `readline.Interface`instance. + * The `readline.createInterface()` method creates a new `readline.Interface` instance. * * ```js * const readline = require('node:readline'); @@ -382,7 +383,7 @@ declare module "readline" { * * If the `stream` is a `TTY`, then it must be in raw mode. * - * This is automatically called by any readline instance on its `input` if the`input` is a terminal. Closing the `readline` instance does not stop + * This is automatically called by any readline instance on its `input` if the `input` is a terminal. Closing the `readline` instance does not stop * the `input` from emitting `'keypress'` events. * * ```js @@ -467,7 +468,7 @@ declare module "readline" { * }); * ``` * - * Currently, `for await...of` loop can be a bit slower. If `async` / `await`flow and speed are both essential, a mixed approach can be applied: + * Currently, `for await...of` loop can be a bit slower. If `async` / `await` flow and speed are both essential, a mixed approach can be applied: * * ```js * const { once } = require('node:events'); @@ -502,7 +503,7 @@ declare module "readline" { cols: number; } /** - * The `readline.clearLine()` method clears current line of given `TTY` stream + * The `readline.clearLine()` method clears current line of given [TTY](https://nodejs.org/docs/latest-v20.x/api/tty.html) stream * in a specified direction identified by `dir`. * @since v0.7.7 * @param callback Invoked once the operation completes. @@ -510,7 +511,7 @@ declare module "readline" { */ export function clearLine(stream: NodeJS.WritableStream, dir: Direction, callback?: () => void): boolean; /** - * The `readline.clearScreenDown()` method clears the given `TTY` stream from + * The `readline.clearScreenDown()` method clears the given [TTY](https://nodejs.org/docs/latest-v20.x/api/tty.html) stream from * the current position of the cursor down. * @since v0.7.7 * @param callback Invoked once the operation completes. @@ -519,7 +520,7 @@ declare module "readline" { export function clearScreenDown(stream: NodeJS.WritableStream, callback?: () => void): boolean; /** * The `readline.cursorTo()` method moves cursor to the specified position in a - * given `TTY` `stream`. + * given [TTY](https://nodejs.org/docs/latest-v20.x/api/tty.html) `stream`. * @since v0.7.7 * @param callback Invoked once the operation completes. * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. @@ -527,7 +528,7 @@ declare module "readline" { export function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number, callback?: () => void): boolean; /** * The `readline.moveCursor()` method moves the cursor _relative_ to its current - * position in a given `TTY` `stream`. + * position in a given [TTY](https://nodejs.org/docs/latest-v20.x/api/tty.html) `stream`. * @since v0.7.7 * @param callback Invoked once the operation completes. * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. diff --git a/node_modules/@types/node/readline/promises.d.ts b/node_modules/@types/node/readline/promises.d.ts index 73fb1115d50096f9e6bcadf04943a597c5146312..f2826bb9320b9cd74ee9cc55d9efb0bd81603bb6 100644 --- a/node_modules/@types/node/readline/promises.d.ts +++ b/node_modules/@types/node/readline/promises.d.ts @@ -6,7 +6,7 @@ declare module "readline/promises" { import { AsyncCompleter, Completer, Direction, Interface as _Interface, ReadLineOptions } from "node:readline"; import { Abortable } from "node:events"; /** - * Instances of the `readlinePromises.Interface` class are constructed using the`readlinePromises.createInterface()` method. Every instance is associated with a + * Instances of the `readlinePromises.Interface` class are constructed using the `readlinePromises.createInterface()` method. Every instance is associated with a * single `input` `Readable` stream and a single `output` `Writable` stream. * The `output` stream is used to print prompts for user input that arrives on, * and is read from, the `input` stream. @@ -15,12 +15,12 @@ declare module "readline/promises" { class Interface extends _Interface { /** * The `rl.question()` method displays the `query` by writing it to the `output`, - * waits for user input to be provided on `input`, then invokes the `callback`function passing the provided input as the first argument. + * waits for user input to be provided on `input`, then invokes the `callback` function passing the provided input as the first argument. * * When called, `rl.question()` will resume the `input` stream if it has been * paused. * - * If the `Interface` was created with `output` set to `null` or`undefined` the `query` is not written. + * If the `Interface` was created with `output` set to `null` or `undefined` the `query` is not written. * * If the question is called after `rl.close()`, it returns a rejected promise. * @@ -67,7 +67,7 @@ declare module "readline/promises" { * The `rl.clearLine()` method adds to the internal list of pending action an * action that clears current line of the associated `stream` in a specified * direction identified by `dir`. - * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true`was passed to the constructor. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. * @since v17.0.0 * @return this */ @@ -76,20 +76,20 @@ declare module "readline/promises" { * The `rl.clearScreenDown()` method adds to the internal list of pending action an * action that clears the associated stream from the current position of the * cursor down. - * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true`was passed to the constructor. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. * @since v17.0.0 * @return this */ clearScreenDown(): this; /** - * The `rl.commit()` method sends all the pending actions to the associated`stream` and clears the internal list of pending actions. + * The `rl.commit()` method sends all the pending actions to the associated `stream` and clears the internal list of pending actions. * @since v17.0.0 */ commit(): Promise; /** * The `rl.cursorTo()` method adds to the internal list of pending action an action * that moves cursor to the specified position in the associated `stream`. - * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true`was passed to the constructor. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. * @since v17.0.0 * @return this */ @@ -98,7 +98,7 @@ declare module "readline/promises" { * The `rl.moveCursor()` method adds to the internal list of pending action an * action that moves the cursor _relative_ to its current position in the * associated `stream`. - * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true`was passed to the constructor. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. * @since v17.0.0 * @return this */ @@ -112,7 +112,7 @@ declare module "readline/promises" { rollback(): this; } /** - * The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface`instance. + * The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface` instance. * * ```js * const readlinePromises = require('node:readline/promises'); diff --git a/node_modules/@types/node/repl.d.ts b/node_modules/@types/node/repl.d.ts index 6c5f81b399df50506180bd8d271840029659572b..f55ef66abd919d2343cb0cd52a17a326952d64ad 100644 --- a/node_modules/@types/node/repl.d.ts +++ b/node_modules/@types/node/repl.d.ts @@ -6,7 +6,7 @@ * ```js * const repl = require('node:repl'); * ``` - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/repl.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/repl.js) */ declare module "repl" { import { AsyncCompleter, Completer, Interface } from "node:readline"; @@ -54,25 +54,25 @@ declare module "repl" { * If `true`, specifies that the default `writer` function should include ANSI color * styling to REPL output. If a custom `writer` function is provided then this has no * effect. - * Default: the REPL instance's `terminal` value. + * @default the REPL instance's `terminal` value */ useColors?: boolean | undefined; /** * If `true`, specifies that the default evaluation function will use the JavaScript * `global` as the context as opposed to creating a new separate context for the REPL * instance. The node CLI REPL sets this value to `true`. - * Default: `false`. + * @default false */ useGlobal?: boolean | undefined; /** * If `true`, specifies that the default writer will not output the return value of a * command if it evaluates to `undefined`. - * Default: `false`. + * @default false */ ignoreUndefined?: boolean | undefined; /** * The function to invoke to format the output of each command before writing to `output`. - * Default: a wrapper for `util.inspect`. + * @default a wrapper for `util.inspect` * * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_customizing_repl_output */ @@ -95,7 +95,7 @@ declare module "repl" { /** * Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is * pressed. This cannot be used together with a custom `eval` function. - * Default: `false`. + * @default false */ breakEvalOnSigint?: boolean | undefined; } @@ -251,7 +251,7 @@ declare module "repl" { private constructor(); /** * The `replServer.defineCommand()` method is used to add new `.`\-prefixed commands - * to the REPL instance. Such commands are invoked by typing a `.` followed by the`keyword`. The `cmd` is either a `Function` or an `Object` with the following + * to the REPL instance. Such commands are invoked by typing a `.` followed by the `keyword`. The `cmd` is either a `Function` or an `Object` with the following * properties: * * The following example shows two new commands added to the REPL instance: @@ -289,7 +289,7 @@ declare module "repl" { defineCommand(keyword: string, cmd: REPLCommandAction | REPLCommand): void; /** * The `replServer.displayPrompt()` method readies the REPL instance for input - * from the user, printing the configured `prompt` to a new line in the `output`and resuming the `input` to accept new input. + * from the user, printing the configured `prompt` to a new line in the `output` and resuming the `input` to accept new input. * * When multi-line input is being entered, an ellipsis is printed rather than the * 'prompt'. @@ -297,14 +297,14 @@ declare module "repl" { * When `preserveCursor` is `true`, the cursor placement will not be reset to `0`. * * The `replServer.displayPrompt` method is primarily intended to be called from - * within the action function for commands registered using the`replServer.defineCommand()` method. + * within the action function for commands registered using the `replServer.defineCommand()` method. * @since v0.1.91 */ displayPrompt(preserveCursor?: boolean): void; /** * The `replServer.clearBufferedCommand()` method clears any command that has been * buffered but not yet executed. This method is primarily intended to be - * called from within the action function for commands registered using the`replServer.defineCommand()` method. + * called from within the action function for commands registered using the `replServer.defineCommand()` method. * @since v9.0.0 */ clearBufferedCommand(): void; diff --git a/node_modules/@types/node/sea.d.ts b/node_modules/@types/node/sea.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6f1d1eaeaf537a150df254f0f95a802dab85e6c7 --- /dev/null +++ b/node_modules/@types/node/sea.d.ts @@ -0,0 +1,153 @@ +/** + * This feature allows the distribution of a Node.js application conveniently to a + * system that does not have Node.js installed. + * + * Node.js supports the creation of [single executable applications](https://github.com/nodejs/single-executable) by allowing + * the injection of a blob prepared by Node.js, which can contain a bundled script, + * into the `node` binary. During start up, the program checks if anything has been + * injected. If the blob is found, it executes the script in the blob. Otherwise + * Node.js operates as it normally does. + * + * The single executable application feature currently only supports running a + * single embedded script using the `CommonJS` module system. + * + * Users can create a single executable application from their bundled script + * with the `node` binary itself and any tool which can inject resources into the + * binary. + * + * Here are the steps for creating a single executable application using one such + * tool, [postject](https://github.com/nodejs/postject): + * + * 1. Create a JavaScript file: + * ```bash + * echo 'console.log(`Hello, ${process.argv[2]}!`);' > hello.js + * ``` + * 2. Create a configuration file building a blob that can be injected into the + * single executable application (see `Generating single executable preparation blobs` for details): + * ```bash + * echo '{ "main": "hello.js", "output": "sea-prep.blob" }' > sea-config.json + * ``` + * 3. Generate the blob to be injected: + * ```bash + * node --experimental-sea-config sea-config.json + * ``` + * 4. Create a copy of the `node` executable and name it according to your needs: + * * On systems other than Windows: + * ```bash + * cp $(command -v node) hello + * ``` + * * On Windows: + * ```text + * node -e "require('fs').copyFileSync(process.execPath, 'hello.exe')" + * ``` + * The `.exe` extension is necessary. + * 5. Remove the signature of the binary (macOS and Windows only): + * * On macOS: + * ```bash + * codesign --remove-signature hello + * ``` + * * On Windows (optional): + * [signtool](https://learn.microsoft.com/en-us/windows/win32/seccrypto/signtool) can be used from the installed [Windows SDK](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/). + * If this step is + * skipped, ignore any signature-related warning from postject. + * ```powershell + * signtool remove /s hello.exe + * ``` + * 6. Inject the blob into the copied binary by running `postject` with + * the following options: + * * `hello` / `hello.exe` \- The name of the copy of the `node` executable + * created in step 4. + * * `NODE_SEA_BLOB` \- The name of the resource / note / section in the binary + * where the contents of the blob will be stored. + * * `sea-prep.blob` \- The name of the blob created in step 1. + * * `--sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2` \- The [fuse](https://www.electronjs.org/docs/latest/tutorial/fuses) used by the Node.js project to detect if a file has been + * injected. + * * `--macho-segment-name NODE_SEA` (only needed on macOS) - The name of the + * segment in the binary where the contents of the blob will be + * stored. + * To summarize, here is the required command for each platform: + * * On Linux: + * ```bash + * npx postject hello NODE_SEA_BLOB sea-prep.blob \ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On Windows - PowerShell: + * ```powershell + * npx postject hello.exe NODE_SEA_BLOB sea-prep.blob ` + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On Windows - Command Prompt: + * ```text + * npx postject hello.exe NODE_SEA_BLOB sea-prep.blob ^ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On macOS: + * ```bash + * npx postject hello NODE_SEA_BLOB sea-prep.blob \ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 \ + * --macho-segment-name NODE_SEA + * ``` + * 7. Sign the binary (macOS and Windows only): + * * On macOS: + * ```bash + * codesign --sign - hello + * ``` + * * On Windows (optional): + * A certificate needs to be present for this to work. However, the unsigned + * binary would still be runnable. + * ```powershell + * signtool sign /fd SHA256 hello.exe + * ``` + * 8. Run the binary: + * * On systems other than Windows + * ```console + * $ ./hello world + * Hello, world! + * ``` + * * On Windows + * ```console + * $ .\hello.exe world + * Hello, world! + * ``` + * @since v19.7.0, v18.16.0 + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v20.12.0/src/node_sea.cc) + */ +declare module "node:sea" { + type AssetKey = string; + /** + * @since v20.12.0 + * @return Whether this script is running inside a single-executable application. + */ + function isSea(): boolean; + /** + * This method can be used to retrieve the assets configured to be bundled into the + * single-executable application at build time. + * An error is thrown when no matching asset can be found. + * @since v20.12.0 + */ + function getAsset(key: AssetKey): ArrayBuffer; + function getAsset(key: AssetKey, encoding: string): string; + /** + * Similar to `sea.getAsset()`, but returns the result in a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob). + * An error is thrown when no matching asset can be found. + * @since v20.12.0 + */ + function getAssetAsBlob(key: AssetKey, options?: { + type: string; + }): Blob; + /** + * This method can be used to retrieve the assets configured to be bundled into the + * single-executable application at build time. + * An error is thrown when no matching asset can be found. + * + * Unlike `sea.getRawAsset()` or `sea.getAssetAsBlob()`, this method does not + * return a copy. Instead, it returns the raw asset bundled inside the executable. + * + * For now, users should avoid writing to the returned array buffer. If the + * injected section is not marked as writable or not aligned properly, + * writes to the returned array buffer is likely to result in a crash. + * @since v20.12.0 + */ + function getRawAsset(key: AssetKey): string | ArrayBuffer; +} diff --git a/node_modules/@types/node/stream.d.ts b/node_modules/@types/node/stream.d.ts index 947a0193f489237de1902e06faaefad02fa085dd..fbcd37d3f160bd3b4e86ebec6d4fbdb9c6806940 100644 --- a/node_modules/@types/node/stream.d.ts +++ b/node_modules/@types/node/stream.d.ts @@ -2,9 +2,10 @@ * A stream is an abstract interface for working with streaming data in Node.js. * The `node:stream` module provides an API for implementing the stream interface. * - * There are many stream objects provided by Node.js. For instance, a `request to an HTTP server` and `process.stdout` are both stream instances. + * There are many stream objects provided by Node.js. For instance, a [request to an HTTP server](https://nodejs.org/docs/latest-v20.x/api/http.html#class-httpincomingmessage) + * and [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) are both stream instances. * - * Streams can be readable, writable, or both. All streams are instances of `EventEmitter`. + * Streams can be readable, writable, or both. All streams are instances of [`EventEmitter`](https://nodejs.org/docs/latest-v20.x/api/events.html#class-eventemitter). * * To access the `node:stream` module: * @@ -14,7 +15,7 @@ * * The `node:stream` module is useful for creating new types of stream instances. * It is usually not necessary to use the `node:stream` module to consume streams. - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/stream.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/stream.js) */ declare module "stream" { import { Abortable, EventEmitter } from "node:events"; @@ -41,14 +42,20 @@ declare module "stream" { import Readable = internal.Readable; import ReadableOptions = internal.ReadableOptions; interface ArrayOptions { - /** the maximum concurrent invocations of `fn` to call on the stream at once. **Default: 1**. */ + /** + * The maximum concurrent invocations of `fn` to call on the stream at once. + * @default 1 + */ concurrency?: number; - /** allows destroying the stream if the signal is aborted. */ + /** Allows destroying the stream if the signal is aborted. */ signal?: AbortSignal; } class ReadableBase extends Stream implements NodeJS.ReadableStream { /** * A utility method for creating Readable Streams out of iterators. + * @since v12.3.0, v10.17.0 + * @param iterable Object implementing the `Symbol.asyncIterator` or `Symbol.iterator` iterable protocol. Emits an 'error' event if a null value is passed. + * @param options Options provided to `new stream.Readable([options])`. By default, `Readable.from()` will set `options.objectMode` to `true`, unless this is explicitly opted out by setting `options.objectMode` to `false`. */ static from(iterable: Iterable | AsyncIterable, options?: ReadableOptions): Readable; /** @@ -63,7 +70,7 @@ declare module "stream" { */ readonly readableAborted: boolean; /** - * Is `true` if it is safe to call `readable.read()`, which means + * Is `true` if it is safe to call {@link read}, which means * the stream has not been destroyed or emitted `'error'` or `'end'`. * @since v11.4.0 */ @@ -75,18 +82,18 @@ declare module "stream" { */ readonly readableDidRead: boolean; /** - * Getter for the property `encoding` of a given `Readable` stream. The `encoding`property can be set using the `readable.setEncoding()` method. + * Getter for the property `encoding` of a given `Readable` stream. The `encoding` property can be set using the {@link setEncoding} method. * @since v12.7.0 */ readonly readableEncoding: BufferEncoding | null; /** - * Becomes `true` when `'end'` event is emitted. + * Becomes `true` when [`'end'`](https://nodejs.org/docs/latest-v20.x/api/stream.html#event-end) event is emitted. * @since v12.9.0 */ readonly readableEnded: boolean; /** * This property reflects the current state of a `Readable` stream as described - * in the `Three states` section. + * in the [Three states](https://nodejs.org/docs/latest-v20.x/api/stream.html#three-states) section. * @since v9.4.0 */ readonly readableFlowing: boolean | null; @@ -132,9 +139,10 @@ declare module "stream" { * specified using the `readable.setEncoding()` method or the stream is operating * in object mode. * - * The optional `size` argument specifies a specific number of bytes to read. If`size` bytes are not available to be read, `null` will be returned _unless_the stream has ended, in which - * case all of the data remaining in the internal - * buffer will be returned. + * The optional `size` argument specifies a specific number of bytes to read. If + * `size` bytes are not available to be read, `null` will be returned _unless_ the + * stream has ended, in which case all of the data remaining in the internal buffer + * will be returned. * * If the `size` argument is not specified, all of the data contained in the * internal buffer will be returned. @@ -191,7 +199,7 @@ declare module "stream" { * ``` * * A `Readable` stream in object mode will always return a single item from - * a call to `readable.read(size)`, regardless of the value of the`size` argument. + * a call to `readable.read(size)`, regardless of the value of the `size` argument. * * If the `readable.read()` method returns a chunk of data, a `'data'` event will * also be emitted. @@ -206,9 +214,9 @@ declare module "stream" { * The `readable.setEncoding()` method sets the character encoding for * data read from the `Readable` stream. * - * By default, no encoding is assigned and stream data will be returned as`Buffer` objects. Setting an encoding causes the stream data - * to be returned as strings of the specified encoding rather than as `Buffer`objects. For instance, calling `readable.setEncoding('utf8')` will cause the - * output data to be interpreted as UTF-8 data, and passed as strings. Calling`readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal + * By default, no encoding is assigned and stream data will be returned as `Buffer` objects. Setting an encoding causes the stream data + * to be returned as strings of the specified encoding rather than as `Buffer` objects. For instance, calling `readable.setEncoding('utf8')` will cause the + * output data to be interpreted as UTF-8 data, and passed as strings. Calling `readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal * string format. * * The `Readable` stream will properly handle multi-byte characters delivered @@ -245,7 +253,7 @@ declare module "stream" { * }); * ``` * - * The `readable.pause()` method has no effect if there is a `'readable'`event listener. + * The `readable.pause()` method has no effect if there is a `'readable'` event listener. * @since v0.9.4 */ pause(): this; @@ -264,14 +272,14 @@ declare module "stream" { * }); * ``` * - * The `readable.resume()` method has no effect if there is a `'readable'`event listener. + * The `readable.resume()` method has no effect if there is a `'readable'` event listener. * @since v0.9.4 */ resume(): this; /** - * The `readable.isPaused()` method returns the current operating state of the`Readable`. This is used primarily by the mechanism that underlies the`readable.pipe()` method. In most - * typical cases, there will be no reason to - * use this method directly. + * The `readable.isPaused()` method returns the current operating state of the `Readable`. + * This is used primarily by the mechanism that underlies the `readable.pipe()` method. + * In most typical cases, there will be no reason to use this method directly. * * ```js * const readable = new stream.Readable(); @@ -373,16 +381,16 @@ declare module "stream" { * however it is best to simply avoid calling `readable.unshift()` while in the * process of performing a read. * @since v0.9.11 - * @param chunk Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer`, `Uint8Array`, or `null`. For object mode - * streams, `chunk` may be any JavaScript value. + * @param chunk Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must + * be a {string}, {Buffer}, {TypedArray}, {DataView} or `null`. For object mode streams, `chunk` may be any JavaScript value. * @param encoding Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`. */ unshift(chunk: any, encoding?: BufferEncoding): void; /** - * Prior to Node.js 0.10, streams did not implement the entire `node:stream`module API as it is currently defined. (See `Compatibility` for more + * Prior to Node.js 0.10, streams did not implement the entire `node:stream` module API as it is currently defined. (See `Compatibility` for more * information.) * - * When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the`readable.wrap()` method can be used to create a `Readable` + * When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the `readable.wrap()` method can be used to create a `Readable` * stream that uses * the old stream as its data source. * @@ -565,8 +573,8 @@ declare module "stream" { ): Promise; _destroy(error: Error | null, callback: (error?: Error | null) => void): void; /** - * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'`event (unless `emitClose` is set to `false`). After this call, the readable - * stream will release any internal resources and subsequent calls to `push()`will be ignored. + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'` event (unless `emitClose` is set to `false`). After this call, the readable + * stream will release any internal resources and subsequent calls to `push()` will be ignored. * * Once `destroy()` has been called any further calls will be a no-op and no * further errors except from `_destroy()` may be emitted as `'error'`. @@ -731,7 +739,7 @@ declare module "stream" { * first argument. The `callback` is called asynchronously and before `'error'` is * emitted. * - * The return value is `true` if the internal buffer is less than the`highWaterMark` configured when the stream was created after admitting `chunk`. + * The return value is `true` if the internal buffer is less than the `highWaterMark` configured when the stream was created after admitting `chunk`. * If `false` is returned, further attempts to write data to the stream should * stop until the `'drain'` event is emitted. * @@ -774,8 +782,8 @@ declare module "stream" { * * A `Writable` stream in object mode will always ignore the `encoding` argument. * @since v0.9.4 - * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any - * JavaScript value other than `null`. + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a {string}, {Buffer}, + * {TypedArray} or {DataView}. For object mode streams, `chunk` may be any JavaScript value other than `null`. * @param [encoding='utf8'] The encoding, if `chunk` is a string. * @param callback Callback for when this chunk of data is flushed. * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. @@ -805,8 +813,8 @@ declare module "stream" { * // Writing more now is not allowed! * ``` * @since v0.9.4 - * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any - * JavaScript value other than `null`. + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a {string}, {Buffer}, + * {TypedArray} or {DataView}. For object mode streams, `chunk` may be any JavaScript value other than `null`. * @param encoding The encoding if `chunk` is a string * @param callback Callback for when the stream is finished. */ @@ -819,10 +827,10 @@ declare module "stream" { * * The primary intent of `writable.cork()` is to accommodate a situation in which * several small chunks are written to the stream in rapid succession. Instead of - * immediately forwarding them to the underlying destination, `writable.cork()`buffers all the chunks until `writable.uncork()` is called, which will pass them + * immediately forwarding them to the underlying destination, `writable.cork()` buffers all the chunks until `writable.uncork()` is called, which will pass them * all to `writable._writev()`, if present. This prevents a head-of-line blocking * situation where data is being buffered while waiting for the first small chunk - * to be processed. However, use of `writable.cork()` without implementing`writable._writev()` may have an adverse effect on throughput. + * to be processed. However, use of `writable.cork()` without implementing `writable._writev()` may have an adverse effect on throughput. * * See also: `writable.uncork()`, `writable._writev()`. * @since v0.11.2 @@ -832,7 +840,7 @@ declare module "stream" { * The `writable.uncork()` method flushes all data buffered since {@link cork} was called. * * When using `writable.cork()` and `writable.uncork()` to manage the buffering - * of writes to a stream, defer calls to `writable.uncork()` using`process.nextTick()`. Doing so allows batching of all`writable.write()` calls that occur within a given Node.js event + * of writes to a stream, defer calls to `writable.uncork()` using `process.nextTick()`. Doing so allows batching of all `writable.write()` calls that occur within a given Node.js event * loop phase. * * ```js @@ -863,10 +871,10 @@ declare module "stream" { */ uncork(): void; /** - * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'`event (unless `emitClose` is set to `false`). After this call, the writable + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'` event (unless `emitClose` is set to `false`). After this call, the writable * stream has ended and subsequent calls to `write()` or `end()` will result in * an `ERR_STREAM_DESTROYED` error. - * This is a destructive and immediate way to destroy a stream. Previous calls to`write()` may not have drained, and may trigger an `ERR_STREAM_DESTROYED` error. + * This is a destructive and immediate way to destroy a stream. Previous calls to `write()` may not have drained, and may trigger an `ERR_STREAM_DESTROYED` error. * Use `end()` instead of destroy if data should flush before close, or wait for * the `'drain'` event before destroying the stream. * @@ -1061,8 +1069,8 @@ declare module "stream" { * readable side ends. Set initially by the `allowHalfOpen` constructor option, * which defaults to `true`. * - * This can be changed manually to change the half-open behavior of an existing`Duplex` stream instance, but must be changed before the `'end'` event is - * emitted. + * This can be changed manually to change the half-open behavior of an existing + * `Duplex` stream instance, but must be changed before the `'end'` event is emitted. * @since v0.9.4 */ allowHalfOpen: boolean; @@ -1283,7 +1291,7 @@ declare module "stream" { } /** * The `stream.PassThrough` class is a trivial implementation of a `Transform` stream that simply passes the input bytes across to the output. Its purpose is - * primarily for examples and testing, but there are some use cases where`stream.PassThrough` is useful as a building block for novel sorts of streams. + * primarily for examples and testing, but there are some use cases where `stream.PassThrough` is useful as a building block for novel sorts of streams. */ class PassThrough extends Transform {} /** @@ -1292,8 +1300,8 @@ declare module "stream" { * Attaches an AbortSignal to a readable or writeable stream. This lets code * control stream destruction using an `AbortController`. * - * Calling `abort` on the `AbortController` corresponding to the passed`AbortSignal` will behave the same way as calling `.destroy(new AbortError())`on the stream, and `controller.error(new - * AbortError())` for webstreams. + * Calling `abort` on the `AbortController` corresponding to the passed `AbortSignal` will behave the same way as calling `.destroy(new AbortError())` on the + * stream, and `controller.error(new AbortError())` for webstreams. * * ```js * const fs = require('node:fs'); @@ -1363,20 +1371,18 @@ declare module "stream" { * ``` * @since v15.4.0 * @param signal A signal representing possible cancellation - * @param stream a stream to attach a signal to + * @param stream A stream to attach a signal to. */ function addAbortSignal(signal: AbortSignal, stream: T): T; /** * Returns the default highWaterMark used by streams. * Defaults to `16384` (16 KiB), or `16` for `objectMode`. * @since v19.9.0 - * @param objectMode */ function getDefaultHighWaterMark(objectMode: boolean): number; /** * Sets the default highWaterMark used by streams. * @since v19.9.0 - * @param objectMode * @param value highWaterMark value */ function setDefaultHighWaterMark(objectMode: boolean, value: number): void; @@ -1409,11 +1415,11 @@ declare module "stream" { * ``` * * Especially useful in error handling scenarios where a stream is destroyed - * prematurely (like an aborted HTTP request), and will not emit `'end'`or `'finish'`. + * prematurely (like an aborted HTTP request), and will not emit `'end'` or `'finish'`. * - * The `finished` API provides `promise version`. + * The `finished` API provides [`promise version`](https://nodejs.org/docs/latest-v20.x/api/stream.html#streamfinishedstream-options). * - * `stream.finished()` leaves dangling event listeners (in particular`'error'`, `'end'`, `'finish'` and `'close'`) after `callback` has been + * `stream.finished()` leaves dangling event listeners (in particular `'error'`, `'end'`, `'finish'` and `'close'`) after `callback` has been * invoked. The reason for this is so that unexpected `'error'` events (due to * incorrect stream implementations) do not cause unexpected crashes. * If this is unwanted behavior then the returned cleanup function needs to be @@ -1428,7 +1434,7 @@ declare module "stream" { * @since v10.0.0 * @param stream A readable and/or writable stream. * @param callback A callback function that takes an optional error argument. - * @return A cleanup function which removes all registered listeners. + * @returns A cleanup function which removes all registered listeners. */ function finished( stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, @@ -1499,7 +1505,7 @@ declare module "stream" { * ); * ``` * - * The `pipeline` API provides a `promise version`. + * The `pipeline` API provides a [`promise version`](https://nodejs.org/docs/latest-v20.x/api/stream.html#streampipelinesource-transforms-destination-options). * * `stream.pipeline()` will call `stream.destroy(err)` on all streams except: * @@ -1539,7 +1545,7 @@ declare module "stream" { function pipeline, B extends PipelineDestination>( source: A, destination: B, - callback?: PipelineCallback, + callback: PipelineCallback, ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; function pipeline< A extends PipelineSource, @@ -1549,7 +1555,7 @@ declare module "stream" { source: A, transform1: T1, destination: B, - callback?: PipelineCallback, + callback: PipelineCallback, ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; function pipeline< A extends PipelineSource, @@ -1561,7 +1567,7 @@ declare module "stream" { transform1: T1, transform2: T2, destination: B, - callback?: PipelineCallback, + callback: PipelineCallback, ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; function pipeline< A extends PipelineSource, @@ -1575,7 +1581,7 @@ declare module "stream" { transform2: T2, transform3: T3, destination: B, - callback?: PipelineCallback, + callback: PipelineCallback, ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; function pipeline< A extends PipelineSource, @@ -1591,11 +1597,11 @@ declare module "stream" { transform3: T3, transform4: T4, destination: B, - callback?: PipelineCallback, + callback: PipelineCallback, ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; function pipeline( streams: ReadonlyArray, - callback?: (err: NodeJS.ErrnoException | null) => void, + callback: (err: NodeJS.ErrnoException | null) => void, ): NodeJS.WritableStream; function pipeline( stream1: NodeJS.ReadableStream, diff --git a/node_modules/@types/node/stream/web.d.ts b/node_modules/@types/node/stream/web.d.ts index 361594dfaf7774fde49f749c51b12c7dd177381e..8dd0ded35ed885f989bc2afdd39f611967f70dac 100644 --- a/node_modules/@types/node/stream/web.d.ts +++ b/node_modules/@types/node/stream/web.d.ts @@ -156,6 +156,7 @@ declare module "stream/web" { } const ReadableStream: { prototype: ReadableStream; + from(iterable: Iterable | AsyncIterable): ReadableStream; new(underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; new(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; }; @@ -350,7 +351,7 @@ declare module "stream/web" { } const CompressionStream: { prototype: CompressionStream; - new(format: string): CompressionStream; + new(format: "deflate" | "deflate-raw" | "gzip"): CompressionStream; }; interface DecompressionStream { readonly readable: ReadableStream; @@ -358,7 +359,7 @@ declare module "stream/web" { } const DecompressionStream: { prototype: DecompressionStream; - new(format: string): DecompressionStream; + new(format: "deflate" | "deflate-raw" | "gzip"): DecompressionStream; }; } declare module "node:stream/web" { diff --git a/node_modules/@types/node/string_decoder.d.ts b/node_modules/@types/node/string_decoder.d.ts index b8691e1f060076e08ed0f023889adef0f2e8fb4e..9c9d827b6e7dca42d0e6dacf68bff5aa547a02b8 100644 --- a/node_modules/@types/node/string_decoder.d.ts +++ b/node_modules/@types/node/string_decoder.d.ts @@ -36,7 +36,7 @@ * decoder.write(Buffer.from([0x82])); * console.log(decoder.end(Buffer.from([0xAC]))); // Prints: € * ``` - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/string_decoder.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/string_decoder.js) */ declare module "string_decoder" { class StringDecoder { @@ -44,22 +44,22 @@ declare module "string_decoder" { /** * Returns a decoded string, ensuring that any incomplete multibyte characters at * the end of the `Buffer`, or `TypedArray`, or `DataView` are omitted from the - * returned string and stored in an internal buffer for the next call to`stringDecoder.write()` or `stringDecoder.end()`. + * returned string and stored in an internal buffer for the next call to `stringDecoder.write()` or `stringDecoder.end()`. * @since v0.1.99 * @param buffer The bytes to decode. */ - write(buffer: Buffer): string; + write(buffer: string | Buffer | NodeJS.ArrayBufferView): string; /** * Returns any remaining input stored in the internal buffer as a string. Bytes * representing incomplete UTF-8 and UTF-16 characters will be replaced with * substitution characters appropriate for the character encoding. * - * If the `buffer` argument is provided, one final call to `stringDecoder.write()`is performed before returning the remaining input. + * If the `buffer` argument is provided, one final call to `stringDecoder.write()` is performed before returning the remaining input. * After `end()` is called, the `stringDecoder` object can be reused for new input. * @since v0.9.3 * @param buffer The bytes to decode. */ - end(buffer?: Buffer): string; + end(buffer?: string | Buffer | NodeJS.ArrayBufferView): string; } } declare module "node:string_decoder" { diff --git a/node_modules/@types/node/test.d.ts b/node_modules/@types/node/test.d.ts index 149c9e0b77671ac4cfd8a7cc0c3b9310f786c6fd..88903dea49dcc3f8b35fddf0c8e66315c31d986b 100644 --- a/node_modules/@types/node/test.d.ts +++ b/node_modules/@types/node/test.d.ts @@ -18,14 +18,14 @@ * * 1. A synchronous function that is considered failing if it throws an exception, * and is considered passing otherwise. - * 2. A function that returns a `Promise` that is considered failing if the`Promise` rejects, and is considered passing if the `Promise` fulfills. + * 2. A function that returns a `Promise` that is considered failing if the `Promise` rejects, and is considered passing if the `Promise` fulfills. * 3. A function that receives a callback function. If the callback receives any * truthy value as its first argument, the test is considered failing. If a * falsy value is passed as the first argument to the callback, the test is * considered passing. If the test function receives a callback function and * also returns a `Promise`, the test will fail. * - * The following example illustrates how tests are written using the`test` module. + * The following example illustrates how tests are written using the `test` module. * * ```js * test('synchronous passing test', (t) => { @@ -76,13 +76,13 @@ * * If any tests fail, the process exit code is set to `1`. * @since v18.0.0, v16.17.0 - * @see [source](https://github.com/nodejs/node/blob/v20.4.0/lib/test.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/test.js) */ declare module "node:test" { import { Readable } from "node:stream"; import { AsyncResource } from "node:async_hooks"; /** - * **Note:**`shard` is used to horizontally parallelize test running across + * **Note:** `shard` is used to horizontally parallelize test running across * machines or processes, ideal for large-scale executions across varied * environments. It's incompatible with `watch` mode, tailored for rapid * code iteration by automatically rerunning tests on file changes. @@ -110,7 +110,7 @@ declare module "node:test" { * additional diagnostic information, or creating subtests. * * `test()` returns a `Promise` that fulfills once the test completes. - * if `test()` is called within a `describe()` block, it fulfills immediately. + * if `test()` is called within a suite, it fulfills immediately. * The return value can usually be discarded for top level tests. * However, the return value from subtests should be used to prevent the parent * test from finishing first and cancelling the subtest @@ -129,15 +129,15 @@ declare module "node:test" { * }); * ``` * - * The `timeout` option can be used to fail the test if it takes longer than`timeout` milliseconds to complete. However, it is not a reliable mechanism for + * The `timeout` option can be used to fail the test if it takes longer than `timeout` milliseconds to complete. However, it is not a reliable mechanism for * canceling tests because a running test might block the application thread and * thus prevent the scheduled cancellation. * @since v18.0.0, v16.17.0 * @param [name='The name'] The name of the test, which is displayed when reporting test results. * @param options Configuration options for the test. The following properties are supported: - * @param [fn='A no-op function'] The function under test. The first argument to this function is a {@link TestContext} object. If the test uses callbacks, the callback function is passed as the - * second argument. - * @return Fulfilled with `undefined` once the test completes, or immediately if the test runs within {@link describe}. + * @param [fn='A no-op function'] The function under test. The first argument to this function is a {@link TestContext} object. If the test uses callbacks, the + * callback function is passed as the second argument. + * @return Fulfilled with `undefined` once the test completes, or immediately if the test runs within a suite. */ function test(name?: string, fn?: TestFn): Promise; function test(name?: string, options?: TestOptions, fn?: TestFn): Promise; @@ -147,14 +147,47 @@ declare module "node:test" { export { after, afterEach, before, beforeEach, describe, it, mock, only, run, skip, test, todo }; } /** - * The `describe()` function imported from the `node:test` module. Each - * invocation of this function results in the creation of a Subtest. - * After invocation of top level `describe` functions, - * all top level tests and suites will execute. - * @param [name='The name'] The name of the suite, which is displayed when reporting test results. - * @param options Configuration options for the suite. supports the same options as `test([name][, options][, fn])`. - * @param [fn='A no-op function'] The function under suite declaring all subtests and subsuites. The first argument to this function is a {@link SuiteContext} object. + * The `suite()` function is imported from the `node:test` module. + * @param name The name of the suite, which is displayed when reporting test results. **Default:** The `name` property of `fn`, or `''` if `fn` does not have a name. + * @param options Optional configuration options for the suite. This supports the same options as `test([name][, options][, fn])`. + * @param [fn='A no-op function'] The suite function declaring nested tests and suites. The first argument to this function is a `{@link SuiteContext}` object. * @return Immediately fulfilled with `undefined`. + * @since v20.13.0 + */ + function suite(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function suite(name?: string, fn?: SuiteFn): Promise; + function suite(options?: TestOptions, fn?: SuiteFn): Promise; + function suite(fn?: SuiteFn): Promise; + namespace suite { + /** + * Shorthand for skipping a suite. This is the same as [`suite([name], { skip: true }[, fn])`](https://nodejs.org/docs/latest-v20.x/api/test.html#suitename-options-fn). + * @since v20.13.0 + */ + function skip(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function skip(name?: string, fn?: SuiteFn): Promise; + function skip(options?: TestOptions, fn?: SuiteFn): Promise; + function skip(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `TODO`. This is the same as [`suite([name], { todo: true }[, fn])`](https://nodejs.org/docs/latest-v20.x/api/test.html#suitename-options-fn). + * @since v20.13.0 + */ + function todo(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function todo(name?: string, fn?: SuiteFn): Promise; + function todo(options?: TestOptions, fn?: SuiteFn): Promise; + function todo(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `only`. This is the same as [`suite([name], { only: true }[, fn])`](https://nodejs.org/docs/latest-v20.x/api/test.html#suitename-options-fn). + * @since v20.13.0 + */ + function only(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function only(name?: string, fn?: SuiteFn): Promise; + function only(options?: TestOptions, fn?: SuiteFn): Promise; + function only(fn?: SuiteFn): Promise; + } + /** + * Alias for `{@link suite}`. + * + * The `describe()` function is imported from the `node:test` module. */ function describe(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; function describe(name?: string, fn?: SuiteFn): Promise; @@ -162,21 +195,23 @@ declare module "node:test" { function describe(fn?: SuiteFn): Promise; namespace describe { /** - * Shorthand for skipping a suite, same as `describe([name], { skip: true }[, fn])`. + * Shorthand for skipping a suite. This is the same as [`describe([name], { skip: true }[, fn])`](https://nodejs.org/docs/latest-v20.x/api/test.html#describename-options-fn). + * @since v18.15.0 */ function skip(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; function skip(name?: string, fn?: SuiteFn): Promise; function skip(options?: TestOptions, fn?: SuiteFn): Promise; function skip(fn?: SuiteFn): Promise; /** - * Shorthand for marking a suite as `TODO`, same as `describe([name], { todo: true }[, fn])`. + * Shorthand for marking a suite as `TODO`. This is the same as [`describe([name], { todo: true }[, fn])`](https://nodejs.org/docs/latest-v20.x/api/test.html#describename-options-fn). + * @since v18.15.0 */ function todo(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; function todo(name?: string, fn?: SuiteFn): Promise; function todo(options?: TestOptions, fn?: SuiteFn): Promise; function todo(fn?: SuiteFn): Promise; /** - * Shorthand for marking a suite as `only`, same as `describe([name], { only: true }[, fn])`. + * Shorthand for marking a suite as `only`. This is the same as [`describe([name], { only: true }[, fn])`](https://nodejs.org/docs/latest-v20.x/api/test.html#describename-options-fn). * @since v18.15.0 */ function only(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; @@ -185,7 +220,7 @@ declare module "node:test" { function only(fn?: SuiteFn): Promise; } /** - * Shorthand for `test()`. + * Alias for `test()`. * * The `it()` function is imported from the `node:test` module. * @since v18.6.0, v16.17.0 @@ -264,49 +299,57 @@ declare module "node:test" { } interface RunOptions { /** - * If a number is provided, then that many files would run in parallel. - * If truthy, it would run (number of cpu cores - 1) files in parallel. - * If falsy, it would only run one file at a time. - * If unspecified, subtests inherit this value from their parent. - * @default true + * If a number is provided, then that many test processes would run in parallel, where each process corresponds to one test file. + * If `true`, it would run `os.availableParallelism() - 1` test files in parallel. If `false`, it would only run one test file at a time. + * @default false */ concurrency?: number | boolean | undefined; /** - * An array containing the list of files to run. - * If unspecified, the test runner execution model will be used. + * An array containing the list of files to run. **Default** matching files from + * [test runner execution model](https://nodejs.org/docs/latest-v20.x/api/test.html#test-runner-execution-model). */ files?: readonly string[] | undefined; /** - * Allows aborting an in-progress test execution. - * @default undefined - */ - signal?: AbortSignal | undefined; - /** - * A number of milliseconds the test will fail after. - * If unspecified, subtests inherit this value from their parent. - * @default Infinity + * Configures the test runner to exit the process once all known + * tests have finished executing even if the event loop would + * otherwise remain active. + * @default false */ - timeout?: number | undefined; + forceExit?: boolean | undefined; /** * Sets inspector port of test child process. * If a nullish value is provided, each process gets its own port, * incremented from the primary's `process.debugPort`. + * @default undefined */ inspectPort?: number | (() => number) | undefined; - /** - * That can be used to only run tests whose name matches the provided pattern. - * Test name patterns are interpreted as JavaScript regular expressions. - * For each test that is executed, any corresponding test hooks, such as `beforeEach()`, are also run. - */ - testNamePatterns?: string | RegExp | string[] | RegExp[]; /** * If truthy, the test context will only run tests that have the `only` option set */ only?: boolean; /** - * A function that accepts the TestsStream instance and can be used to setup listeners before any tests are run. + * A function that accepts the `TestsStream` instance and can be used to setup listeners before any tests are run. + * @default undefined */ setup?: (root: Test) => void | Promise; + /** + * Allows aborting an in-progress test execution. + */ + signal?: AbortSignal | undefined; + /** + * A String, RegExp or a RegExp Array, that can be used to only run tests whose + * name matches the provided pattern. Test name patterns are interpreted as JavaScript + * regular expressions. For each test that is executed, any corresponding test hooks, + * such as `beforeEach()`, are also run. + * @default undefined + */ + testNamePatterns?: string | RegExp | string[] | RegExp[]; + /** + * A number of milliseconds the test execution will fail after. + * If unspecified, subtests inherit this value from their parent. + * @default Infinity + */ + timeout?: number | undefined; /** * Whether to run in watch mode or not. * @default false @@ -328,12 +371,18 @@ declare module "node:test" { timeout: number | null; } /** - * A successful call to `run()` method will return a new `TestsStream` object, streaming a series of events representing the execution of the tests.`TestsStream` will emit events, in the + * A successful call to `run()` method will return a new `TestsStream` object, streaming a series of events representing the execution of the tests. `TestsStream` will emit events, in the * order of the tests definition + * + * Some of the events are guaranteed to be emitted in the same order as the tests are defined, while others are emitted in the order that the tests execute. * @since v18.9.0, v16.19.0 */ class TestsStream extends Readable implements NodeJS.ReadableStream { + addListener(event: "test:coverage", listener: (data: TestCoverage) => void): this; + addListener(event: "test:complete", listener: (data: TestComplete) => void): this; + addListener(event: "test:dequeue", listener: (data: TestDequeue) => void): this; addListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + addListener(event: "test:enqueue", listener: (data: TestEnqueue) => void): this; addListener(event: "test:fail", listener: (data: TestFail) => void): this; addListener(event: "test:pass", listener: (data: TestPass) => void): this; addListener(event: "test:plan", listener: (data: TestPlan) => void): this; @@ -341,7 +390,11 @@ declare module "node:test" { addListener(event: "test:stderr", listener: (data: TestStderr) => void): this; addListener(event: "test:stdout", listener: (data: TestStdout) => void): this; addListener(event: string, listener: (...args: any[]) => void): this; + emit(event: "test:coverage", data: TestCoverage): boolean; + emit(event: "test:complete", data: TestComplete): boolean; + emit(event: "test:dequeue", data: TestDequeue): boolean; emit(event: "test:diagnostic", data: DiagnosticData): boolean; + emit(event: "test:enqueue", data: TestEnqueue): boolean; emit(event: "test:fail", data: TestFail): boolean; emit(event: "test:pass", data: TestPass): boolean; emit(event: "test:plan", data: TestPlan): boolean; @@ -349,7 +402,11 @@ declare module "node:test" { emit(event: "test:stderr", data: TestStderr): boolean; emit(event: "test:stdout", data: TestStdout): boolean; emit(event: string | symbol, ...args: any[]): boolean; + on(event: "test:coverage", listener: (data: TestCoverage) => void): this; + on(event: "test:complete", listener: (data: TestComplete) => void): this; + on(event: "test:dequeue", listener: (data: TestDequeue) => void): this; on(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + on(event: "test:enqueue", listener: (data: TestEnqueue) => void): this; on(event: "test:fail", listener: (data: TestFail) => void): this; on(event: "test:pass", listener: (data: TestPass) => void): this; on(event: "test:plan", listener: (data: TestPlan) => void): this; @@ -357,7 +414,11 @@ declare module "node:test" { on(event: "test:stderr", listener: (data: TestStderr) => void): this; on(event: "test:stdout", listener: (data: TestStdout) => void): this; on(event: string, listener: (...args: any[]) => void): this; + once(event: "test:coverage", listener: (data: TestCoverage) => void): this; + once(event: "test:complete", listener: (data: TestComplete) => void): this; + once(event: "test:dequeue", listener: (data: TestDequeue) => void): this; once(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + once(event: "test:enqueue", listener: (data: TestEnqueue) => void): this; once(event: "test:fail", listener: (data: TestFail) => void): this; once(event: "test:pass", listener: (data: TestPass) => void): this; once(event: "test:plan", listener: (data: TestPlan) => void): this; @@ -365,7 +426,11 @@ declare module "node:test" { once(event: "test:stderr", listener: (data: TestStderr) => void): this; once(event: "test:stdout", listener: (data: TestStdout) => void): this; once(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "test:coverage", listener: (data: TestCoverage) => void): this; + prependListener(event: "test:complete", listener: (data: TestComplete) => void): this; + prependListener(event: "test:dequeue", listener: (data: TestDequeue) => void): this; prependListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + prependListener(event: "test:enqueue", listener: (data: TestEnqueue) => void): this; prependListener(event: "test:fail", listener: (data: TestFail) => void): this; prependListener(event: "test:pass", listener: (data: TestPass) => void): this; prependListener(event: "test:plan", listener: (data: TestPlan) => void): this; @@ -373,7 +438,11 @@ declare module "node:test" { prependListener(event: "test:stderr", listener: (data: TestStderr) => void): this; prependListener(event: "test:stdout", listener: (data: TestStdout) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "test:coverage", listener: (data: TestCoverage) => void): this; + prependOnceListener(event: "test:complete", listener: (data: TestComplete) => void): this; + prependOnceListener(event: "test:dequeue", listener: (data: TestDequeue) => void): this; prependOnceListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + prependOnceListener(event: "test:enqueue", listener: (data: TestEnqueue) => void): this; prependOnceListener(event: "test:fail", listener: (data: TestFail) => void): this; prependOnceListener(event: "test:pass", listener: (data: TestPass) => void): this; prependOnceListener(event: "test:plan", listener: (data: TestPlan) => void): this; @@ -392,7 +461,7 @@ declare module "node:test" { /** * This function is used to create a hook running before subtest of the current test. * @param fn The hook function. If the hook uses callbacks, the callback function is passed as - * the second argument. Default: A no-op function. + * the second argument. **Default:** A no-op function. * @param options Configuration options for the hook. * @since v20.1.0 */ @@ -400,14 +469,14 @@ declare module "node:test" { /** * This function is used to create a hook running before each subtest of the current test. * @param fn The hook function. If the hook uses callbacks, the callback function is passed as - * the second argument. Default: A no-op function. + * the second argument. **Default:** A no-op function. * @param options Configuration options for the hook. * @since v18.8.0 */ beforeEach: typeof beforeEach; /** * This function is used to create a hook that runs after the current test finishes. - * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * @param [fn='A no-op function'] The hook function. If the hook uses callbacks, the callback function is passed as * the second argument. Default: A no-op function. * @param options Configuration options for the hook. * @since v18.13.0 @@ -416,7 +485,7 @@ declare module "node:test" { /** * This function is used to create a hook running after each subtest of the current test. * @param fn The hook function. If the hook uses callbacks, the callback function is passed as - * the second argument. Default: A no-op function. + * the second argument. **Default:** A no-op function. * @param options Configuration options for the hook. * @since v18.8.0 */ @@ -470,7 +539,7 @@ declare module "node:test" { */ readonly signal: AbortSignal; /** - * This function causes the test's output to indicate the test as skipped. If`message` is provided, it is included in the output. Calling `skip()` does + * This function causes the test's output to indicate the test as skipped. If `message` is provided, it is included in the output. Calling `skip()` does * not terminate execution of the test function. This function does not return a * value. * @@ -508,7 +577,7 @@ declare module "node:test" { * @param options Configuration options for the test * @param fn The function under test. This first argument to this function is a * {@link TestContext} object. If the test uses callbacks, the callback function is - * passed as the second argument. Default: A no-op function. + * passed as the second argument. **Default:** A no-op function. * @returns A {@link Promise} resolved with `undefined` once the test completes. */ test: typeof test; @@ -517,6 +586,7 @@ declare module "node:test" { */ readonly mock: MockTracker; } + /** * An instance of `SuiteContext` is passed to each suite function in order to * interact with the test runner. However, the `SuiteContext` constructor is not @@ -577,7 +647,7 @@ declare module "node:test" { todo?: boolean | string | undefined; } /** - * This function is used to create a hook running before running a suite. + * This function creates a hook that runs before executing a suite. * * ```js * describe('tests', async () => { @@ -593,7 +663,7 @@ declare module "node:test" { */ function before(fn?: HookFn, options?: HookOptions): void; /** - * This function is used to create a hook running after running a suite. + * This function creates a hook that runs after executing a suite. * * ```js * describe('tests', async () => { @@ -609,8 +679,7 @@ declare module "node:test" { */ function after(fn?: HookFn, options?: HookOptions): void; /** - * This function is used to create a hook running - * before each subtest of the current suite. + * This function creates a hook that runs before each test in the current suite. * * ```js * describe('tests', async () => { @@ -626,8 +695,8 @@ declare module "node:test" { */ function beforeEach(fn?: HookFn, options?: HookOptions): void; /** - * This function is used to create a hook running - * after each subtest of the current test. + * This function creates a hook that runs after each test in the current suite. + * The `afterEach()` hook is run even if the test fails. * * ```js * describe('tests', async () => { @@ -695,7 +764,7 @@ declare module "node:test" { /** * The `MockTracker` class is used to manage mocking functionality. The test runner * module provides a top level `mock` export which is a `MockTracker` instance. - * Each test also provides its own `MockTracker` instance via the test context's`mock` property. + * Each test also provides its own `MockTracker` instance via the test context's `mock` property. * @since v19.1.0, v18.13.0 */ class MockTracker { @@ -811,7 +880,7 @@ declare module "node:test" { ): Mock; /** - * This function is syntax sugar for `MockTracker.method` with `options.getter`set to `true`. + * This function is syntax sugar for `MockTracker.method` with `options.getter` set to `true`. * @since v19.3.0, v18.13.0 */ getter< @@ -833,7 +902,7 @@ declare module "node:test" { options?: MockFunctionOptions, ): Mock<(() => MockedObject[MethodName]) | Implementation>; /** - * This function is syntax sugar for `MockTracker.method` with `options.setter`set to `true`. + * This function is syntax sugar for `MockTracker.method` with `options.setter` set to `true`. * @since v19.3.0, v18.13.0 */ setter< @@ -856,11 +925,11 @@ declare module "node:test" { ): Mock<((value: MockedObject[MethodName]) => void) | Implementation>; /** * This function restores the default behavior of all mocks that were previously - * created by this `MockTracker` and disassociates the mocks from the`MockTracker` instance. Once disassociated, the mocks can still be used, but the`MockTracker` instance can no longer be + * created by this `MockTracker` and disassociates the mocks from the `MockTracker` instance. Once disassociated, the mocks can still be used, but the `MockTracker` instance can no longer be * used to reset their behavior or * otherwise interact with them. * - * After each test completes, this function is called on the test context's`MockTracker`. If the global `MockTracker` is used extensively, calling this + * After each test completes, this function is called on the test context's `MockTracker`. If the global `MockTracker` is used extensively, calling this * function manually is recommended. * @since v19.1.0, v18.13.0 */ @@ -926,7 +995,7 @@ declare module "node:test" { readonly calls: Array>; /** * This function returns the number of times that this mock has been invoked. This - * function is more efficient than checking `ctx.calls.length` because `ctx.calls`is a getter that creates a copy of the internal call tracking array. + * function is more efficient than checking `ctx.calls.length` because `ctx.calls` is a getter that creates a copy of the internal call tracking array. * @since v19.1.0, v18.13.0 * @return The number of times that this mock has been invoked. */ @@ -962,7 +1031,7 @@ declare module "node:test" { * @since v19.1.0, v18.13.0 * @param implementation The function to be used as the mock's new implementation. */ - mockImplementation(implementation: Function): void; + mockImplementation(implementation: F): void; /** * This function is used to change the behavior of an existing mock for a single * invocation. Once invocation `onCall` has occurred, the mock will revert to @@ -999,7 +1068,7 @@ declare module "node:test" { * @param implementation The function to be used as the mock's implementation for the invocation number specified by `onCall`. * @param onCall The invocation number that will use `implementation`. If the specified invocation has already occurred then an exception is thrown. */ - mockImplementationOnce(implementation: Function, onCall?: number): void; + mockImplementationOnce(implementation: F, onCall?: number): void; /** * Resets the call history of the mock function. * @since v19.3.0, v18.13.0 @@ -1050,7 +1119,7 @@ declare module "node:test" { * * The above example enables mocking for the `Date` constructor, `setInterval` timer and * implicitly mocks the `clearInterval` function. Only the `Date` constructor from `globalThis`, - * `setInterval` and `clearInterval` functions from `node:timers`,`node:timers/promises`, and `globalThis` will be mocked. + * `setInterval` and `clearInterval` functions from `node:timers`, `node:timers/promises`, and `globalThis` will be mocked. * * Example usage with initial time set * @@ -1075,7 +1144,9 @@ declare module "node:test" { * and `globalThis` will be mocked. * The `Date` constructor from `globalThis` will be mocked. * - * If there is no initial epoch set, the initial date will be based on 0 in the Unix epoch. This is `January 1st, 1970, 00:00:00 UTC`. You can set an initial date by passing a now property to the `.enable()` method. This value will be used as the initial date for the mocked Date object. It can either be a positive integer, or another Date object. + * If there is no initial epoch set, the initial date will be based on 0 in the Unix epoch. This is `January 1st, 1970, 00:00:00 UTC`. You can + * set an initial date by passing a now property to the `.enable()` method. This value will be used as the initial date for the mocked Date + * object. It can either be a positive integer, or another Date object. * @since v20.4.0 */ enable(options?: MockTimersOptions): void; @@ -1244,8 +1315,10 @@ declare module "node:test" { only, run, skip, + SuiteContext, test, test as default, + TestContext, todo, }; } @@ -1257,12 +1330,11 @@ interface TestLocationInfo { */ column?: number; /** - * The path of the test file, `undefined` if test is not ran through a file. + * The path of the test file, `undefined` if test was run through the REPL. */ file?: string; /** - * The line number where the test is defined, or - * `undefined` if the test was run through the REPL. + * The line number where the test is defined, or `undefined` if the test was run through the REPL. */ line?: number; } @@ -1276,6 +1348,202 @@ interface DiagnosticData extends TestLocationInfo { */ nesting: number; } +interface TestCoverage { + /** + * An object containing the coverage report. + */ + summary: { + /** + * An array of coverage reports for individual files. Each report is an object with the following schema: + */ + files: Array<{ + /** + * The absolute path of the file. + */ + path: string; + /** + * The total number of lines. + */ + totalLineCount: number; + /** + * The total number of branches. + */ + totalBranchCount: number; + /** + * The total number of functions. + */ + totalFunctionCount: number; + /** + * The number of covered lines. + */ + coveredLineCount: number; + /** + * The number of covered branches. + */ + coveredBranchCount: number; + /** + * The number of covered functions. + */ + coveredFunctionCount: number; + /** + * The percentage of lines covered. + */ + coveredLinePercent: number; + /** + * The percentage of branches covered. + */ + coveredBranchPercent: number; + /** + * The percentage of functions covered. + */ + coveredFunctionPercent: number; + /** + * An array of functions representing function coverage. + */ + functions: Array<{ + /** + * The name of the function. + */ + name: string; + /** + * The line number where the function is defined. + */ + line: number; + /** + * The number of times the function was called. + */ + count: number; + }>; + /** + * An array of lines representing line numbers and the number of times they were covered. + */ + lines: Array<{ + /** + * The line number. + */ + line: number; + /** + * The number of times the line was covered. + */ + count: number; + }>; + }>; + /** + * An object containing a summary of coverage for all files. + */ + totals: { + /** + * The total number of lines. + */ + totalLineCount: number; + /** + * The total number of branches. + */ + totalBranchCount: number; + /** + * The total number of functions. + */ + totalFunctionCount: number; + /** + * The number of covered lines. + */ + coveredLineCount: number; + /** + * The number of covered branches. + */ + coveredBranchCount: number; + /** + * The number of covered functions. + */ + coveredFunctionCount: number; + /** + * The percentage of lines covered. + */ + coveredLinePercent: number; + /** + * The percentage of branches covered. + */ + coveredBranchPercent: number; + /** + * The percentage of functions covered. + */ + coveredFunctionPercent: number; + }; + /** + * The working directory when code coverage began. This + * is useful for displaying relative path names in case + * the tests changed the working directory of the Node.js process. + */ + workingDirectory: string; + }; + /** + * The nesting level of the test. + */ + nesting: number; +} +interface TestComplete extends TestLocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * Whether the test passed or not. + */ + passed: boolean; + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * An error wrapping the error thrown by the test if it did not pass. + */ + error: Error; + /** + * The type of the test, used to denote whether this is a suite. + */ + type?: "suite"; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; +} +interface TestDequeue extends TestLocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; +} +interface TestEnqueue extends TestLocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; +} interface TestFail extends TestLocationInfo { /** * Additional execution metadata. @@ -1286,12 +1554,12 @@ interface TestFail extends TestLocationInfo { */ duration_ms: number; /** - * The error thrown by the test. + * An error wrapping the error thrown by the test if it did not pass. */ error: Error; /** * The type of the test, used to denote whether this is a suite. - * @since 20.0.0, 19.9.0, 18.17.0 + * @since v20.0.0, v19.9.0, v18.17.0 */ type?: "suite"; }; @@ -1374,36 +1642,16 @@ interface TestStart extends TestLocationInfo { } interface TestStderr extends TestLocationInfo { /** - * The message written to `stderr` + * The message written to `stderr`. */ message: string; } interface TestStdout extends TestLocationInfo { /** - * The message written to `stdout` + * The message written to `stdout`. */ message: string; } -interface TestEnqueue extends TestLocationInfo { - /** - * The test name - */ - name: string; - /** - * The nesting level of the test. - */ - nesting: number; -} -interface TestDequeue extends TestLocationInfo { - /** - * The test name - */ - name: string; - /** - * The nesting level of the test. - */ - nesting: number; -} /** * The `node:test/reporters` module exposes the builtin-reporters for `node:test`. @@ -1420,21 +1668,23 @@ interface TestDequeue extends TestLocationInfo { * import test from 'test/reporters'; * ``` * @since v19.9.0 - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/test/reporters.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/test/reporters.js) */ declare module "node:test/reporters" { import { Transform, TransformOptions } from "node:stream"; type TestEvent = + | { type: "test:coverage"; data: TestCoverage } + | { type: "test:complete"; data: TestComplete } + | { type: "test:dequeue"; data: TestDequeue } | { type: "test:diagnostic"; data: DiagnosticData } + | { type: "test:enqueue"; data: TestEnqueue } | { type: "test:fail"; data: TestFail } | { type: "test:pass"; data: TestPass } | { type: "test:plan"; data: TestPlan } | { type: "test:start"; data: TestStart } | { type: "test:stderr"; data: TestStderr } | { type: "test:stdout"; data: TestStdout } - | { type: "test:enqueue"; data: TestEnqueue } - | { type: "test:dequeue"; data: TestDequeue } | { type: "test:watch:drained" }; type TestEventGenerator = AsyncGenerator; @@ -1455,9 +1705,12 @@ declare module "node:test/reporters" { constructor(); } /** - * The `junit` reporter outputs test results in a jUnit XML format + * The `junit` reporter outputs test results in a jUnit XML format. */ function junit(source: TestEventGenerator): AsyncGenerator; + /** + * The `lcov` reporter outputs test coverage when used with the [`--experimental-test-coverage`](https://nodejs.org/docs/latest-v20.x/api/cli.html#--experimental-test-coverage) flag. + */ class Lcov extends Transform { constructor(opts?: TransformOptions); } diff --git a/node_modules/@types/node/timers.d.ts b/node_modules/@types/node/timers.d.ts index 039f31f7ad0e07c4a455b0db6204648fe0e3e8b4..5a73ca91a82eea1cacda4880aeab0b4c43ef4c80 100644 --- a/node_modules/@types/node/timers.d.ts +++ b/node_modules/@types/node/timers.d.ts @@ -6,7 +6,7 @@ * The timer functions within Node.js implement a similar API as the timers API * provided by Web Browsers but use a different internal implementation that is * built around the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout). - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/timers.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/timers.js) */ declare module "timers" { import { Abortable } from "node:events"; @@ -43,12 +43,12 @@ declare module "timers" { * actions. * * By default, when an immediate is scheduled, the Node.js event loop will continue - * running as long as the immediate is active. The `Immediate` object returned by `setImmediate()` exports both `immediate.ref()` and `immediate.unref()`functions that can be used to + * running as long as the immediate is active. The `Immediate` object returned by `setImmediate()` exports both `immediate.ref()` and `immediate.unref()` functions that can be used to * control this default behavior. */ class Immediate implements RefCounted { /** - * When called, requests that the Node.js event loop _not_ exit so long as the`Immediate` is active. Calling `immediate.ref()` multiple times will have no + * When called, requests that the Node.js event loop _not_ exit so long as the `Immediate` is active. Calling `immediate.ref()` multiple times will have no * effect. * * By default, all `Immediate` objects are "ref'ed", making it normally unnecessary @@ -100,7 +100,7 @@ declare module "timers" { /** * When called, the active `Timeout` object will not require the Node.js event loop * to remain active. If there is no other activity keeping the event loop running, - * the process may exit before the `Timeout` object's callback is invoked. Calling`timeout.unref()` multiple times will have no effect. + * the process may exit before the `Timeout` object's callback is invoked. Calling `timeout.unref()` multiple times will have no effect. * @since v0.9.1 * @return a reference to `timeout` */ @@ -138,7 +138,7 @@ declare module "timers" { * nor of their ordering. The callback will be called as close as possible to the * time specified. * - * When `delay` is larger than `2147483647` or less than `1`, the `delay`will be set to `1`. Non-integer delays are truncated to an integer. + * When `delay` is larger than `2147483647` or less than `1`, the `delay` will be set to `1`. Non-integer delays are truncated to an integer. * * If `callback` is not a function, a `TypeError` will be thrown. * diff --git a/node_modules/@types/node/timers/promises.d.ts b/node_modules/@types/node/timers/promises.d.ts index 5a54dc772dcbdb9974966bc3c5072a3e8636c0d4..50cee98b293501356b2f9140c101ccc26f3fb7a7 100644 --- a/node_modules/@types/node/timers/promises.d.ts +++ b/node_modules/@types/node/timers/promises.d.ts @@ -1,6 +1,6 @@ /** * The `timers/promises` API provides an alternative set of timer functions - * that return `Promise` objects. The API is accessible via`require('node:timers/promises')`. + * that return `Promise` objects. The API is accessible via `require('node:timers/promises')`. * * ```js * import { @@ -66,21 +66,25 @@ declare module "timers/promises" { function setInterval(delay?: number, value?: T, options?: TimerOptions): AsyncIterable; interface Scheduler { /** + * An experimental API defined by the [Scheduling APIs](https://github.com/WICG/scheduling-apis) draft specification being developed as a standard Web Platform API. + * + * Calling `timersPromises.scheduler.wait(delay, options)` is roughly equivalent to calling `timersPromises.setTimeout(delay, undefined, options)` except that the `ref` + * option is not supported. + * * ```js * import { scheduler } from 'node:timers/promises'; * * await scheduler.wait(1000); // Wait one second before continuing * ``` - * An experimental API defined by the Scheduling APIs draft specification being developed as a standard Web Platform API. - * Calling timersPromises.scheduler.wait(delay, options) is roughly equivalent to calling timersPromises.setTimeout(delay, undefined, options) except that the ref option is not supported. * @since v16.14.0 * @experimental * @param [delay=1] The number of milliseconds to wait before fulfilling the promise. */ - wait: (delay?: number, options?: TimerOptions) => Promise; + wait: (delay?: number, options?: Pick) => Promise; /** - * An experimental API defined by the Scheduling APIs draft specification being developed as a standard Web Platform API. - * Calling timersPromises.scheduler.yield() is equivalent to calling timersPromises.setImmediate() with no arguments. + * An experimental API defined by the [Scheduling APIs](https://nodejs.org/docs/latest-v20.x/api/async_hooks.html#promise-execution-tracking) draft specification + * being developed as a standard Web Platform API. + * Calling `timersPromises.scheduler.yield()` is equivalent to calling `timersPromises.setImmediate()` with no arguments. * @since v16.14.0 * @experimental */ diff --git a/node_modules/@types/node/tls.d.ts b/node_modules/@types/node/tls.d.ts index b289e841c3ce3e1e60b02eb607db1f3978358a83..707549b5789083d29b50eb645d5a0b385e9a76c1 100644 --- a/node_modules/@types/node/tls.d.ts +++ b/node_modules/@types/node/tls.d.ts @@ -6,7 +6,7 @@ * ```js * const tls = require('node:tls'); * ``` - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/tls.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/tls.js) */ declare module "tls" { import { X509Certificate } from "node:crypto"; @@ -125,7 +125,7 @@ declare module "tls" { */ asn1Curve?: string; /** - * The NIST name for the elliptic curve,if it has one + * The NIST name for the elliptic curve, if it has one * (not all well-known curves have been assigned names by NIST). */ nistCurve?: string; @@ -220,7 +220,7 @@ declare module "tls" { /** * Construct a new tls.TLSSocket object from an existing TCP socket. */ - constructor(socket: net.Socket, options?: TLSSocketOptions); + constructor(socket: net.Socket | stream.Duplex, options?: TLSSocketOptions); /** * This property is `true` if the peer certificate was signed by one of the CAs * specified when creating the `tls.TLSSocket` instance, otherwise `false`. @@ -278,7 +278,7 @@ declare module "tls" { * an ephemeral key exchange in `perfect forward secrecy` on a client * connection. It returns an empty object when the key exchange is not * ephemeral. As this is only supported on a client socket; `null` is returned - * if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The`name` property is available only when type is `'ECDH'`. + * if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The `name` property is available only when type is `'ECDH'`. * * For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`. * @since v5.0.0 @@ -382,7 +382,7 @@ declare module "tls" { * This method can be used to request a peer's certificate after the secure * connection has been established. * - * When running as the server, the socket will be destroyed with an error after`handshakeTimeout` timeout. + * When running as the server, the socket will be destroyed with an error after `handshakeTimeout` timeout. * * For TLSv1.3, renegotiation cannot be initiated, it is not supported by the * protocol. @@ -975,7 +975,7 @@ declare module "tls" { * This function is intended to be used in combination with the`checkServerIdentity` option that can be passed to {@link connect} and as * such operates on a `certificate object`. For other purposes, consider using `x509.checkHost()` instead. * - * This function can be overwritten by providing an alternative function as the`options.checkServerIdentity` option that is passed to `tls.connect()`. The + * This function can be overwritten by providing an alternative function as the `options.checkServerIdentity` option that is passed to `tls.connect()`. The * overwriting function can call `tls.checkServerIdentity()` of course, to augment * the checks done with additional verification. * @@ -984,7 +984,7 @@ declare module "tls" { * * Earlier versions of Node.js incorrectly accepted certificates for a given`hostname` if a matching `uniformResourceIdentifier` subject alternative name * was present (see [CVE-2021-44531](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44531)). Applications that wish to accept`uniformResourceIdentifier` subject alternative names can use - * a custom`options.checkServerIdentity` function that implements the desired behavior. + * a custom `options.checkServerIdentity` function that implements the desired behavior. * @since v0.8.4 * @param hostname The host name or IP address to verify the certificate against. * @param cert A `certificate object` representing the peer's certificate. @@ -1092,7 +1092,7 @@ declare module "tls" { * stream and the cleartext one is used as a replacement for the initial encrypted * stream. * - * `tls.createSecurePair()` returns a `tls.SecurePair` object with `cleartext` and`encrypted` stream properties. + * `tls.createSecurePair()` returns a `tls.SecurePair` object with `cleartext` and `encrypted` stream properties. * * Using `cleartext` has the same API as {@link TLSSocket}. * @@ -1125,10 +1125,10 @@ declare module "tls" { rejectUnauthorized?: boolean, ): SecurePair; /** - * {@link createServer} sets the default value of the `honorCipherOrder` option + * `{@link createServer}` sets the default value of the `honorCipherOrder` option * to `true`, other APIs that create secure contexts leave it unset. * - * {@link createServer} uses a 128 bit truncated SHA1 hash value generated + * `{@link createServer}` uses a 128 bit truncated SHA1 hash value generated * from `process.argv` as the default value of the `sessionIdContext` option, other * APIs that create secure contexts have no default value. * @@ -1136,12 +1136,12 @@ declare module "tls" { * usable as an argument to several `tls` APIs, such as `server.addContext()`, * but has no public methods. The {@link Server} constructor and the {@link createServer} method do not support the `secureContext` option. * - * A key is _required_ for ciphers that use certificates. Either `key` or`pfx` can be used to provide it. + * A key is _required_ for ciphers that use certificates. Either `key` or `pfx` can be used to provide it. * * If the `ca` option is not given, then Node.js will default to using [Mozilla's publicly trusted list of * CAs](https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt). * - * Custom DHE parameters are discouraged in favor of the new `dhparam: 'auto'`option. When set to `'auto'`, well-known DHE parameters of sufficient strength + * Custom DHE parameters are discouraged in favor of the new `dhparam: 'auto' `option. When set to `'auto'`, well-known DHE parameters of sufficient strength * will be selected automatically. Otherwise, if necessary, `openssl dhparam` can * be used to create custom parameters. The key length must be greater than or * equal to 1024 bits or else an error will be thrown. Although 1024 bits is @@ -1152,9 +1152,10 @@ declare module "tls" { /** * Returns an array with the names of the supported TLS ciphers. The names are * lower-case for historical reasons, but must be uppercased to be used in - * the `ciphers` option of {@link createSecureContext}. + * the `ciphers` option of `{@link createSecureContext}`. * - * Not all supported ciphers are enabled by default. See `Modifying the default TLS cipher suite`. + * Not all supported ciphers are enabled by default. See + * [Modifying the default TLS cipher suite](https://nodejs.org/docs/latest-v20.x/api/tls.html#modifying-the-default-tls-cipher-suite). * * Cipher names that start with `'tls_'` are for TLSv1.3, all the others are for * TLSv1.2 and below. @@ -1167,41 +1168,47 @@ declare module "tls" { function getCiphers(): string[]; /** * The default curve name to use for ECDH key agreement in a tls server. - * The default value is 'auto'. See tls.createSecureContext() for further + * The default value is `'auto'`. See `{@link createSecureContext()}` for further * information. + * @since v0.11.13 */ let DEFAULT_ECDH_CURVE: string; /** - * The default value of the maxVersion option of - * tls.createSecureContext(). It can be assigned any of the supported TLS - * protocol versions, 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: - * 'TLSv1.3', unless changed using CLI options. Using --tls-max-v1.2 sets - * the default to 'TLSv1.2'. Using --tls-max-v1.3 sets the default to - * 'TLSv1.3'. If multiple of the options are provided, the highest maximum - * is used. + * The default value of the `maxVersion` option of `{@link createSecureContext()}`. + * It can be assigned any of the supported TLS protocol versions, + * `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. **Default:** `'TLSv1.3'`, unless + * changed using CLI options. Using `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using + * `--tls-max-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options + * are provided, the highest maximum is used. + * @since v11.4.0 */ let DEFAULT_MAX_VERSION: SecureVersion; /** - * The default value of the minVersion option of tls.createSecureContext(). + * The default value of the `minVersion` option of `{@link createSecureContext()}`. * It can be assigned any of the supported TLS protocol versions, - * 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: 'TLSv1.2', unless - * changed using CLI options. Using --tls-min-v1.0 sets the default to - * 'TLSv1'. Using --tls-min-v1.1 sets the default to 'TLSv1.1'. Using - * --tls-min-v1.3 sets the default to 'TLSv1.3'. If multiple of the options + * `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. **Default:** `'TLSv1.2'`, unless + * changed using CLI options. Using `--tls-min-v1.0` sets the default to + * `'TLSv1'`. Using `--tls-min-v1.1` sets the default to `'TLSv1.1'`. Using + * `--tls-min-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options * are provided, the lowest minimum is used. + * @since v11.4.0 */ let DEFAULT_MIN_VERSION: SecureVersion; /** - * The default value of the ciphers option of tls.createSecureContext(). + * The default value of the `ciphers` option of `{@link createSecureContext()}`. * It can be assigned any of the supported OpenSSL ciphers. - * Defaults to the content of crypto.constants.defaultCoreCipherList, unless - * changed using CLI options using --tls-default-ciphers. + * Defaults to the content of `crypto.constants.defaultCoreCipherList`, unless + * changed using CLI options using `--tls-default-ciphers`. + * @since v19.8.0 */ let DEFAULT_CIPHERS: string; /** - * An immutable array of strings representing the root certificates (in PEM - * format) used for verifying peer certificates. This is the default value - * of the ca option to tls.createSecureContext(). + * An immutable array of strings representing the root certificates (in PEM format) + * from the bundled Mozilla CA store as supplied by the current Node.js version. + * + * The bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store + * that is fixed at release time. It is identical on all supported platforms. + * @since v12.3.0 */ const rootCertificates: readonly string[]; } diff --git a/node_modules/@types/node/trace_events.d.ts b/node_modules/@types/node/trace_events.d.ts index 336135959baba13c54c0d7859445290994236804..b9d498e08303f3ff85d1ddb2d7a8cd7904164118 100644 --- a/node_modules/@types/node/trace_events.d.ts +++ b/node_modules/@types/node/trace_events.d.ts @@ -1,40 +1,36 @@ /** - * The `node:trace_events` module provides a mechanism to centralize tracing - * information generated by V8, Node.js core, and userspace code. + * The `node:trace_events` module provides a mechanism to centralize tracing information + * generated by V8, Node.js core, and userspace code. * * Tracing can be enabled with the `--trace-event-categories` command-line flag - * or by using the `node:trace_events` module. The `--trace-event-categories` flag + * or by using the `trace_events` module. The `--trace-event-categories` flag * accepts a list of comma-separated category names. * * The available categories are: * * * `node`: An empty placeholder. - * * `node.async_hooks`: Enables capture of detailed `async_hooks` trace data. - * The `async_hooks` events have a unique `asyncId` and a special `triggerId` `triggerAsyncId` property. + * * `node.async_hooks`: Enables capture of detailed [`async_hooks`](https://nodejs.org/docs/latest-v20.x/api/async_hooks.html) trace data. + * The [`async_hooks`](https://nodejs.org/docs/latest-v20.x/api/async_hooks.html) events have a unique `asyncId` and a special `triggerId` `triggerAsyncId` property. * * `node.bootstrap`: Enables capture of Node.js bootstrap milestones. - * * `node.console`: Enables capture of `console.time()` and `console.count()`output. - * * `node.threadpoolwork.sync`: Enables capture of trace data for threadpool - * synchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. - * * `node.threadpoolwork.async`: Enables capture of trace data for threadpool - * asynchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. + * * `node.console`: Enables capture of `console.time()` and `console.count()` output. + * * `node.threadpoolwork.sync`: Enables capture of trace data for threadpool synchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. + * * `node.threadpoolwork.async`: Enables capture of trace data for threadpool asynchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. * * `node.dns.native`: Enables capture of trace data for DNS queries. * * `node.net.native`: Enables capture of trace data for network. * * `node.environment`: Enables capture of Node.js Environment milestones. * * `node.fs.sync`: Enables capture of trace data for file system sync methods. - * * `node.fs_dir.sync`: Enables capture of trace data for file system sync - * directory methods. + * * `node.fs_dir.sync`: Enables capture of trace data for file system sync directory methods. * * `node.fs.async`: Enables capture of trace data for file system async methods. - * * `node.fs_dir.async`: Enables capture of trace data for file system async - * directory methods. - * * `node.perf`: Enables capture of `Performance API` measurements. + * * `node.fs_dir.async`: Enables capture of trace data for file system async directory methods. + * * `node.perf`: Enables capture of [Performance API](https://nodejs.org/docs/latest-v20.x/api/perf_hooks.html) measurements. * * `node.perf.usertiming`: Enables capture of only Performance API User Timing * measures and marks. * * `node.perf.timerify`: Enables capture of only Performance API timerify * measurements. * * `node.promises.rejections`: Enables capture of trace data tracking the number * of unhandled Promise rejections and handled-after-rejections. - * * `node.vm.script`: Enables capture of trace data for the `node:vm` module's`runInNewContext()`, `runInContext()`, and `runInThisContext()` methods. - * * `v8`: The `V8` events are GC, compiling, and execution related. + * * `node.vm.script`: Enables capture of trace data for the `node:vm` module's `runInNewContext()`, `runInContext()`, and `runInThisContext()` methods. + * * `v8`: The [V8](https://nodejs.org/docs/latest-v20.x/api/v8.html) events are GC, compiling, and execution related. * * `node.http`: Enables capture of trace data for http request / response. * * By default the `node`, `node.async_hooks`, and `v8` categories are enabled. @@ -43,8 +39,8 @@ * node --trace-event-categories v8,node,node.async_hooks server.js * ``` * - * Prior versions of Node.js required the use of the `--trace-events-enabled`flag to enable trace events. This requirement has been removed. However, the`--trace-events-enabled` flag _may_ still be - * used and will enable the`node`, `node.async_hooks`, and `v8` trace event categories by default. + * Prior versions of Node.js required the use of the `--trace-events-enabled` flag to enable trace events. This requirement has been removed. However, the `--trace-events-enabled` flag _may_ still be + * used and will enable the `node`, `node.async_hooks`, and `v8` trace event categories by default. * * ```bash * node --trace-events-enabled @@ -69,7 +65,7 @@ * Running Node.js with tracing enabled will produce log files that can be opened * in the [`chrome://tracing`](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) tab of Chrome. * - * The logging file is by default called `node_trace.${rotation}.log`, where`${rotation}` is an incrementing log-rotation id. The filepath pattern can + * The logging file is by default called `node_trace.${rotation}.log`, where `${rotation}` is an incrementing log-rotation id. The filepath pattern can * be specified with `--trace-event-file-pattern` that accepts a template * string that supports `${rotation}` and `${pid}`: * @@ -77,7 +73,7 @@ * node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js * ``` * - * To guarantee that the log file is properly generated after signal events like`SIGINT`, `SIGTERM`, or `SIGBREAK`, make sure to have the appropriate handlers + * To guarantee that the log file is properly generated after signal events like `SIGINT`, `SIGTERM`, or `SIGBREAK`, make sure to have the appropriate handlers * in your code, such as: * * ```js @@ -92,9 +88,9 @@ * However the trace-event timestamps are expressed in microseconds, * unlike `process.hrtime()` which returns nanoseconds. * - * The features from this module are not available in `Worker` threads. + * The features from this module are not available in [`Worker`](https://nodejs.org/docs/latest-v20.x/api/worker_threads.html#class-worker) threads. * @experimental - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/trace_events.js) + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/trace_events.js) */ declare module "trace_events" { /** @@ -111,6 +107,7 @@ declare module "trace_events" { /** * A comma-separated list of the trace event categories covered by this * `Tracing` object. + * @since v10.0.0 */ readonly categories: string; /** @@ -119,15 +116,34 @@ declare module "trace_events" { * Only trace event categories _not_ covered by other enabled `Tracing` * objects and _not_ specified by the `--trace-event-categories` flag * will be disabled. + * + * ```js + * const trace_events = require('node:trace_events'); + * const t1 = trace_events.createTracing({ categories: ['node', 'v8'] }); + * const t2 = trace_events.createTracing({ categories: ['node.perf', 'node'] }); + * t1.enable(); + * t2.enable(); + * + * // Prints 'node,node.perf,v8' + * console.log(trace_events.getEnabledCategories()); + * + * t2.disable(); // Will only disable emission of the 'node.perf' category + * + * // Prints 'node,v8' + * console.log(trace_events.getEnabledCategories()); + * ``` + * @since v10.0.0 */ disable(): void; /** * Enables this `Tracing` object for the set of categories covered by * the `Tracing` object. + * @since v10.0.0 */ enable(): void; /** * `true` only if the `Tracing` object has been enabled. + * @since v10.0.0 */ readonly enabled: boolean; } @@ -151,7 +167,6 @@ declare module "trace_events" { * tracing.disable(); * ``` * @since v10.0.0 - * @return . */ function createTracing(options: CreateTracingOptions): Tracing; /** @@ -160,7 +175,7 @@ declare module "trace_events" { * by the _union_ of all currently-enabled `Tracing` objects and any categories * enabled using the `--trace-event-categories` flag. * - * Given the file `test.js` below, the command`node --trace-event-categories node.perf test.js` will print`'node.async_hooks,node.perf'` to the console. + * Given the file `test.js` below, the command `node --trace-event-categories node.perf test.js` will print `'node.async_hooks,node.perf'` to the console. * * ```js * const trace_events = require('node:trace_events'); diff --git a/node_modules/@types/node/ts4.8/assert.d.ts b/node_modules/@types/node/ts4.8/assert.d.ts deleted file mode 100644 index cd821433575b42840106da9995aaaec26eb0edc7..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/assert.d.ts +++ /dev/null @@ -1,996 +0,0 @@ -/** - * The `node:assert` module provides a set of assertion functions for verifying - * invariants. - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/assert.js) - */ -declare module "assert" { - /** - * An alias of {@link ok}. - * @since v0.5.9 - * @param value The input that is checked for being truthy. - */ - function assert(value: unknown, message?: string | Error): asserts value; - namespace assert { - /** - * Indicates the failure of an assertion. All errors thrown by the `node:assert`module will be instances of the `AssertionError` class. - */ - class AssertionError extends Error { - /** - * Set to the `actual` argument for methods such as {@link assert.strictEqual()}. - */ - actual: unknown; - /** - * Set to the `expected` argument for methods such as {@link assert.strictEqual()}. - */ - expected: unknown; - /** - * Set to the passed in operator value. - */ - operator: string; - /** - * Indicates if the message was auto-generated (`true`) or not. - */ - generatedMessage: boolean; - /** - * Value is always `ERR_ASSERTION` to show that the error is an assertion error. - */ - code: "ERR_ASSERTION"; - constructor(options?: { - /** If provided, the error message is set to this value. */ - message?: string | undefined; - /** The `actual` property on the error instance. */ - actual?: unknown | undefined; - /** The `expected` property on the error instance. */ - expected?: unknown | undefined; - /** The `operator` property on the error instance. */ - operator?: string | undefined; - /** If provided, the generated stack trace omits frames before this function. */ - // eslint-disable-next-line @typescript-eslint/ban-types - stackStartFn?: Function | undefined; - }); - } - /** - * This feature is deprecated and will be removed in a future version. - * Please consider using alternatives such as the `mock` helper function. - * @since v14.2.0, v12.19.0 - * @deprecated Deprecated - */ - class CallTracker { - /** - * The wrapper function is expected to be called exactly `exact` times. If the - * function has not been called exactly `exact` times when `tracker.verify()` is called, then `tracker.verify()` will throw an - * error. - * - * ```js - * import assert from 'node:assert'; - * - * // Creates call tracker. - * const tracker = new assert.CallTracker(); - * - * function func() {} - * - * // Returns a function that wraps func() that must be called exact times - * // before tracker.verify(). - * const callsfunc = tracker.calls(func); - * ``` - * @since v14.2.0, v12.19.0 - * @param [fn='A no-op function'] - * @param [exact=1] - * @return that wraps `fn`. - */ - calls(exact?: number): () => void; - calls any>(fn?: Func, exact?: number): Func; - /** - * Example: - * - * ```js - * import assert from 'node:assert'; - * - * const tracker = new assert.CallTracker(); - * - * function func() {} - * const callsfunc = tracker.calls(func); - * callsfunc(1, 2, 3); - * - * assert.deepStrictEqual(tracker.getCalls(callsfunc), - * [{ thisArg: undefined, arguments: [1, 2, 3] }]); - * ``` - * @since v18.8.0, v16.18.0 - * @param fn - * @return An Array with all the calls to a tracked function. - */ - getCalls(fn: Function): CallTrackerCall[]; - /** - * The arrays contains information about the expected and actual number of calls of - * the functions that have not been called the expected number of times. - * - * ```js - * import assert from 'node:assert'; - * - * // Creates call tracker. - * const tracker = new assert.CallTracker(); - * - * function func() {} - * - * // Returns a function that wraps func() that must be called exact times - * // before tracker.verify(). - * const callsfunc = tracker.calls(func, 2); - * - * // Returns an array containing information on callsfunc() - * console.log(tracker.report()); - * // [ - * // { - * // message: 'Expected the func function to be executed 2 time(s) but was - * // executed 0 time(s).', - * // actual: 0, - * // expected: 2, - * // operator: 'func', - * // stack: stack trace - * // } - * // ] - * ``` - * @since v14.2.0, v12.19.0 - * @return An Array of objects containing information about the wrapper functions returned by `calls`. - */ - report(): CallTrackerReportInformation[]; - /** - * Reset calls of the call tracker. - * If a tracked function is passed as an argument, the calls will be reset for it. - * If no arguments are passed, all tracked functions will be reset. - * - * ```js - * import assert from 'node:assert'; - * - * const tracker = new assert.CallTracker(); - * - * function func() {} - * const callsfunc = tracker.calls(func); - * - * callsfunc(); - * // Tracker was called once - * assert.strictEqual(tracker.getCalls(callsfunc).length, 1); - * - * tracker.reset(callsfunc); - * assert.strictEqual(tracker.getCalls(callsfunc).length, 0); - * ``` - * @since v18.8.0, v16.18.0 - * @param fn a tracked function to reset. - */ - reset(fn?: Function): void; - /** - * Iterates through the list of functions passed to `tracker.calls()` and will throw an error for functions that - * have not been called the expected number of times. - * - * ```js - * import assert from 'node:assert'; - * - * // Creates call tracker. - * const tracker = new assert.CallTracker(); - * - * function func() {} - * - * // Returns a function that wraps func() that must be called exact times - * // before tracker.verify(). - * const callsfunc = tracker.calls(func, 2); - * - * callsfunc(); - * - * // Will throw an error since callsfunc() was only called once. - * tracker.verify(); - * ``` - * @since v14.2.0, v12.19.0 - */ - verify(): void; - } - interface CallTrackerCall { - thisArg: object; - arguments: unknown[]; - } - interface CallTrackerReportInformation { - message: string; - /** The actual number of times the function was called. */ - actual: number; - /** The number of times the function was expected to be called. */ - expected: number; - /** The name of the function that is wrapped. */ - operator: string; - /** A stack trace of the function. */ - stack: object; - } - type AssertPredicate = RegExp | (new() => object) | ((thrown: unknown) => boolean) | object | Error; - /** - * Throws an `AssertionError` with the provided error message or a default - * error message. If the `message` parameter is an instance of an `Error` then - * it will be thrown instead of the `AssertionError`. - * - * ```js - * import assert from 'node:assert/strict'; - * - * assert.fail(); - * // AssertionError [ERR_ASSERTION]: Failed - * - * assert.fail('boom'); - * // AssertionError [ERR_ASSERTION]: boom - * - * assert.fail(new TypeError('need array')); - * // TypeError: need array - * ``` - * - * Using `assert.fail()` with more than two arguments is possible but deprecated. - * See below for further details. - * @since v0.1.21 - * @param [message='Failed'] - */ - function fail(message?: string | Error): never; - /** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */ - function fail( - actual: unknown, - expected: unknown, - message?: string | Error, - operator?: string, - // eslint-disable-next-line @typescript-eslint/ban-types - stackStartFn?: Function, - ): never; - /** - * Tests if `value` is truthy. It is equivalent to`assert.equal(!!value, true, message)`. - * - * If `value` is not truthy, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is `undefined`, a default - * error message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. - * If no arguments are passed in at all `message` will be set to the string:`` 'No value argument passed to `assert.ok()`' ``. - * - * Be aware that in the `repl` the error message will be different to the one - * thrown in a file! See below for further details. - * - * ```js - * import assert from 'node:assert/strict'; - * - * assert.ok(true); - * // OK - * assert.ok(1); - * // OK - * - * assert.ok(); - * // AssertionError: No value argument passed to `assert.ok()` - * - * assert.ok(false, 'it\'s false'); - * // AssertionError: it's false - * - * // In the repl: - * assert.ok(typeof 123 === 'string'); - * // AssertionError: false == true - * - * // In a file (e.g. test.js): - * assert.ok(typeof 123 === 'string'); - * // AssertionError: The expression evaluated to a falsy value: - * // - * // assert.ok(typeof 123 === 'string') - * - * assert.ok(false); - * // AssertionError: The expression evaluated to a falsy value: - * // - * // assert.ok(false) - * - * assert.ok(0); - * // AssertionError: The expression evaluated to a falsy value: - * // - * // assert.ok(0) - * ``` - * - * ```js - * import assert from 'node:assert/strict'; - * - * // Using `assert()` works the same: - * assert(0); - * // AssertionError: The expression evaluated to a falsy value: - * // - * // assert(0) - * ``` - * @since v0.1.21 - */ - function ok(value: unknown, message?: string | Error): asserts value; - /** - * **Strict assertion mode** - * - * An alias of {@link strictEqual}. - * - * **Legacy assertion mode** - * - * > Stability: 3 - Legacy: Use {@link strictEqual} instead. - * - * Tests shallow, coercive equality between the `actual` and `expected` parameters - * using the [`==` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality). `NaN` is specially handled - * and treated as being identical if both sides are `NaN`. - * - * ```js - * import assert from 'node:assert'; - * - * assert.equal(1, 1); - * // OK, 1 == 1 - * assert.equal(1, '1'); - * // OK, 1 == '1' - * assert.equal(NaN, NaN); - * // OK - * - * assert.equal(1, 2); - * // AssertionError: 1 == 2 - * assert.equal({ a: { b: 1 } }, { a: { b: 1 } }); - * // AssertionError: { a: { b: 1 } } == { a: { b: 1 } } - * ``` - * - * If the values are not equal, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is undefined, a default - * error message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. - * @since v0.1.21 - */ - function equal(actual: unknown, expected: unknown, message?: string | Error): void; - /** - * **Strict assertion mode** - * - * An alias of {@link notStrictEqual}. - * - * **Legacy assertion mode** - * - * > Stability: 3 - Legacy: Use {@link notStrictEqual} instead. - * - * Tests shallow, coercive inequality with the [`!=` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Inequality). `NaN` is - * specially handled and treated as being identical if both sides are `NaN`. - * - * ```js - * import assert from 'node:assert'; - * - * assert.notEqual(1, 2); - * // OK - * - * assert.notEqual(1, 1); - * // AssertionError: 1 != 1 - * - * assert.notEqual(1, '1'); - * // AssertionError: 1 != '1' - * ``` - * - * If the values are equal, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is undefined, a default error - * message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. - * @since v0.1.21 - */ - function notEqual(actual: unknown, expected: unknown, message?: string | Error): void; - /** - * **Strict assertion mode** - * - * An alias of {@link deepStrictEqual}. - * - * **Legacy assertion mode** - * - * > Stability: 3 - Legacy: Use {@link deepStrictEqual} instead. - * - * Tests for deep equality between the `actual` and `expected` parameters. Consider - * using {@link deepStrictEqual} instead. {@link deepEqual} can have - * surprising results. - * - * _Deep equality_ means that the enumerable "own" properties of child objects - * are also recursively evaluated by the following rules. - * @since v0.1.21 - */ - function deepEqual(actual: unknown, expected: unknown, message?: string | Error): void; - /** - * **Strict assertion mode** - * - * An alias of {@link notDeepStrictEqual}. - * - * **Legacy assertion mode** - * - * > Stability: 3 - Legacy: Use {@link notDeepStrictEqual} instead. - * - * Tests for any deep inequality. Opposite of {@link deepEqual}. - * - * ```js - * import assert from 'node:assert'; - * - * const obj1 = { - * a: { - * b: 1, - * }, - * }; - * const obj2 = { - * a: { - * b: 2, - * }, - * }; - * const obj3 = { - * a: { - * b: 1, - * }, - * }; - * const obj4 = { __proto__: obj1 }; - * - * assert.notDeepEqual(obj1, obj1); - * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } - * - * assert.notDeepEqual(obj1, obj2); - * // OK - * - * assert.notDeepEqual(obj1, obj3); - * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } - * - * assert.notDeepEqual(obj1, obj4); - * // OK - * ``` - * - * If the values are deeply equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a default - * error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown - * instead of the `AssertionError`. - * @since v0.1.21 - */ - function notDeepEqual(actual: unknown, expected: unknown, message?: string | Error): void; - /** - * Tests strict equality between the `actual` and `expected` parameters as - * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). - * - * ```js - * import assert from 'node:assert/strict'; - * - * assert.strictEqual(1, 2); - * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: - * // - * // 1 !== 2 - * - * assert.strictEqual(1, 1); - * // OK - * - * assert.strictEqual('Hello foobar', 'Hello World!'); - * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: - * // + actual - expected - * // - * // + 'Hello foobar' - * // - 'Hello World!' - * // ^ - * - * const apples = 1; - * const oranges = 2; - * assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`); - * // AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2 - * - * assert.strictEqual(1, '1', new TypeError('Inputs are not identical')); - * // TypeError: Inputs are not identical - * ``` - * - * If the values are not strictly equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a - * default error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown - * instead of the `AssertionError`. - * @since v0.1.21 - */ - function strictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; - /** - * Tests strict inequality between the `actual` and `expected` parameters as - * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). - * - * ```js - * import assert from 'node:assert/strict'; - * - * assert.notStrictEqual(1, 2); - * // OK - * - * assert.notStrictEqual(1, 1); - * // AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to: - * // - * // 1 - * - * assert.notStrictEqual(1, '1'); - * // OK - * ``` - * - * If the values are strictly equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a - * default error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown - * instead of the `AssertionError`. - * @since v0.1.21 - */ - function notStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; - /** - * Tests for deep equality between the `actual` and `expected` parameters. - * "Deep" equality means that the enumerable "own" properties of child objects - * are recursively evaluated also by the following rules. - * @since v1.2.0 - */ - function deepStrictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; - /** - * Tests for deep strict inequality. Opposite of {@link deepStrictEqual}. - * - * ```js - * import assert from 'node:assert/strict'; - * - * assert.notDeepStrictEqual({ a: 1 }, { a: '1' }); - * // OK - * ``` - * - * If the values are deeply and strictly equal, an `AssertionError` is thrown - * with a `message` property set equal to the value of the `message` parameter. If - * the `message` parameter is undefined, a default error message is assigned. If - * the `message` parameter is an instance of an `Error` then it will be thrown - * instead of the `AssertionError`. - * @since v1.2.0 - */ - function notDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; - /** - * Expects the function `fn` to throw an error. - * - * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), - * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, - * a validation object where each property will be tested for strict deep equality, - * or an instance of error where each property will be tested for strict deep - * equality including the non-enumerable `message` and `name` properties. When - * using an object, it is also possible to use a regular expression, when - * validating against a string property. See below for examples. - * - * If specified, `message` will be appended to the message provided by the`AssertionError` if the `fn` call fails to throw or in case the error validation - * fails. - * - * Custom validation object/error instance: - * - * ```js - * import assert from 'node:assert/strict'; - * - * const err = new TypeError('Wrong value'); - * err.code = 404; - * err.foo = 'bar'; - * err.info = { - * nested: true, - * baz: 'text', - * }; - * err.reg = /abc/i; - * - * assert.throws( - * () => { - * throw err; - * }, - * { - * name: 'TypeError', - * message: 'Wrong value', - * info: { - * nested: true, - * baz: 'text', - * }, - * // Only properties on the validation object will be tested for. - * // Using nested objects requires all properties to be present. Otherwise - * // the validation is going to fail. - * }, - * ); - * - * // Using regular expressions to validate error properties: - * assert.throws( - * () => { - * throw err; - * }, - * { - * // The `name` and `message` properties are strings and using regular - * // expressions on those will match against the string. If they fail, an - * // error is thrown. - * name: /^TypeError$/, - * message: /Wrong/, - * foo: 'bar', - * info: { - * nested: true, - * // It is not possible to use regular expressions for nested properties! - * baz: 'text', - * }, - * // The `reg` property contains a regular expression and only if the - * // validation object contains an identical regular expression, it is going - * // to pass. - * reg: /abc/i, - * }, - * ); - * - * // Fails due to the different `message` and `name` properties: - * assert.throws( - * () => { - * const otherErr = new Error('Not found'); - * // Copy all enumerable properties from `err` to `otherErr`. - * for (const [key, value] of Object.entries(err)) { - * otherErr[key] = value; - * } - * throw otherErr; - * }, - * // The error's `message` and `name` properties will also be checked when using - * // an error as validation object. - * err, - * ); - * ``` - * - * Validate instanceof using constructor: - * - * ```js - * import assert from 'node:assert/strict'; - * - * assert.throws( - * () => { - * throw new Error('Wrong value'); - * }, - * Error, - * ); - * ``` - * - * Validate error message using [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions): - * - * Using a regular expression runs `.toString` on the error object, and will - * therefore also include the error name. - * - * ```js - * import assert from 'node:assert/strict'; - * - * assert.throws( - * () => { - * throw new Error('Wrong value'); - * }, - * /^Error: Wrong value$/, - * ); - * ``` - * - * Custom error validation: - * - * The function must return `true` to indicate all internal validations passed. - * It will otherwise fail with an `AssertionError`. - * - * ```js - * import assert from 'node:assert/strict'; - * - * assert.throws( - * () => { - * throw new Error('Wrong value'); - * }, - * (err) => { - * assert(err instanceof Error); - * assert(/value/.test(err)); - * // Avoid returning anything from validation functions besides `true`. - * // Otherwise, it's not clear what part of the validation failed. Instead, - * // throw an error about the specific validation that failed (as done in this - * // example) and add as much helpful debugging information to that error as - * // possible. - * return true; - * }, - * 'unexpected error', - * ); - * ``` - * - * `error` cannot be a string. If a string is provided as the second - * argument, then `error` is assumed to be omitted and the string will be used for`message` instead. This can lead to easy-to-miss mistakes. Using the same - * message as the thrown error message is going to result in an`ERR_AMBIGUOUS_ARGUMENT` error. Please read the example below carefully if using - * a string as the second argument gets considered: - * - * ```js - * import assert from 'node:assert/strict'; - * - * function throwingFirst() { - * throw new Error('First'); - * } - * - * function throwingSecond() { - * throw new Error('Second'); - * } - * - * function notThrowing() {} - * - * // The second argument is a string and the input function threw an Error. - * // The first case will not throw as it does not match for the error message - * // thrown by the input function! - * assert.throws(throwingFirst, 'Second'); - * // In the next example the message has no benefit over the message from the - * // error and since it is not clear if the user intended to actually match - * // against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error. - * assert.throws(throwingSecond, 'Second'); - * // TypeError [ERR_AMBIGUOUS_ARGUMENT] - * - * // The string is only used (as message) in case the function does not throw: - * assert.throws(notThrowing, 'Second'); - * // AssertionError [ERR_ASSERTION]: Missing expected exception: Second - * - * // If it was intended to match for the error message do this instead: - * // It does not throw because the error messages match. - * assert.throws(throwingSecond, /Second$/); - * - * // If the error message does not match, an AssertionError is thrown. - * assert.throws(throwingFirst, /Second$/); - * // AssertionError [ERR_ASSERTION] - * ``` - * - * Due to the confusing error-prone notation, avoid a string as the second - * argument. - * @since v0.1.21 - */ - function throws(block: () => unknown, message?: string | Error): void; - function throws(block: () => unknown, error: AssertPredicate, message?: string | Error): void; - /** - * Asserts that the function `fn` does not throw an error. - * - * Using `assert.doesNotThrow()` is actually not useful because there - * is no benefit in catching an error and then rethrowing it. Instead, consider - * adding a comment next to the specific code path that should not throw and keep - * error messages as expressive as possible. - * - * When `assert.doesNotThrow()` is called, it will immediately call the `fn`function. - * - * If an error is thrown and it is the same type as that specified by the `error`parameter, then an `AssertionError` is thrown. If the error is of a - * different type, or if the `error` parameter is undefined, the error is - * propagated back to the caller. - * - * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), - * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), or a validation - * function. See {@link throws} for more details. - * - * The following, for instance, will throw the `TypeError` because there is no - * matching error type in the assertion: - * - * ```js - * import assert from 'node:assert/strict'; - * - * assert.doesNotThrow( - * () => { - * throw new TypeError('Wrong value'); - * }, - * SyntaxError, - * ); - * ``` - * - * However, the following will result in an `AssertionError` with the message - * 'Got unwanted exception...': - * - * ```js - * import assert from 'node:assert/strict'; - * - * assert.doesNotThrow( - * () => { - * throw new TypeError('Wrong value'); - * }, - * TypeError, - * ); - * ``` - * - * If an `AssertionError` is thrown and a value is provided for the `message`parameter, the value of `message` will be appended to the `AssertionError` message: - * - * ```js - * import assert from 'node:assert/strict'; - * - * assert.doesNotThrow( - * () => { - * throw new TypeError('Wrong value'); - * }, - * /Wrong value/, - * 'Whoops', - * ); - * // Throws: AssertionError: Got unwanted exception: Whoops - * ``` - * @since v0.1.21 - */ - function doesNotThrow(block: () => unknown, message?: string | Error): void; - function doesNotThrow(block: () => unknown, error: AssertPredicate, message?: string | Error): void; - /** - * Throws `value` if `value` is not `undefined` or `null`. This is useful when - * testing the `error` argument in callbacks. The stack trace contains all frames - * from the error passed to `ifError()` including the potential new frames for`ifError()` itself. - * - * ```js - * import assert from 'node:assert/strict'; - * - * assert.ifError(null); - * // OK - * assert.ifError(0); - * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0 - * assert.ifError('error'); - * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error' - * assert.ifError(new Error()); - * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error - * - * // Create some random error frames. - * let err; - * (function errorFrame() { - * err = new Error('test error'); - * })(); - * - * (function ifErrorFrame() { - * assert.ifError(err); - * })(); - * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error - * // at ifErrorFrame - * // at errorFrame - * ``` - * @since v0.1.97 - */ - function ifError(value: unknown): asserts value is null | undefined; - /** - * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately - * calls the function and awaits the returned promise to complete. It will then - * check that the promise is rejected. - * - * If `asyncFn` is a function and it throws an error synchronously,`assert.rejects()` will return a rejected `Promise` with that error. If the - * function does not return a promise, `assert.rejects()` will return a rejected`Promise` with an `ERR_INVALID_RETURN_VALUE` error. In both cases the error - * handler is skipped. - * - * Besides the async nature to await the completion behaves identically to {@link throws}. - * - * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), - * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, - * an object where each property will be tested for, or an instance of error where - * each property will be tested for including the non-enumerable `message` and`name` properties. - * - * If specified, `message` will be the message provided by the `AssertionError` if the `asyncFn` fails to reject. - * - * ```js - * import assert from 'node:assert/strict'; - * - * await assert.rejects( - * async () => { - * throw new TypeError('Wrong value'); - * }, - * { - * name: 'TypeError', - * message: 'Wrong value', - * }, - * ); - * ``` - * - * ```js - * import assert from 'node:assert/strict'; - * - * await assert.rejects( - * async () => { - * throw new TypeError('Wrong value'); - * }, - * (err) => { - * assert.strictEqual(err.name, 'TypeError'); - * assert.strictEqual(err.message, 'Wrong value'); - * return true; - * }, - * ); - * ``` - * - * ```js - * import assert from 'node:assert/strict'; - * - * assert.rejects( - * Promise.reject(new Error('Wrong value')), - * Error, - * ).then(() => { - * // ... - * }); - * ``` - * - * `error` cannot be a string. If a string is provided as the second - * argument, then `error` is assumed to be omitted and the string will be used for`message` instead. This can lead to easy-to-miss mistakes. Please read the - * example in {@link throws} carefully if using a string as the second - * argument gets considered. - * @since v10.0.0 - */ - function rejects(block: (() => Promise) | Promise, message?: string | Error): Promise; - function rejects( - block: (() => Promise) | Promise, - error: AssertPredicate, - message?: string | Error, - ): Promise; - /** - * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately - * calls the function and awaits the returned promise to complete. It will then - * check that the promise is not rejected. - * - * If `asyncFn` is a function and it throws an error synchronously,`assert.doesNotReject()` will return a rejected `Promise` with that error. If - * the function does not return a promise, `assert.doesNotReject()` will return a - * rejected `Promise` with an `ERR_INVALID_RETURN_VALUE` error. In both cases - * the error handler is skipped. - * - * Using `assert.doesNotReject()` is actually not useful because there is little - * benefit in catching a rejection and then rejecting it again. Instead, consider - * adding a comment next to the specific code path that should not reject and keep - * error messages as expressive as possible. - * - * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), - * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), or a validation - * function. See {@link throws} for more details. - * - * Besides the async nature to await the completion behaves identically to {@link doesNotThrow}. - * - * ```js - * import assert from 'node:assert/strict'; - * - * await assert.doesNotReject( - * async () => { - * throw new TypeError('Wrong value'); - * }, - * SyntaxError, - * ); - * ``` - * - * ```js - * import assert from 'node:assert/strict'; - * - * assert.doesNotReject(Promise.reject(new TypeError('Wrong value'))) - * .then(() => { - * // ... - * }); - * ``` - * @since v10.0.0 - */ - function doesNotReject( - block: (() => Promise) | Promise, - message?: string | Error, - ): Promise; - function doesNotReject( - block: (() => Promise) | Promise, - error: AssertPredicate, - message?: string | Error, - ): Promise; - /** - * Expects the `string` input to match the regular expression. - * - * ```js - * import assert from 'node:assert/strict'; - * - * assert.match('I will fail', /pass/); - * // AssertionError [ERR_ASSERTION]: The input did not match the regular ... - * - * assert.match(123, /pass/); - * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. - * - * assert.match('I will pass', /pass/); - * // OK - * ``` - * - * If the values do not match, or if the `string` argument is of another type than`string`, an `AssertionError` is thrown with a `message` property set equal - * to the value of the `message` parameter. If the `message` parameter is - * undefined, a default error message is assigned. If the `message` parameter is an - * instance of an `Error` then it will be thrown instead of the `AssertionError`. - * @since v13.6.0, v12.16.0 - */ - function match(value: string, regExp: RegExp, message?: string | Error): void; - /** - * Expects the `string` input not to match the regular expression. - * - * ```js - * import assert from 'node:assert/strict'; - * - * assert.doesNotMatch('I will fail', /fail/); - * // AssertionError [ERR_ASSERTION]: The input was expected to not match the ... - * - * assert.doesNotMatch(123, /pass/); - * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. - * - * assert.doesNotMatch('I will pass', /different/); - * // OK - * ``` - * - * If the values do match, or if the `string` argument is of another type than`string`, an `AssertionError` is thrown with a `message` property set equal - * to the value of the `message` parameter. If the `message` parameter is - * undefined, a default error message is assigned. If the `message` parameter is an - * instance of an `Error` then it will be thrown instead of the `AssertionError`. - * @since v13.6.0, v12.16.0 - */ - function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void; - const strict: - & Omit< - typeof assert, - | "equal" - | "notEqual" - | "deepEqual" - | "notDeepEqual" - | "ok" - | "strictEqual" - | "deepStrictEqual" - | "ifError" - | "strict" - > - & { - (value: unknown, message?: string | Error): asserts value; - equal: typeof strictEqual; - notEqual: typeof notStrictEqual; - deepEqual: typeof deepStrictEqual; - notDeepEqual: typeof notDeepStrictEqual; - // Mapped types and assertion functions are incompatible? - // TS2775: Assertions require every name in the call target - // to be declared with an explicit type annotation. - ok: typeof ok; - strictEqual: typeof strictEqual; - deepStrictEqual: typeof deepStrictEqual; - ifError: typeof ifError; - strict: typeof strict; - }; - } - export = assert; -} -declare module "node:assert" { - import assert = require("assert"); - export = assert; -} diff --git a/node_modules/@types/node/ts4.8/assert/strict.d.ts b/node_modules/@types/node/ts4.8/assert/strict.d.ts deleted file mode 100644 index f333913a4565f7067b05ddbc415490e585f2d1e1..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/assert/strict.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -declare module "assert/strict" { - import { strict } from "node:assert"; - export = strict; -} -declare module "node:assert/strict" { - import { strict } from "node:assert"; - export = strict; -} diff --git a/node_modules/@types/node/ts4.8/async_hooks.d.ts b/node_modules/@types/node/ts4.8/async_hooks.d.ts deleted file mode 100644 index 0667a6150af717a759e15e4fe04b6d29fe533411..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/async_hooks.d.ts +++ /dev/null @@ -1,539 +0,0 @@ -/** - * We strongly discourage the use of the `async_hooks` API. - * Other APIs that can cover most of its use cases include: - * - * * `AsyncLocalStorage` tracks async context - * * `process.getActiveResourcesInfo()` tracks active resources - * - * The `node:async_hooks` module provides an API to track asynchronous resources. - * It can be accessed using: - * - * ```js - * import async_hooks from 'node:async_hooks'; - * ``` - * @experimental - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/async_hooks.js) - */ -declare module "async_hooks" { - /** - * ```js - * import { executionAsyncId } from 'node:async_hooks'; - * import fs from 'node:fs'; - * - * console.log(executionAsyncId()); // 1 - bootstrap - * const path = '.'; - * fs.open(path, 'r', (err, fd) => { - * console.log(executionAsyncId()); // 6 - open() - * }); - * ``` - * - * The ID returned from `executionAsyncId()` is related to execution timing, not - * causality (which is covered by `triggerAsyncId()`): - * - * ```js - * const server = net.createServer((conn) => { - * // Returns the ID of the server, not of the new connection, because the - * // callback runs in the execution scope of the server's MakeCallback(). - * async_hooks.executionAsyncId(); - * - * }).listen(port, () => { - * // Returns the ID of a TickObject (process.nextTick()) because all - * // callbacks passed to .listen() are wrapped in a nextTick(). - * async_hooks.executionAsyncId(); - * }); - * ``` - * - * Promise contexts may not get precise `executionAsyncIds` by default. - * See the section on `promise execution tracking`. - * @since v8.1.0 - * @return The `asyncId` of the current execution context. Useful to track when something calls. - */ - function executionAsyncId(): number; - /** - * Resource objects returned by `executionAsyncResource()` are most often internal - * Node.js handle objects with undocumented APIs. Using any functions or properties - * on the object is likely to crash your application and should be avoided. - * - * Using `executionAsyncResource()` in the top-level execution context will - * return an empty object as there is no handle or request object to use, - * but having an object representing the top-level can be helpful. - * - * ```js - * import { open } from 'node:fs'; - * import { executionAsyncId, executionAsyncResource } from 'node:async_hooks'; - * - * console.log(executionAsyncId(), executionAsyncResource()); // 1 {} - * open(new URL(import.meta.url), 'r', (err, fd) => { - * console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap - * }); - * ``` - * - * This can be used to implement continuation local storage without the - * use of a tracking `Map` to store the metadata: - * - * ```js - * import { createServer } from 'node:http'; - * import { - * executionAsyncId, - * executionAsyncResource, - * createHook, - * } from 'async_hooks'; - * const sym = Symbol('state'); // Private symbol to avoid pollution - * - * createHook({ - * init(asyncId, type, triggerAsyncId, resource) { - * const cr = executionAsyncResource(); - * if (cr) { - * resource[sym] = cr[sym]; - * } - * }, - * }).enable(); - * - * const server = createServer((req, res) => { - * executionAsyncResource()[sym] = { state: req.url }; - * setTimeout(function() { - * res.end(JSON.stringify(executionAsyncResource()[sym])); - * }, 100); - * }).listen(3000); - * ``` - * @since v13.9.0, v12.17.0 - * @return The resource representing the current execution. Useful to store data within the resource. - */ - function executionAsyncResource(): object; - /** - * ```js - * const server = net.createServer((conn) => { - * // The resource that caused (or triggered) this callback to be called - * // was that of the new connection. Thus the return value of triggerAsyncId() - * // is the asyncId of "conn". - * async_hooks.triggerAsyncId(); - * - * }).listen(port, () => { - * // Even though all callbacks passed to .listen() are wrapped in a nextTick() - * // the callback itself exists because the call to the server's .listen() - * // was made. So the return value would be the ID of the server. - * async_hooks.triggerAsyncId(); - * }); - * ``` - * - * Promise contexts may not get valid `triggerAsyncId`s by default. See - * the section on `promise execution tracking`. - * @return The ID of the resource responsible for calling the callback that is currently being executed. - */ - function triggerAsyncId(): number; - interface HookCallbacks { - /** - * Called when a class is constructed that has the possibility to emit an asynchronous event. - * @param asyncId a unique ID for the async resource - * @param type the type of the async resource - * @param triggerAsyncId the unique ID of the async resource in whose execution context this async resource was created - * @param resource reference to the resource representing the async operation, needs to be released during destroy - */ - init?(asyncId: number, type: string, triggerAsyncId: number, resource: object): void; - /** - * When an asynchronous operation is initiated or completes a callback is called to notify the user. - * The before callback is called just before said callback is executed. - * @param asyncId the unique identifier assigned to the resource about to execute the callback. - */ - before?(asyncId: number): void; - /** - * Called immediately after the callback specified in before is completed. - * @param asyncId the unique identifier assigned to the resource which has executed the callback. - */ - after?(asyncId: number): void; - /** - * Called when a promise has resolve() called. This may not be in the same execution id - * as the promise itself. - * @param asyncId the unique id for the promise that was resolve()d. - */ - promiseResolve?(asyncId: number): void; - /** - * Called after the resource corresponding to asyncId is destroyed - * @param asyncId a unique ID for the async resource - */ - destroy?(asyncId: number): void; - } - interface AsyncHook { - /** - * Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop. - */ - enable(): this; - /** - * Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled. - */ - disable(): this; - } - /** - * Registers functions to be called for different lifetime events of each async - * operation. - * - * The callbacks `init()`/`before()`/`after()`/`destroy()` are called for the - * respective asynchronous event during a resource's lifetime. - * - * All callbacks are optional. For example, if only resource cleanup needs to - * be tracked, then only the `destroy` callback needs to be passed. The - * specifics of all functions that can be passed to `callbacks` is in the `Hook Callbacks` section. - * - * ```js - * import { createHook } from 'node:async_hooks'; - * - * const asyncHook = createHook({ - * init(asyncId, type, triggerAsyncId, resource) { }, - * destroy(asyncId) { }, - * }); - * ``` - * - * The callbacks will be inherited via the prototype chain: - * - * ```js - * class MyAsyncCallbacks { - * init(asyncId, type, triggerAsyncId, resource) { } - * destroy(asyncId) {} - * } - * - * class MyAddedCallbacks extends MyAsyncCallbacks { - * before(asyncId) { } - * after(asyncId) { } - * } - * - * const asyncHook = async_hooks.createHook(new MyAddedCallbacks()); - * ``` - * - * Because promises are asynchronous resources whose lifecycle is tracked - * via the async hooks mechanism, the `init()`, `before()`, `after()`, and`destroy()` callbacks _must not_ be async functions that return promises. - * @since v8.1.0 - * @param callbacks The `Hook Callbacks` to register - * @return Instance used for disabling and enabling hooks - */ - function createHook(callbacks: HookCallbacks): AsyncHook; - interface AsyncResourceOptions { - /** - * The ID of the execution context that created this async event. - * @default executionAsyncId() - */ - triggerAsyncId?: number | undefined; - /** - * Disables automatic `emitDestroy` when the object is garbage collected. - * This usually does not need to be set (even if `emitDestroy` is called - * manually), unless the resource's `asyncId` is retrieved and the - * sensitive API's `emitDestroy` is called with it. - * @default false - */ - requireManualDestroy?: boolean | undefined; - } - /** - * The class `AsyncResource` is designed to be extended by the embedder's async - * resources. Using this, users can easily trigger the lifetime events of their - * own resources. - * - * The `init` hook will trigger when an `AsyncResource` is instantiated. - * - * The following is an overview of the `AsyncResource` API. - * - * ```js - * import { AsyncResource, executionAsyncId } from 'node:async_hooks'; - * - * // AsyncResource() is meant to be extended. Instantiating a - * // new AsyncResource() also triggers init. If triggerAsyncId is omitted then - * // async_hook.executionAsyncId() is used. - * const asyncResource = new AsyncResource( - * type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false }, - * ); - * - * // Run a function in the execution context of the resource. This will - * // * establish the context of the resource - * // * trigger the AsyncHooks before callbacks - * // * call the provided function `fn` with the supplied arguments - * // * trigger the AsyncHooks after callbacks - * // * restore the original execution context - * asyncResource.runInAsyncScope(fn, thisArg, ...args); - * - * // Call AsyncHooks destroy callbacks. - * asyncResource.emitDestroy(); - * - * // Return the unique ID assigned to the AsyncResource instance. - * asyncResource.asyncId(); - * - * // Return the trigger ID for the AsyncResource instance. - * asyncResource.triggerAsyncId(); - * ``` - */ - class AsyncResource { - /** - * AsyncResource() is meant to be extended. Instantiating a - * new AsyncResource() also triggers init. If triggerAsyncId is omitted then - * async_hook.executionAsyncId() is used. - * @param type The type of async event. - * @param triggerAsyncId The ID of the execution context that created - * this async event (default: `executionAsyncId()`), or an - * AsyncResourceOptions object (since v9.3.0) - */ - constructor(type: string, triggerAsyncId?: number | AsyncResourceOptions); - /** - * Binds the given function to the current execution context. - * @since v14.8.0, v12.19.0 - * @param fn The function to bind to the current execution context. - * @param type An optional name to associate with the underlying `AsyncResource`. - */ - static bind any, ThisArg>( - fn: Func, - type?: string, - thisArg?: ThisArg, - ): Func; - /** - * Binds the given function to execute to this `AsyncResource`'s scope. - * @since v14.8.0, v12.19.0 - * @param fn The function to bind to the current `AsyncResource`. - */ - bind any>(fn: Func): Func; - /** - * Call the provided function with the provided arguments in the execution context - * of the async resource. This will establish the context, trigger the AsyncHooks - * before callbacks, call the function, trigger the AsyncHooks after callbacks, and - * then restore the original execution context. - * @since v9.6.0 - * @param fn The function to call in the execution context of this async resource. - * @param thisArg The receiver to be used for the function call. - * @param args Optional arguments to pass to the function. - */ - runInAsyncScope( - fn: (this: This, ...args: any[]) => Result, - thisArg?: This, - ...args: any[] - ): Result; - /** - * Call all `destroy` hooks. This should only ever be called once. An error will - * be thrown if it is called more than once. This **must** be manually called. If - * the resource is left to be collected by the GC then the `destroy` hooks will - * never be called. - * @return A reference to `asyncResource`. - */ - emitDestroy(): this; - /** - * @return The unique `asyncId` assigned to the resource. - */ - asyncId(): number; - /** - * @return The same `triggerAsyncId` that is passed to the `AsyncResource` constructor. - */ - triggerAsyncId(): number; - } - /** - * This class creates stores that stay coherent through asynchronous operations. - * - * While you can create your own implementation on top of the `node:async_hooks`module, `AsyncLocalStorage` should be preferred as it is a performant and memory - * safe implementation that involves significant optimizations that are non-obvious - * to implement. - * - * The following example uses `AsyncLocalStorage` to build a simple logger - * that assigns IDs to incoming HTTP requests and includes them in messages - * logged within each request. - * - * ```js - * import http from 'node:http'; - * import { AsyncLocalStorage } from 'node:async_hooks'; - * - * const asyncLocalStorage = new AsyncLocalStorage(); - * - * function logWithId(msg) { - * const id = asyncLocalStorage.getStore(); - * console.log(`${id !== undefined ? id : '-'}:`, msg); - * } - * - * let idSeq = 0; - * http.createServer((req, res) => { - * asyncLocalStorage.run(idSeq++, () => { - * logWithId('start'); - * // Imagine any chain of async operations here - * setImmediate(() => { - * logWithId('finish'); - * res.end(); - * }); - * }); - * }).listen(8080); - * - * http.get('http://localhost:8080'); - * http.get('http://localhost:8080'); - * // Prints: - * // 0: start - * // 1: start - * // 0: finish - * // 1: finish - * ``` - * - * Each instance of `AsyncLocalStorage` maintains an independent storage context. - * Multiple instances can safely exist simultaneously without risk of interfering - * with each other's data. - * @since v13.10.0, v12.17.0 - */ - class AsyncLocalStorage { - /** - * Binds the given function to the current execution context. - * @since v19.8.0 - * @experimental - * @param fn The function to bind to the current execution context. - * @return A new function that calls `fn` within the captured execution context. - */ - static bind any>(fn: Func): Func; - /** - * Captures the current execution context and returns a function that accepts a - * function as an argument. Whenever the returned function is called, it - * calls the function passed to it within the captured context. - * - * ```js - * const asyncLocalStorage = new AsyncLocalStorage(); - * const runInAsyncScope = asyncLocalStorage.run(123, () => AsyncLocalStorage.snapshot()); - * const result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore())); - * console.log(result); // returns 123 - * ``` - * - * AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple - * async context tracking purposes, for example: - * - * ```js - * class Foo { - * #runInAsyncScope = AsyncLocalStorage.snapshot(); - * - * get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); } - * } - * - * const foo = asyncLocalStorage.run(123, () => new Foo()); - * console.log(asyncLocalStorage.run(321, () => foo.get())); // returns 123 - * ``` - * @since v19.8.0 - * @experimental - * @return A new function with the signature `(fn: (...args) : R, ...args) : R`. - */ - static snapshot(): (fn: (...args: TArgs) => R, ...args: TArgs) => R; - /** - * Disables the instance of `AsyncLocalStorage`. All subsequent calls - * to `asyncLocalStorage.getStore()` will return `undefined` until`asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()` is called again. - * - * When calling `asyncLocalStorage.disable()`, all current contexts linked to the - * instance will be exited. - * - * Calling `asyncLocalStorage.disable()` is required before the`asyncLocalStorage` can be garbage collected. This does not apply to stores - * provided by the `asyncLocalStorage`, as those objects are garbage collected - * along with the corresponding async resources. - * - * Use this method when the `asyncLocalStorage` is not in use anymore - * in the current process. - * @since v13.10.0, v12.17.0 - * @experimental - */ - disable(): void; - /** - * Returns the current store. - * If called outside of an asynchronous context initialized by - * calling `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()`, it - * returns `undefined`. - * @since v13.10.0, v12.17.0 - */ - getStore(): T | undefined; - /** - * Runs a function synchronously within a context and returns its - * return value. The store is not accessible outside of the callback function. - * The store is accessible to any asynchronous operations created within the - * callback. - * - * The optional `args` are passed to the callback function. - * - * If the callback function throws an error, the error is thrown by `run()` too. - * The stacktrace is not impacted by this call and the context is exited. - * - * Example: - * - * ```js - * const store = { id: 2 }; - * try { - * asyncLocalStorage.run(store, () => { - * asyncLocalStorage.getStore(); // Returns the store object - * setTimeout(() => { - * asyncLocalStorage.getStore(); // Returns the store object - * }, 200); - * throw new Error(); - * }); - * } catch (e) { - * asyncLocalStorage.getStore(); // Returns undefined - * // The error will be caught here - * } - * ``` - * @since v13.10.0, v12.17.0 - */ - run(store: T, callback: () => R): R; - run(store: T, callback: (...args: TArgs) => R, ...args: TArgs): R; - /** - * Runs a function synchronously outside of a context and returns its - * return value. The store is not accessible within the callback function or - * the asynchronous operations created within the callback. Any `getStore()`call done within the callback function will always return `undefined`. - * - * The optional `args` are passed to the callback function. - * - * If the callback function throws an error, the error is thrown by `exit()` too. - * The stacktrace is not impacted by this call and the context is re-entered. - * - * Example: - * - * ```js - * // Within a call to run - * try { - * asyncLocalStorage.getStore(); // Returns the store object or value - * asyncLocalStorage.exit(() => { - * asyncLocalStorage.getStore(); // Returns undefined - * throw new Error(); - * }); - * } catch (e) { - * asyncLocalStorage.getStore(); // Returns the same object or value - * // The error will be caught here - * } - * ``` - * @since v13.10.0, v12.17.0 - * @experimental - */ - exit(callback: (...args: TArgs) => R, ...args: TArgs): R; - /** - * Transitions into the context for the remainder of the current - * synchronous execution and then persists the store through any following - * asynchronous calls. - * - * Example: - * - * ```js - * const store = { id: 1 }; - * // Replaces previous store with the given store object - * asyncLocalStorage.enterWith(store); - * asyncLocalStorage.getStore(); // Returns the store object - * someAsyncOperation(() => { - * asyncLocalStorage.getStore(); // Returns the same object - * }); - * ``` - * - * This transition will continue for the _entire_ synchronous execution. - * This means that if, for example, the context is entered within an event - * handler subsequent event handlers will also run within that context unless - * specifically bound to another context with an `AsyncResource`. That is why`run()` should be preferred over `enterWith()` unless there are strong reasons - * to use the latter method. - * - * ```js - * const store = { id: 1 }; - * - * emitter.on('my-event', () => { - * asyncLocalStorage.enterWith(store); - * }); - * emitter.on('my-event', () => { - * asyncLocalStorage.getStore(); // Returns the same object - * }); - * - * asyncLocalStorage.getStore(); // Returns undefined - * emitter.emit('my-event'); - * asyncLocalStorage.getStore(); // Returns the same object - * ``` - * @since v13.11.0, v12.17.0 - * @experimental - */ - enterWith(store: T): void; - } -} -declare module "node:async_hooks" { - export * from "async_hooks"; -} diff --git a/node_modules/@types/node/ts4.8/buffer.d.ts b/node_modules/@types/node/ts4.8/buffer.d.ts deleted file mode 100644 index 2fa2e745ffbedb44e198850165d2fd17968b8775..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/buffer.d.ts +++ /dev/null @@ -1,2362 +0,0 @@ -/** - * `Buffer` objects are used to represent a fixed-length sequence of bytes. Many - * Node.js APIs support `Buffer`s. - * - * The `Buffer` class is a subclass of JavaScript's [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) class and - * extends it with methods that cover additional use cases. Node.js APIs accept - * plain [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) s wherever `Buffer`s are supported as well. - * - * While the `Buffer` class is available within the global scope, it is still - * recommended to explicitly reference it via an import or require statement. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * // Creates a zero-filled Buffer of length 10. - * const buf1 = Buffer.alloc(10); - * - * // Creates a Buffer of length 10, - * // filled with bytes which all have the value `1`. - * const buf2 = Buffer.alloc(10, 1); - * - * // Creates an uninitialized buffer of length 10. - * // This is faster than calling Buffer.alloc() but the returned - * // Buffer instance might contain old data that needs to be - * // overwritten using fill(), write(), or other functions that fill the Buffer's - * // contents. - * const buf3 = Buffer.allocUnsafe(10); - * - * // Creates a Buffer containing the bytes [1, 2, 3]. - * const buf4 = Buffer.from([1, 2, 3]); - * - * // Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries - * // are all truncated using `(value & 255)` to fit into the range 0–255. - * const buf5 = Buffer.from([257, 257.5, -255, '1']); - * - * // Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést': - * // [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation) - * // [116, 195, 169, 115, 116] (in decimal notation) - * const buf6 = Buffer.from('tést'); - * - * // Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74]. - * const buf7 = Buffer.from('tést', 'latin1'); - * ``` - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/buffer.js) - */ -declare module "buffer" { - import { BinaryLike } from "node:crypto"; - import { ReadableStream as WebReadableStream } from "node:stream/web"; - /** - * This function returns `true` if `input` contains only valid UTF-8-encoded data, - * including the case in which `input` is empty. - * - * Throws if the `input` is a detached array buffer. - * @since v19.4.0, v18.14.0 - * @param input The input to validate. - */ - export function isUtf8(input: Buffer | ArrayBuffer | NodeJS.TypedArray): boolean; - /** - * This function returns `true` if `input` contains only valid ASCII-encoded data, - * including the case in which `input` is empty. - * - * Throws if the `input` is a detached array buffer. - * @since v19.6.0, v18.15.0 - * @param input The input to validate. - */ - export function isAscii(input: Buffer | ArrayBuffer | NodeJS.TypedArray): boolean; - export const INSPECT_MAX_BYTES: number; - export const kMaxLength: number; - export const kStringMaxLength: number; - export const constants: { - MAX_LENGTH: number; - MAX_STRING_LENGTH: number; - }; - export type TranscodeEncoding = - | "ascii" - | "utf8" - | "utf-8" - | "utf16le" - | "utf-16le" - | "ucs2" - | "ucs-2" - | "latin1" - | "binary"; - /** - * Re-encodes the given `Buffer` or `Uint8Array` instance from one character - * encoding to another. Returns a new `Buffer` instance. - * - * Throws if the `fromEnc` or `toEnc` specify invalid character encodings or if - * conversion from `fromEnc` to `toEnc` is not permitted. - * - * Encodings supported by `buffer.transcode()` are: `'ascii'`, `'utf8'`,`'utf16le'`, `'ucs2'`, `'latin1'`, and `'binary'`. - * - * The transcoding process will use substitution characters if a given byte - * sequence cannot be adequately represented in the target encoding. For instance: - * - * ```js - * import { Buffer, transcode } from 'node:buffer'; - * - * const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii'); - * console.log(newBuf.toString('ascii')); - * // Prints: '?' - * ``` - * - * Because the Euro (`€`) sign is not representable in US-ASCII, it is replaced - * with `?` in the transcoded `Buffer`. - * @since v7.1.0 - * @param source A `Buffer` or `Uint8Array` instance. - * @param fromEnc The current encoding. - * @param toEnc To target encoding. - */ - export function transcode(source: Uint8Array, fromEnc: TranscodeEncoding, toEnc: TranscodeEncoding): Buffer; - export const SlowBuffer: { - /** @deprecated since v6.0.0, use `Buffer.allocUnsafeSlow()` */ - new(size: number): Buffer; - prototype: Buffer; - }; - /** - * Resolves a `'blob:nodedata:...'` an associated `Blob` object registered using - * a prior call to `URL.createObjectURL()`. - * @since v16.7.0 - * @experimental - * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. - */ - export function resolveObjectURL(id: string): Blob | undefined; - export { Buffer }; - /** - * @experimental - */ - export interface BlobOptions { - /** - * @default 'utf8' - */ - encoding?: BufferEncoding | undefined; - /** - * The Blob content-type. The intent is for `type` to convey - * the MIME media type of the data, however no validation of the type format - * is performed. - */ - type?: string | undefined; - } - /** - * A [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) encapsulates immutable, raw data that can be safely shared across - * multiple worker threads. - * @since v15.7.0, v14.18.0 - */ - export class Blob { - /** - * The total size of the `Blob` in bytes. - * @since v15.7.0, v14.18.0 - */ - readonly size: number; - /** - * The content-type of the `Blob`. - * @since v15.7.0, v14.18.0 - */ - readonly type: string; - /** - * Creates a new `Blob` object containing a concatenation of the given sources. - * - * {ArrayBuffer}, {TypedArray}, {DataView}, and {Buffer} sources are copied into - * the 'Blob' and can therefore be safely modified after the 'Blob' is created. - * - * String sources are also copied into the `Blob`. - */ - constructor(sources: Array, options?: BlobOptions); - /** - * Returns a promise that fulfills with an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing a copy of - * the `Blob` data. - * @since v15.7.0, v14.18.0 - */ - arrayBuffer(): Promise; - /** - * Creates and returns a new `Blob` containing a subset of this `Blob` objects - * data. The original `Blob` is not altered. - * @since v15.7.0, v14.18.0 - * @param start The starting index. - * @param end The ending index. - * @param type The content-type for the new `Blob` - */ - slice(start?: number, end?: number, type?: string): Blob; - /** - * Returns a promise that fulfills with the contents of the `Blob` decoded as a - * UTF-8 string. - * @since v15.7.0, v14.18.0 - */ - text(): Promise; - /** - * Returns a new `ReadableStream` that allows the content of the `Blob` to be read. - * @since v16.7.0 - */ - stream(): WebReadableStream; - } - export interface FileOptions { - /** - * One of either `'transparent'` or `'native'`. When set to `'native'`, line endings in string source parts will be - * converted to the platform native line-ending as specified by `require('node:os').EOL`. - */ - endings?: "native" | "transparent"; - /** The File content-type. */ - type?: string; - /** The last modified date of the file. `Default`: Date.now(). */ - lastModified?: number; - } - /** - * A [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) provides information about files. - * @since v19.2.0, v18.13.0 - */ - export class File extends Blob { - constructor(sources: Array, fileName: string, options?: FileOptions); - /** - * The name of the `File`. - * @since v19.2.0, v18.13.0 - */ - readonly name: string; - /** - * The last modified date of the `File`. - * @since v19.2.0, v18.13.0 - */ - readonly lastModified: number; - } - export import atob = globalThis.atob; - export import btoa = globalThis.btoa; - import { Blob as NodeBlob } from "buffer"; - // This conditional type will be the existing global Blob in a browser, or - // the copy below in a Node environment. - type __Blob = typeof globalThis extends { onmessage: any; Blob: any } ? {} : NodeBlob; - global { - namespace NodeJS { - export { BufferEncoding }; - } - // Buffer class - type BufferEncoding = - | "ascii" - | "utf8" - | "utf-8" - | "utf16le" - | "utf-16le" - | "ucs2" - | "ucs-2" - | "base64" - | "base64url" - | "latin1" - | "binary" - | "hex"; - type WithImplicitCoercion = - | T - | { - valueOf(): T; - }; - /** - * Raw data is stored in instances of the Buffer class. - * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. - * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'base64url'|'binary'(deprecated)|'hex' - */ - interface BufferConstructor { - /** - * Allocates a new buffer containing the given {str}. - * - * @param str String to store in buffer. - * @param encoding encoding to use, optional. Default is 'utf8' - * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. - */ - new(str: string, encoding?: BufferEncoding): Buffer; - /** - * Allocates a new buffer of {size} octets. - * - * @param size count of octets to allocate. - * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). - */ - new(size: number): Buffer; - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. - */ - new(array: Uint8Array): Buffer; - /** - * Produces a Buffer backed by the same allocated memory as - * the given {ArrayBuffer}/{SharedArrayBuffer}. - * - * @param arrayBuffer The ArrayBuffer with which to share memory. - * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. - */ - new(arrayBuffer: ArrayBuffer | SharedArrayBuffer): Buffer; - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. - */ - new(array: readonly any[]): Buffer; - /** - * Copies the passed {buffer} data onto a new {Buffer} instance. - * - * @param buffer The buffer to copy. - * @deprecated since v10.0.0 - Use `Buffer.from(buffer)` instead. - */ - new(buffer: Buffer): Buffer; - /** - * Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`. - * Array entries outside that range will be truncated to fit into it. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. - * const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); - * ``` - * - * If `array` is an `Array`\-like object (that is, one with a `length` property of - * type `number`), it is treated as if it is an array, unless it is a `Buffer` or - * a `Uint8Array`. This means all other `TypedArray` variants get treated as an`Array`. To create a `Buffer` from the bytes backing a `TypedArray`, use `Buffer.copyBytesFrom()`. - * - * A `TypeError` will be thrown if `array` is not an `Array` or another type - * appropriate for `Buffer.from()` variants. - * - * `Buffer.from(array)` and `Buffer.from(string)` may also use the internal`Buffer` pool like `Buffer.allocUnsafe()` does. - * @since v5.10.0 - */ - from( - arrayBuffer: WithImplicitCoercion, - byteOffset?: number, - length?: number, - ): Buffer; - /** - * Creates a new Buffer using the passed {data} - * @param data data to create a new Buffer - */ - from(data: Uint8Array | readonly number[]): Buffer; - from(data: WithImplicitCoercion): Buffer; - /** - * Creates a new Buffer containing the given JavaScript string {str}. - * If provided, the {encoding} parameter identifies the character encoding. - * If not provided, {encoding} defaults to 'utf8'. - */ - from( - str: - | WithImplicitCoercion - | { - [Symbol.toPrimitive](hint: "string"): string; - }, - encoding?: BufferEncoding, - ): Buffer; - /** - * Creates a new Buffer using the passed {data} - * @param values to create a new Buffer - */ - of(...items: number[]): Buffer; - /** - * Returns `true` if `obj` is a `Buffer`, `false` otherwise. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * Buffer.isBuffer(Buffer.alloc(10)); // true - * Buffer.isBuffer(Buffer.from('foo')); // true - * Buffer.isBuffer('a string'); // false - * Buffer.isBuffer([]); // false - * Buffer.isBuffer(new Uint8Array(1024)); // false - * ``` - * @since v0.1.101 - */ - isBuffer(obj: any): obj is Buffer; - /** - * Returns `true` if `encoding` is the name of a supported character encoding, - * or `false` otherwise. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * console.log(Buffer.isEncoding('utf8')); - * // Prints: true - * - * console.log(Buffer.isEncoding('hex')); - * // Prints: true - * - * console.log(Buffer.isEncoding('utf/8')); - * // Prints: false - * - * console.log(Buffer.isEncoding('')); - * // Prints: false - * ``` - * @since v0.9.1 - * @param encoding A character encoding name to check. - */ - isEncoding(encoding: string): encoding is BufferEncoding; - /** - * Returns the byte length of a string when encoded using `encoding`. - * This is not the same as [`String.prototype.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length), which does not account - * for the encoding that is used to convert the string into bytes. - * - * For `'base64'`, `'base64url'`, and `'hex'`, this function assumes valid input. - * For strings that contain non-base64/hex-encoded data (e.g. whitespace), the - * return value might be greater than the length of a `Buffer` created from the - * string. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const str = '\u00bd + \u00bc = \u00be'; - * - * console.log(`${str}: ${str.length} characters, ` + - * `${Buffer.byteLength(str, 'utf8')} bytes`); - * // Prints: ½ + ¼ = ¾: 9 characters, 12 bytes - * ``` - * - * When `string` is a - * `Buffer`/[`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)/[`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/- - * Reference/Global_Objects/TypedArray)/[`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)/[`SharedArrayBuffer`](https://develop- - * er.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer), the byte length as reported by `.byteLength`is returned. - * @since v0.1.90 - * @param string A value to calculate the length of. - * @param [encoding='utf8'] If `string` is a string, this is its encoding. - * @return The number of bytes contained within `string`. - */ - byteLength( - string: string | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer, - encoding?: BufferEncoding, - ): number; - /** - * Returns a new `Buffer` which is the result of concatenating all the `Buffer`instances in the `list` together. - * - * If the list has no items, or if the `totalLength` is 0, then a new zero-length`Buffer` is returned. - * - * If `totalLength` is not provided, it is calculated from the `Buffer` instances - * in `list` by adding their lengths. - * - * If `totalLength` is provided, it is coerced to an unsigned integer. If the - * combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is - * truncated to `totalLength`. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * // Create a single `Buffer` from a list of three `Buffer` instances. - * - * const buf1 = Buffer.alloc(10); - * const buf2 = Buffer.alloc(14); - * const buf3 = Buffer.alloc(18); - * const totalLength = buf1.length + buf2.length + buf3.length; - * - * console.log(totalLength); - * // Prints: 42 - * - * const bufA = Buffer.concat([buf1, buf2, buf3], totalLength); - * - * console.log(bufA); - * // Prints: - * console.log(bufA.length); - * // Prints: 42 - * ``` - * - * `Buffer.concat()` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does. - * @since v0.7.11 - * @param list List of `Buffer` or {@link Uint8Array} instances to concatenate. - * @param totalLength Total length of the `Buffer` instances in `list` when concatenated. - */ - concat(list: readonly Uint8Array[], totalLength?: number): Buffer; - /** - * Copies the underlying memory of `view` into a new `Buffer`. - * - * ```js - * const u16 = new Uint16Array([0, 0xffff]); - * const buf = Buffer.copyBytesFrom(u16, 1, 1); - * u16[1] = 0; - * console.log(buf.length); // 2 - * console.log(buf[0]); // 255 - * console.log(buf[1]); // 255 - * ``` - * @since v19.8.0 - * @param view The {TypedArray} to copy. - * @param [offset=': 0'] The starting offset within `view`. - * @param [length=view.length - offset] The number of elements from `view` to copy. - */ - copyBytesFrom(view: NodeJS.TypedArray, offset?: number, length?: number): Buffer; - /** - * Compares `buf1` to `buf2`, typically for the purpose of sorting arrays of`Buffer` instances. This is equivalent to calling `buf1.compare(buf2)`. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf1 = Buffer.from('1234'); - * const buf2 = Buffer.from('0123'); - * const arr = [buf1, buf2]; - * - * console.log(arr.sort(Buffer.compare)); - * // Prints: [ , ] - * // (This result is equal to: [buf2, buf1].) - * ``` - * @since v0.11.13 - * @return Either `-1`, `0`, or `1`, depending on the result of the comparison. See `compare` for details. - */ - compare(buf1: Uint8Array, buf2: Uint8Array): -1 | 0 | 1; - /** - * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.alloc(5); - * - * console.log(buf); - * // Prints: - * ``` - * - * If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. - * - * If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.alloc(5, 'a'); - * - * console.log(buf); - * // Prints: - * ``` - * - * If both `fill` and `encoding` are specified, the allocated `Buffer` will be - * initialized by calling `buf.fill(fill, encoding)`. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); - * - * console.log(buf); - * // Prints: - * ``` - * - * Calling `Buffer.alloc()` can be measurably slower than the alternative `Buffer.allocUnsafe()` but ensures that the newly created `Buffer` instance - * contents will never contain sensitive data from previous allocations, including - * data that might not have been allocated for `Buffer`s. - * - * A `TypeError` will be thrown if `size` is not a number. - * @since v5.10.0 - * @param size The desired length of the new `Buffer`. - * @param [fill=0] A value to pre-fill the new `Buffer` with. - * @param [encoding='utf8'] If `fill` is a string, this is its encoding. - */ - alloc(size: number, fill?: string | Uint8Array | number, encoding?: BufferEncoding): Buffer; - /** - * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. - * - * The underlying memory for `Buffer` instances created in this way is _not_ - * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.allocUnsafe(10); - * - * console.log(buf); - * // Prints (contents may vary): - * - * buf.fill(0); - * - * console.log(buf); - * // Prints: - * ``` - * - * A `TypeError` will be thrown if `size` is not a number. - * - * The `Buffer` module pre-allocates an internal `Buffer` instance of - * size `Buffer.poolSize` that is used as a pool for the fast allocation of new`Buffer` instances created using `Buffer.allocUnsafe()`, `Buffer.from(array)`, - * and `Buffer.concat()` only when `size` is less than`Buffer.poolSize >>> 1` (floor of `Buffer.poolSize` divided by two). - * - * Use of this pre-allocated internal memory pool is a key difference between - * calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. - * Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`pool, while `Buffer.allocUnsafe(size).fill(fill)`_will_ use the internal`Buffer` pool if `size` is less - * than or equal to half `Buffer.poolSize`. The - * difference is subtle but can be important when an application requires the - * additional performance that `Buffer.allocUnsafe()` provides. - * @since v5.10.0 - * @param size The desired length of the new `Buffer`. - */ - allocUnsafe(size: number): Buffer; - /** - * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. A zero-length `Buffer` is created if - * `size` is 0. - * - * The underlying memory for `Buffer` instances created in this way is _not_ - * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `buf.fill(0)` to initialize - * such `Buffer` instances with zeroes. - * - * When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, - * allocations under 4 KiB are sliced from a single pre-allocated `Buffer`. This - * allows applications to avoid the garbage collection overhead of creating many - * individually allocated `Buffer` instances. This approach improves both - * performance and memory usage by eliminating the need to track and clean up as - * many individual `ArrayBuffer` objects. - * - * However, in the case where a developer may need to retain a small chunk of - * memory from a pool for an indeterminate amount of time, it may be appropriate - * to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and - * then copying out the relevant bits. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * // Need to keep around a few small chunks of memory. - * const store = []; - * - * socket.on('readable', () => { - * let data; - * while (null !== (data = readable.read())) { - * // Allocate for retained data. - * const sb = Buffer.allocUnsafeSlow(10); - * - * // Copy the data into the new allocation. - * data.copy(sb, 0, 0, 10); - * - * store.push(sb); - * } - * }); - * ``` - * - * A `TypeError` will be thrown if `size` is not a number. - * @since v5.12.0 - * @param size The desired length of the new `Buffer`. - */ - allocUnsafeSlow(size: number): Buffer; - /** - * This is the size (in bytes) of pre-allocated internal `Buffer` instances used - * for pooling. This value may be modified. - * @since v0.11.3 - */ - poolSize: number; - } - interface Buffer extends Uint8Array { - /** - * Writes `string` to `buf` at `offset` according to the character encoding in`encoding`. The `length` parameter is the number of bytes to write. If `buf` did - * not contain enough space to fit the entire string, only part of `string` will be - * written. However, partially encoded characters will not be written. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.alloc(256); - * - * const len = buf.write('\u00bd + \u00bc = \u00be', 0); - * - * console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`); - * // Prints: 12 bytes: ½ + ¼ = ¾ - * - * const buffer = Buffer.alloc(10); - * - * const length = buffer.write('abcd', 8); - * - * console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`); - * // Prints: 2 bytes : ab - * ``` - * @since v0.1.90 - * @param string String to write to `buf`. - * @param [offset=0] Number of bytes to skip before starting to write `string`. - * @param [length=buf.length - offset] Maximum number of bytes to write (written bytes will not exceed `buf.length - offset`). - * @param [encoding='utf8'] The character encoding of `string`. - * @return Number of bytes written. - */ - write(string: string, encoding?: BufferEncoding): number; - write(string: string, offset: number, encoding?: BufferEncoding): number; - write(string: string, offset: number, length: number, encoding?: BufferEncoding): number; - /** - * Decodes `buf` to a string according to the specified character encoding in`encoding`. `start` and `end` may be passed to decode only a subset of `buf`. - * - * If `encoding` is `'utf8'` and a byte sequence in the input is not valid UTF-8, - * then each invalid byte is replaced with the replacement character `U+FFFD`. - * - * The maximum length of a string instance (in UTF-16 code units) is available - * as {@link constants.MAX_STRING_LENGTH}. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf1 = Buffer.allocUnsafe(26); - * - * for (let i = 0; i < 26; i++) { - * // 97 is the decimal ASCII value for 'a'. - * buf1[i] = i + 97; - * } - * - * console.log(buf1.toString('utf8')); - * // Prints: abcdefghijklmnopqrstuvwxyz - * console.log(buf1.toString('utf8', 0, 5)); - * // Prints: abcde - * - * const buf2 = Buffer.from('tést'); - * - * console.log(buf2.toString('hex')); - * // Prints: 74c3a97374 - * console.log(buf2.toString('utf8', 0, 3)); - * // Prints: té - * console.log(buf2.toString(undefined, 0, 3)); - * // Prints: té - * ``` - * @since v0.1.90 - * @param [encoding='utf8'] The character encoding to use. - * @param [start=0] The byte offset to start decoding at. - * @param [end=buf.length] The byte offset to stop decoding at (not inclusive). - */ - toString(encoding?: BufferEncoding, start?: number, end?: number): string; - /** - * Returns a JSON representation of `buf`. [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) implicitly calls - * this function when stringifying a `Buffer` instance. - * - * `Buffer.from()` accepts objects in the format returned from this method. - * In particular, `Buffer.from(buf.toJSON())` works like `Buffer.from(buf)`. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]); - * const json = JSON.stringify(buf); - * - * console.log(json); - * // Prints: {"type":"Buffer","data":[1,2,3,4,5]} - * - * const copy = JSON.parse(json, (key, value) => { - * return value && value.type === 'Buffer' ? - * Buffer.from(value) : - * value; - * }); - * - * console.log(copy); - * // Prints: - * ``` - * @since v0.9.2 - */ - toJSON(): { - type: "Buffer"; - data: number[]; - }; - /** - * Returns `true` if both `buf` and `otherBuffer` have exactly the same bytes,`false` otherwise. Equivalent to `buf.compare(otherBuffer) === 0`. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf1 = Buffer.from('ABC'); - * const buf2 = Buffer.from('414243', 'hex'); - * const buf3 = Buffer.from('ABCD'); - * - * console.log(buf1.equals(buf2)); - * // Prints: true - * console.log(buf1.equals(buf3)); - * // Prints: false - * ``` - * @since v0.11.13 - * @param otherBuffer A `Buffer` or {@link Uint8Array} with which to compare `buf`. - */ - equals(otherBuffer: Uint8Array): boolean; - /** - * Compares `buf` with `target` and returns a number indicating whether `buf`comes before, after, or is the same as `target` in sort order. - * Comparison is based on the actual sequence of bytes in each `Buffer`. - * - * * `0` is returned if `target` is the same as `buf` - * * `1` is returned if `target` should come _before_`buf` when sorted. - * * `-1` is returned if `target` should come _after_`buf` when sorted. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf1 = Buffer.from('ABC'); - * const buf2 = Buffer.from('BCD'); - * const buf3 = Buffer.from('ABCD'); - * - * console.log(buf1.compare(buf1)); - * // Prints: 0 - * console.log(buf1.compare(buf2)); - * // Prints: -1 - * console.log(buf1.compare(buf3)); - * // Prints: -1 - * console.log(buf2.compare(buf1)); - * // Prints: 1 - * console.log(buf2.compare(buf3)); - * // Prints: 1 - * console.log([buf1, buf2, buf3].sort(Buffer.compare)); - * // Prints: [ , , ] - * // (This result is equal to: [buf1, buf3, buf2].) - * ``` - * - * The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd`arguments can be used to limit the comparison to specific ranges within `target`and `buf` respectively. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]); - * const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]); - * - * console.log(buf1.compare(buf2, 5, 9, 0, 4)); - * // Prints: 0 - * console.log(buf1.compare(buf2, 0, 6, 4)); - * // Prints: -1 - * console.log(buf1.compare(buf2, 5, 6, 5)); - * // Prints: 1 - * ``` - * - * `ERR_OUT_OF_RANGE` is thrown if `targetStart < 0`, `sourceStart < 0`,`targetEnd > target.byteLength`, or `sourceEnd > source.byteLength`. - * @since v0.11.13 - * @param target A `Buffer` or {@link Uint8Array} with which to compare `buf`. - * @param [targetStart=0] The offset within `target` at which to begin comparison. - * @param [targetEnd=target.length] The offset within `target` at which to end comparison (not inclusive). - * @param [sourceStart=0] The offset within `buf` at which to begin comparison. - * @param [sourceEnd=buf.length] The offset within `buf` at which to end comparison (not inclusive). - */ - compare( - target: Uint8Array, - targetStart?: number, - targetEnd?: number, - sourceStart?: number, - sourceEnd?: number, - ): -1 | 0 | 1; - /** - * Copies data from a region of `buf` to a region in `target`, even if the `target`memory region overlaps with `buf`. - * - * [`TypedArray.prototype.set()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set) performs the same operation, and is available - * for all TypedArrays, including Node.js `Buffer`s, although it takes - * different function arguments. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * // Create two `Buffer` instances. - * const buf1 = Buffer.allocUnsafe(26); - * const buf2 = Buffer.allocUnsafe(26).fill('!'); - * - * for (let i = 0; i < 26; i++) { - * // 97 is the decimal ASCII value for 'a'. - * buf1[i] = i + 97; - * } - * - * // Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`. - * buf1.copy(buf2, 8, 16, 20); - * // This is equivalent to: - * // buf2.set(buf1.subarray(16, 20), 8); - * - * console.log(buf2.toString('ascii', 0, 25)); - * // Prints: !!!!!!!!qrst!!!!!!!!!!!!! - * ``` - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * // Create a `Buffer` and copy data from one region to an overlapping region - * // within the same `Buffer`. - * - * const buf = Buffer.allocUnsafe(26); - * - * for (let i = 0; i < 26; i++) { - * // 97 is the decimal ASCII value for 'a'. - * buf[i] = i + 97; - * } - * - * buf.copy(buf, 0, 4, 10); - * - * console.log(buf.toString()); - * // Prints: efghijghijklmnopqrstuvwxyz - * ``` - * @since v0.1.90 - * @param target A `Buffer` or {@link Uint8Array} to copy into. - * @param [targetStart=0] The offset within `target` at which to begin writing. - * @param [sourceStart=0] The offset within `buf` from which to begin copying. - * @param [sourceEnd=buf.length] The offset within `buf` at which to stop copying (not inclusive). - * @return The number of bytes copied. - */ - copy(target: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; - /** - * Returns a new `Buffer` that references the same memory as the original, but - * offset and cropped by the `start` and `end` indices. - * - * This method is not compatible with the `Uint8Array.prototype.slice()`, - * which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.from('buffer'); - * - * const copiedBuf = Uint8Array.prototype.slice.call(buf); - * copiedBuf[0]++; - * console.log(copiedBuf.toString()); - * // Prints: cuffer - * - * console.log(buf.toString()); - * // Prints: buffer - * - * // With buf.slice(), the original buffer is modified. - * const notReallyCopiedBuf = buf.slice(); - * notReallyCopiedBuf[0]++; - * console.log(notReallyCopiedBuf.toString()); - * // Prints: cuffer - * console.log(buf.toString()); - * // Also prints: cuffer (!) - * ``` - * @since v0.3.0 - * @deprecated Use `subarray` instead. - * @param [start=0] Where the new `Buffer` will start. - * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). - */ - slice(start?: number, end?: number): Buffer; - /** - * Returns a new `Buffer` that references the same memory as the original, but - * offset and cropped by the `start` and `end` indices. - * - * Specifying `end` greater than `buf.length` will return the same result as - * that of `end` equal to `buf.length`. - * - * This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray). - * - * Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte - * // from the original `Buffer`. - * - * const buf1 = Buffer.allocUnsafe(26); - * - * for (let i = 0; i < 26; i++) { - * // 97 is the decimal ASCII value for 'a'. - * buf1[i] = i + 97; - * } - * - * const buf2 = buf1.subarray(0, 3); - * - * console.log(buf2.toString('ascii', 0, buf2.length)); - * // Prints: abc - * - * buf1[0] = 33; - * - * console.log(buf2.toString('ascii', 0, buf2.length)); - * // Prints: !bc - * ``` - * - * Specifying negative indexes causes the slice to be generated relative to the - * end of `buf` rather than the beginning. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.from('buffer'); - * - * console.log(buf.subarray(-6, -1).toString()); - * // Prints: buffe - * // (Equivalent to buf.subarray(0, 5).) - * - * console.log(buf.subarray(-6, -2).toString()); - * // Prints: buff - * // (Equivalent to buf.subarray(0, 4).) - * - * console.log(buf.subarray(-5, -2).toString()); - * // Prints: uff - * // (Equivalent to buf.subarray(1, 4).) - * ``` - * @since v3.0.0 - * @param [start=0] Where the new `Buffer` will start. - * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). - */ - subarray(start?: number, end?: number): Buffer; - /** - * Writes `value` to `buf` at the specified `offset` as big-endian. - * - * `value` is interpreted and written as a two's complement signed integer. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.allocUnsafe(8); - * - * buf.writeBigInt64BE(0x0102030405060708n, 0); - * - * console.log(buf); - * // Prints: - * ``` - * @since v12.0.0, v10.20.0 - * @param value Number to be written to `buf`. - * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. - * @return `offset` plus the number of bytes written. - */ - writeBigInt64BE(value: bigint, offset?: number): number; - /** - * Writes `value` to `buf` at the specified `offset` as little-endian. - * - * `value` is interpreted and written as a two's complement signed integer. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.allocUnsafe(8); - * - * buf.writeBigInt64LE(0x0102030405060708n, 0); - * - * console.log(buf); - * // Prints: - * ``` - * @since v12.0.0, v10.20.0 - * @param value Number to be written to `buf`. - * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. - * @return `offset` plus the number of bytes written. - */ - writeBigInt64LE(value: bigint, offset?: number): number; - /** - * Writes `value` to `buf` at the specified `offset` as big-endian. - * - * This function is also available under the `writeBigUint64BE` alias. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.allocUnsafe(8); - * - * buf.writeBigUInt64BE(0xdecafafecacefaden, 0); - * - * console.log(buf); - * // Prints: - * ``` - * @since v12.0.0, v10.20.0 - * @param value Number to be written to `buf`. - * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. - * @return `offset` plus the number of bytes written. - */ - writeBigUInt64BE(value: bigint, offset?: number): number; - /** - * @alias Buffer.writeBigUInt64BE - * @since v14.10.0, v12.19.0 - */ - writeBigUint64BE(value: bigint, offset?: number): number; - /** - * Writes `value` to `buf` at the specified `offset` as little-endian - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.allocUnsafe(8); - * - * buf.writeBigUInt64LE(0xdecafafecacefaden, 0); - * - * console.log(buf); - * // Prints: - * ``` - * - * This function is also available under the `writeBigUint64LE` alias. - * @since v12.0.0, v10.20.0 - * @param value Number to be written to `buf`. - * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. - * @return `offset` plus the number of bytes written. - */ - writeBigUInt64LE(value: bigint, offset?: number): number; - /** - * @alias Buffer.writeBigUInt64LE - * @since v14.10.0, v12.19.0 - */ - writeBigUint64LE(value: bigint, offset?: number): number; - /** - * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined - * when `value` is anything other than an unsigned integer. - * - * This function is also available under the `writeUintLE` alias. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.allocUnsafe(6); - * - * buf.writeUIntLE(0x1234567890ab, 0, 6); - * - * console.log(buf); - * // Prints: - * ``` - * @since v0.5.5 - * @param value Number to be written to `buf`. - * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. - * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. - * @return `offset` plus the number of bytes written. - */ - writeUIntLE(value: number, offset: number, byteLength: number): number; - /** - * @alias Buffer.writeUIntLE - * @since v14.9.0, v12.19.0 - */ - writeUintLE(value: number, offset: number, byteLength: number): number; - /** - * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined - * when `value` is anything other than an unsigned integer. - * - * This function is also available under the `writeUintBE` alias. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.allocUnsafe(6); - * - * buf.writeUIntBE(0x1234567890ab, 0, 6); - * - * console.log(buf); - * // Prints: - * ``` - * @since v0.5.5 - * @param value Number to be written to `buf`. - * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. - * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. - * @return `offset` plus the number of bytes written. - */ - writeUIntBE(value: number, offset: number, byteLength: number): number; - /** - * @alias Buffer.writeUIntBE - * @since v14.9.0, v12.19.0 - */ - writeUintBE(value: number, offset: number, byteLength: number): number; - /** - * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined - * when `value` is anything other than a signed integer. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.allocUnsafe(6); - * - * buf.writeIntLE(0x1234567890ab, 0, 6); - * - * console.log(buf); - * // Prints: - * ``` - * @since v0.11.15 - * @param value Number to be written to `buf`. - * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. - * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. - * @return `offset` plus the number of bytes written. - */ - writeIntLE(value: number, offset: number, byteLength: number): number; - /** - * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when`value` is anything other than a - * signed integer. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.allocUnsafe(6); - * - * buf.writeIntBE(0x1234567890ab, 0, 6); - * - * console.log(buf); - * // Prints: - * ``` - * @since v0.11.15 - * @param value Number to be written to `buf`. - * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. - * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. - * @return `offset` plus the number of bytes written. - */ - writeIntBE(value: number, offset: number, byteLength: number): number; - /** - * Reads an unsigned, big-endian 64-bit integer from `buf` at the specified`offset`. - * - * This function is also available under the `readBigUint64BE` alias. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); - * - * console.log(buf.readBigUInt64BE(0)); - * // Prints: 4294967295n - * ``` - * @since v12.0.0, v10.20.0 - * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. - */ - readBigUInt64BE(offset?: number): bigint; - /** - * @alias Buffer.readBigUInt64BE - * @since v14.10.0, v12.19.0 - */ - readBigUint64BE(offset?: number): bigint; - /** - * Reads an unsigned, little-endian 64-bit integer from `buf` at the specified`offset`. - * - * This function is also available under the `readBigUint64LE` alias. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); - * - * console.log(buf.readBigUInt64LE(0)); - * // Prints: 18446744069414584320n - * ``` - * @since v12.0.0, v10.20.0 - * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. - */ - readBigUInt64LE(offset?: number): bigint; - /** - * @alias Buffer.readBigUInt64LE - * @since v14.10.0, v12.19.0 - */ - readBigUint64LE(offset?: number): bigint; - /** - * Reads a signed, big-endian 64-bit integer from `buf` at the specified `offset`. - * - * Integers read from a `Buffer` are interpreted as two's complement signed - * values. - * @since v12.0.0, v10.20.0 - * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. - */ - readBigInt64BE(offset?: number): bigint; - /** - * Reads a signed, little-endian 64-bit integer from `buf` at the specified`offset`. - * - * Integers read from a `Buffer` are interpreted as two's complement signed - * values. - * @since v12.0.0, v10.20.0 - * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. - */ - readBigInt64LE(offset?: number): bigint; - /** - * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as an unsigned, little-endian integer supporting - * up to 48 bits of accuracy. - * - * This function is also available under the `readUintLE` alias. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); - * - * console.log(buf.readUIntLE(0, 6).toString(16)); - * // Prints: ab9078563412 - * ``` - * @since v0.11.15 - * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. - * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. - */ - readUIntLE(offset: number, byteLength: number): number; - /** - * @alias Buffer.readUIntLE - * @since v14.9.0, v12.19.0 - */ - readUintLE(offset: number, byteLength: number): number; - /** - * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as an unsigned big-endian integer supporting - * up to 48 bits of accuracy. - * - * This function is also available under the `readUintBE` alias. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); - * - * console.log(buf.readUIntBE(0, 6).toString(16)); - * // Prints: 1234567890ab - * console.log(buf.readUIntBE(1, 6).toString(16)); - * // Throws ERR_OUT_OF_RANGE. - * ``` - * @since v0.11.15 - * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. - * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. - */ - readUIntBE(offset: number, byteLength: number): number; - /** - * @alias Buffer.readUIntBE - * @since v14.9.0, v12.19.0 - */ - readUintBE(offset: number, byteLength: number): number; - /** - * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as a little-endian, two's complement signed value - * supporting up to 48 bits of accuracy. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); - * - * console.log(buf.readIntLE(0, 6).toString(16)); - * // Prints: -546f87a9cbee - * ``` - * @since v0.11.15 - * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. - * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. - */ - readIntLE(offset: number, byteLength: number): number; - /** - * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as a big-endian, two's complement signed value - * supporting up to 48 bits of accuracy. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); - * - * console.log(buf.readIntBE(0, 6).toString(16)); - * // Prints: 1234567890ab - * console.log(buf.readIntBE(1, 6).toString(16)); - * // Throws ERR_OUT_OF_RANGE. - * console.log(buf.readIntBE(1, 0).toString(16)); - * // Throws ERR_OUT_OF_RANGE. - * ``` - * @since v0.11.15 - * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. - * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. - */ - readIntBE(offset: number, byteLength: number): number; - /** - * Reads an unsigned 8-bit integer from `buf` at the specified `offset`. - * - * This function is also available under the `readUint8` alias. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.from([1, -2]); - * - * console.log(buf.readUInt8(0)); - * // Prints: 1 - * console.log(buf.readUInt8(1)); - * // Prints: 254 - * console.log(buf.readUInt8(2)); - * // Throws ERR_OUT_OF_RANGE. - * ``` - * @since v0.5.0 - * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. - */ - readUInt8(offset?: number): number; - /** - * @alias Buffer.readUInt8 - * @since v14.9.0, v12.19.0 - */ - readUint8(offset?: number): number; - /** - * Reads an unsigned, little-endian 16-bit integer from `buf` at the specified`offset`. - * - * This function is also available under the `readUint16LE` alias. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.from([0x12, 0x34, 0x56]); - * - * console.log(buf.readUInt16LE(0).toString(16)); - * // Prints: 3412 - * console.log(buf.readUInt16LE(1).toString(16)); - * // Prints: 5634 - * console.log(buf.readUInt16LE(2).toString(16)); - * // Throws ERR_OUT_OF_RANGE. - * ``` - * @since v0.5.5 - * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. - */ - readUInt16LE(offset?: number): number; - /** - * @alias Buffer.readUInt16LE - * @since v14.9.0, v12.19.0 - */ - readUint16LE(offset?: number): number; - /** - * Reads an unsigned, big-endian 16-bit integer from `buf` at the specified`offset`. - * - * This function is also available under the `readUint16BE` alias. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.from([0x12, 0x34, 0x56]); - * - * console.log(buf.readUInt16BE(0).toString(16)); - * // Prints: 1234 - * console.log(buf.readUInt16BE(1).toString(16)); - * // Prints: 3456 - * ``` - * @since v0.5.5 - * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. - */ - readUInt16BE(offset?: number): number; - /** - * @alias Buffer.readUInt16BE - * @since v14.9.0, v12.19.0 - */ - readUint16BE(offset?: number): number; - /** - * Reads an unsigned, little-endian 32-bit integer from `buf` at the specified`offset`. - * - * This function is also available under the `readUint32LE` alias. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); - * - * console.log(buf.readUInt32LE(0).toString(16)); - * // Prints: 78563412 - * console.log(buf.readUInt32LE(1).toString(16)); - * // Throws ERR_OUT_OF_RANGE. - * ``` - * @since v0.5.5 - * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. - */ - readUInt32LE(offset?: number): number; - /** - * @alias Buffer.readUInt32LE - * @since v14.9.0, v12.19.0 - */ - readUint32LE(offset?: number): number; - /** - * Reads an unsigned, big-endian 32-bit integer from `buf` at the specified`offset`. - * - * This function is also available under the `readUint32BE` alias. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); - * - * console.log(buf.readUInt32BE(0).toString(16)); - * // Prints: 12345678 - * ``` - * @since v0.5.5 - * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. - */ - readUInt32BE(offset?: number): number; - /** - * @alias Buffer.readUInt32BE - * @since v14.9.0, v12.19.0 - */ - readUint32BE(offset?: number): number; - /** - * Reads a signed 8-bit integer from `buf` at the specified `offset`. - * - * Integers read from a `Buffer` are interpreted as two's complement signed values. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.from([-1, 5]); - * - * console.log(buf.readInt8(0)); - * // Prints: -1 - * console.log(buf.readInt8(1)); - * // Prints: 5 - * console.log(buf.readInt8(2)); - * // Throws ERR_OUT_OF_RANGE. - * ``` - * @since v0.5.0 - * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. - */ - readInt8(offset?: number): number; - /** - * Reads a signed, little-endian 16-bit integer from `buf` at the specified`offset`. - * - * Integers read from a `Buffer` are interpreted as two's complement signed values. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.from([0, 5]); - * - * console.log(buf.readInt16LE(0)); - * // Prints: 1280 - * console.log(buf.readInt16LE(1)); - * // Throws ERR_OUT_OF_RANGE. - * ``` - * @since v0.5.5 - * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. - */ - readInt16LE(offset?: number): number; - /** - * Reads a signed, big-endian 16-bit integer from `buf` at the specified `offset`. - * - * Integers read from a `Buffer` are interpreted as two's complement signed values. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.from([0, 5]); - * - * console.log(buf.readInt16BE(0)); - * // Prints: 5 - * ``` - * @since v0.5.5 - * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. - */ - readInt16BE(offset?: number): number; - /** - * Reads a signed, little-endian 32-bit integer from `buf` at the specified`offset`. - * - * Integers read from a `Buffer` are interpreted as two's complement signed values. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.from([0, 0, 0, 5]); - * - * console.log(buf.readInt32LE(0)); - * // Prints: 83886080 - * console.log(buf.readInt32LE(1)); - * // Throws ERR_OUT_OF_RANGE. - * ``` - * @since v0.5.5 - * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. - */ - readInt32LE(offset?: number): number; - /** - * Reads a signed, big-endian 32-bit integer from `buf` at the specified `offset`. - * - * Integers read from a `Buffer` are interpreted as two's complement signed values. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.from([0, 0, 0, 5]); - * - * console.log(buf.readInt32BE(0)); - * // Prints: 5 - * ``` - * @since v0.5.5 - * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. - */ - readInt32BE(offset?: number): number; - /** - * Reads a 32-bit, little-endian float from `buf` at the specified `offset`. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.from([1, 2, 3, 4]); - * - * console.log(buf.readFloatLE(0)); - * // Prints: 1.539989614439558e-36 - * console.log(buf.readFloatLE(1)); - * // Throws ERR_OUT_OF_RANGE. - * ``` - * @since v0.11.15 - * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. - */ - readFloatLE(offset?: number): number; - /** - * Reads a 32-bit, big-endian float from `buf` at the specified `offset`. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.from([1, 2, 3, 4]); - * - * console.log(buf.readFloatBE(0)); - * // Prints: 2.387939260590663e-38 - * ``` - * @since v0.11.15 - * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. - */ - readFloatBE(offset?: number): number; - /** - * Reads a 64-bit, little-endian double from `buf` at the specified `offset`. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); - * - * console.log(buf.readDoubleLE(0)); - * // Prints: 5.447603722011605e-270 - * console.log(buf.readDoubleLE(1)); - * // Throws ERR_OUT_OF_RANGE. - * ``` - * @since v0.11.15 - * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. - */ - readDoubleLE(offset?: number): number; - /** - * Reads a 64-bit, big-endian double from `buf` at the specified `offset`. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); - * - * console.log(buf.readDoubleBE(0)); - * // Prints: 8.20788039913184e-304 - * ``` - * @since v0.11.15 - * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. - */ - readDoubleBE(offset?: number): number; - reverse(): this; - /** - * Interprets `buf` as an array of unsigned 16-bit integers and swaps the - * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 2. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); - * - * console.log(buf1); - * // Prints: - * - * buf1.swap16(); - * - * console.log(buf1); - * // Prints: - * - * const buf2 = Buffer.from([0x1, 0x2, 0x3]); - * - * buf2.swap16(); - * // Throws ERR_INVALID_BUFFER_SIZE. - * ``` - * - * One convenient use of `buf.swap16()` is to perform a fast in-place conversion - * between UTF-16 little-endian and UTF-16 big-endian: - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.from('This is little-endian UTF-16', 'utf16le'); - * buf.swap16(); // Convert to big-endian UTF-16 text. - * ``` - * @since v5.10.0 - * @return A reference to `buf`. - */ - swap16(): Buffer; - /** - * Interprets `buf` as an array of unsigned 32-bit integers and swaps the - * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 4. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); - * - * console.log(buf1); - * // Prints: - * - * buf1.swap32(); - * - * console.log(buf1); - * // Prints: - * - * const buf2 = Buffer.from([0x1, 0x2, 0x3]); - * - * buf2.swap32(); - * // Throws ERR_INVALID_BUFFER_SIZE. - * ``` - * @since v5.10.0 - * @return A reference to `buf`. - */ - swap32(): Buffer; - /** - * Interprets `buf` as an array of 64-bit numbers and swaps byte order _in-place_. - * Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 8. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); - * - * console.log(buf1); - * // Prints: - * - * buf1.swap64(); - * - * console.log(buf1); - * // Prints: - * - * const buf2 = Buffer.from([0x1, 0x2, 0x3]); - * - * buf2.swap64(); - * // Throws ERR_INVALID_BUFFER_SIZE. - * ``` - * @since v6.3.0 - * @return A reference to `buf`. - */ - swap64(): Buffer; - /** - * Writes `value` to `buf` at the specified `offset`. `value` must be a - * valid unsigned 8-bit integer. Behavior is undefined when `value` is anything - * other than an unsigned 8-bit integer. - * - * This function is also available under the `writeUint8` alias. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.allocUnsafe(4); - * - * buf.writeUInt8(0x3, 0); - * buf.writeUInt8(0x4, 1); - * buf.writeUInt8(0x23, 2); - * buf.writeUInt8(0x42, 3); - * - * console.log(buf); - * // Prints: - * ``` - * @since v0.5.0 - * @param value Number to be written to `buf`. - * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. - * @return `offset` plus the number of bytes written. - */ - writeUInt8(value: number, offset?: number): number; - /** - * @alias Buffer.writeUInt8 - * @since v14.9.0, v12.19.0 - */ - writeUint8(value: number, offset?: number): number; - /** - * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid unsigned 16-bit integer. Behavior is undefined when `value` is - * anything other than an unsigned 16-bit integer. - * - * This function is also available under the `writeUint16LE` alias. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.allocUnsafe(4); - * - * buf.writeUInt16LE(0xdead, 0); - * buf.writeUInt16LE(0xbeef, 2); - * - * console.log(buf); - * // Prints: - * ``` - * @since v0.5.5 - * @param value Number to be written to `buf`. - * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. - * @return `offset` plus the number of bytes written. - */ - writeUInt16LE(value: number, offset?: number): number; - /** - * @alias Buffer.writeUInt16LE - * @since v14.9.0, v12.19.0 - */ - writeUint16LE(value: number, offset?: number): number; - /** - * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid unsigned 16-bit integer. Behavior is undefined when `value`is anything other than an - * unsigned 16-bit integer. - * - * This function is also available under the `writeUint16BE` alias. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.allocUnsafe(4); - * - * buf.writeUInt16BE(0xdead, 0); - * buf.writeUInt16BE(0xbeef, 2); - * - * console.log(buf); - * // Prints: - * ``` - * @since v0.5.5 - * @param value Number to be written to `buf`. - * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. - * @return `offset` plus the number of bytes written. - */ - writeUInt16BE(value: number, offset?: number): number; - /** - * @alias Buffer.writeUInt16BE - * @since v14.9.0, v12.19.0 - */ - writeUint16BE(value: number, offset?: number): number; - /** - * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid unsigned 32-bit integer. Behavior is undefined when `value` is - * anything other than an unsigned 32-bit integer. - * - * This function is also available under the `writeUint32LE` alias. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.allocUnsafe(4); - * - * buf.writeUInt32LE(0xfeedface, 0); - * - * console.log(buf); - * // Prints: - * ``` - * @since v0.5.5 - * @param value Number to be written to `buf`. - * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. - * @return `offset` plus the number of bytes written. - */ - writeUInt32LE(value: number, offset?: number): number; - /** - * @alias Buffer.writeUInt32LE - * @since v14.9.0, v12.19.0 - */ - writeUint32LE(value: number, offset?: number): number; - /** - * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid unsigned 32-bit integer. Behavior is undefined when `value`is anything other than an - * unsigned 32-bit integer. - * - * This function is also available under the `writeUint32BE` alias. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.allocUnsafe(4); - * - * buf.writeUInt32BE(0xfeedface, 0); - * - * console.log(buf); - * // Prints: - * ``` - * @since v0.5.5 - * @param value Number to be written to `buf`. - * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. - * @return `offset` plus the number of bytes written. - */ - writeUInt32BE(value: number, offset?: number): number; - /** - * @alias Buffer.writeUInt32BE - * @since v14.9.0, v12.19.0 - */ - writeUint32BE(value: number, offset?: number): number; - /** - * Writes `value` to `buf` at the specified `offset`. `value` must be a valid - * signed 8-bit integer. Behavior is undefined when `value` is anything other than - * a signed 8-bit integer. - * - * `value` is interpreted and written as a two's complement signed integer. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.allocUnsafe(2); - * - * buf.writeInt8(2, 0); - * buf.writeInt8(-2, 1); - * - * console.log(buf); - * // Prints: - * ``` - * @since v0.5.0 - * @param value Number to be written to `buf`. - * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. - * @return `offset` plus the number of bytes written. - */ - writeInt8(value: number, offset?: number): number; - /** - * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid signed 16-bit integer. Behavior is undefined when `value` is - * anything other than a signed 16-bit integer. - * - * The `value` is interpreted and written as a two's complement signed integer. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.allocUnsafe(2); - * - * buf.writeInt16LE(0x0304, 0); - * - * console.log(buf); - * // Prints: - * ``` - * @since v0.5.5 - * @param value Number to be written to `buf`. - * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. - * @return `offset` plus the number of bytes written. - */ - writeInt16LE(value: number, offset?: number): number; - /** - * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid signed 16-bit integer. Behavior is undefined when `value` is - * anything other than a signed 16-bit integer. - * - * The `value` is interpreted and written as a two's complement signed integer. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.allocUnsafe(2); - * - * buf.writeInt16BE(0x0102, 0); - * - * console.log(buf); - * // Prints: - * ``` - * @since v0.5.5 - * @param value Number to be written to `buf`. - * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. - * @return `offset` plus the number of bytes written. - */ - writeInt16BE(value: number, offset?: number): number; - /** - * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid signed 32-bit integer. Behavior is undefined when `value` is - * anything other than a signed 32-bit integer. - * - * The `value` is interpreted and written as a two's complement signed integer. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.allocUnsafe(4); - * - * buf.writeInt32LE(0x05060708, 0); - * - * console.log(buf); - * // Prints: - * ``` - * @since v0.5.5 - * @param value Number to be written to `buf`. - * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. - * @return `offset` plus the number of bytes written. - */ - writeInt32LE(value: number, offset?: number): number; - /** - * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid signed 32-bit integer. Behavior is undefined when `value` is - * anything other than a signed 32-bit integer. - * - * The `value` is interpreted and written as a two's complement signed integer. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.allocUnsafe(4); - * - * buf.writeInt32BE(0x01020304, 0); - * - * console.log(buf); - * // Prints: - * ``` - * @since v0.5.5 - * @param value Number to be written to `buf`. - * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. - * @return `offset` plus the number of bytes written. - */ - writeInt32BE(value: number, offset?: number): number; - /** - * Writes `value` to `buf` at the specified `offset` as little-endian. Behavior is - * undefined when `value` is anything other than a JavaScript number. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.allocUnsafe(4); - * - * buf.writeFloatLE(0xcafebabe, 0); - * - * console.log(buf); - * // Prints: - * ``` - * @since v0.11.15 - * @param value Number to be written to `buf`. - * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. - * @return `offset` plus the number of bytes written. - */ - writeFloatLE(value: number, offset?: number): number; - /** - * Writes `value` to `buf` at the specified `offset` as big-endian. Behavior is - * undefined when `value` is anything other than a JavaScript number. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.allocUnsafe(4); - * - * buf.writeFloatBE(0xcafebabe, 0); - * - * console.log(buf); - * // Prints: - * ``` - * @since v0.11.15 - * @param value Number to be written to `buf`. - * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. - * @return `offset` plus the number of bytes written. - */ - writeFloatBE(value: number, offset?: number): number; - /** - * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a JavaScript number. Behavior is undefined when `value` is anything - * other than a JavaScript number. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.allocUnsafe(8); - * - * buf.writeDoubleLE(123.456, 0); - * - * console.log(buf); - * // Prints: - * ``` - * @since v0.11.15 - * @param value Number to be written to `buf`. - * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. - * @return `offset` plus the number of bytes written. - */ - writeDoubleLE(value: number, offset?: number): number; - /** - * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a JavaScript number. Behavior is undefined when `value` is anything - * other than a JavaScript number. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.allocUnsafe(8); - * - * buf.writeDoubleBE(123.456, 0); - * - * console.log(buf); - * // Prints: - * ``` - * @since v0.11.15 - * @param value Number to be written to `buf`. - * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. - * @return `offset` plus the number of bytes written. - */ - writeDoubleBE(value: number, offset?: number): number; - /** - * Fills `buf` with the specified `value`. If the `offset` and `end` are not given, - * the entire `buf` will be filled: - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * // Fill a `Buffer` with the ASCII character 'h'. - * - * const b = Buffer.allocUnsafe(50).fill('h'); - * - * console.log(b.toString()); - * // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh - * - * // Fill a buffer with empty string - * const c = Buffer.allocUnsafe(5).fill(''); - * - * console.log(c.fill('')); - * // Prints: - * ``` - * - * `value` is coerced to a `uint32` value if it is not a string, `Buffer`, or - * integer. If the resulting integer is greater than `255` (decimal), `buf` will be - * filled with `value & 255`. - * - * If the final write of a `fill()` operation falls on a multi-byte character, - * then only the bytes of that character that fit into `buf` are written: - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * // Fill a `Buffer` with character that takes up two bytes in UTF-8. - * - * console.log(Buffer.allocUnsafe(5).fill('\u0222')); - * // Prints: - * ``` - * - * If `value` contains invalid characters, it is truncated; if no valid - * fill data remains, an exception is thrown: - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.allocUnsafe(5); - * - * console.log(buf.fill('a')); - * // Prints: - * console.log(buf.fill('aazz', 'hex')); - * // Prints: - * console.log(buf.fill('zz', 'hex')); - * // Throws an exception. - * ``` - * @since v0.5.0 - * @param value The value with which to fill `buf`. Empty value (string, Uint8Array, Buffer) is coerced to `0`. - * @param [offset=0] Number of bytes to skip before starting to fill `buf`. - * @param [end=buf.length] Where to stop filling `buf` (not inclusive). - * @param [encoding='utf8'] The encoding for `value` if `value` is a string. - * @return A reference to `buf`. - */ - fill(value: string | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): this; - /** - * If `value` is: - * - * * a string, `value` is interpreted according to the character encoding in`encoding`. - * * a `Buffer` or [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array), `value` will be used in its entirety. - * To compare a partial `Buffer`, use `buf.subarray`. - * * a number, `value` will be interpreted as an unsigned 8-bit integer - * value between `0` and `255`. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.from('this is a buffer'); - * - * console.log(buf.indexOf('this')); - * // Prints: 0 - * console.log(buf.indexOf('is')); - * // Prints: 2 - * console.log(buf.indexOf(Buffer.from('a buffer'))); - * // Prints: 8 - * console.log(buf.indexOf(97)); - * // Prints: 8 (97 is the decimal ASCII value for 'a') - * console.log(buf.indexOf(Buffer.from('a buffer example'))); - * // Prints: -1 - * console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8))); - * // Prints: 8 - * - * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); - * - * console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le')); - * // Prints: 4 - * console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le')); - * // Prints: 6 - * ``` - * - * If `value` is not a string, number, or `Buffer`, this method will throw a`TypeError`. If `value` is a number, it will be coerced to a valid byte value, - * an integer between 0 and 255. - * - * If `byteOffset` is not a number, it will be coerced to a number. If the result - * of coercion is `NaN` or `0`, then the entire buffer will be searched. This - * behavior matches [`String.prototype.indexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf). - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const b = Buffer.from('abcdef'); - * - * // Passing a value that's a number, but not a valid byte. - * // Prints: 2, equivalent to searching for 99 or 'c'. - * console.log(b.indexOf(99.9)); - * console.log(b.indexOf(256 + 99)); - * - * // Passing a byteOffset that coerces to NaN or 0. - * // Prints: 1, searching the whole buffer. - * console.log(b.indexOf('b', undefined)); - * console.log(b.indexOf('b', {})); - * console.log(b.indexOf('b', null)); - * console.log(b.indexOf('b', [])); - * ``` - * - * If `value` is an empty string or empty `Buffer` and `byteOffset` is less - * than `buf.length`, `byteOffset` will be returned. If `value` is empty and`byteOffset` is at least `buf.length`, `buf.length` will be returned. - * @since v1.5.0 - * @param value What to search for. - * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. - * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. - * @return The index of the first occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. - */ - indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; - /** - * Identical to `buf.indexOf()`, except the last occurrence of `value` is found - * rather than the first occurrence. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.from('this buffer is a buffer'); - * - * console.log(buf.lastIndexOf('this')); - * // Prints: 0 - * console.log(buf.lastIndexOf('buffer')); - * // Prints: 17 - * console.log(buf.lastIndexOf(Buffer.from('buffer'))); - * // Prints: 17 - * console.log(buf.lastIndexOf(97)); - * // Prints: 15 (97 is the decimal ASCII value for 'a') - * console.log(buf.lastIndexOf(Buffer.from('yolo'))); - * // Prints: -1 - * console.log(buf.lastIndexOf('buffer', 5)); - * // Prints: 5 - * console.log(buf.lastIndexOf('buffer', 4)); - * // Prints: -1 - * - * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); - * - * console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le')); - * // Prints: 6 - * console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le')); - * // Prints: 4 - * ``` - * - * If `value` is not a string, number, or `Buffer`, this method will throw a`TypeError`. If `value` is a number, it will be coerced to a valid byte value, - * an integer between 0 and 255. - * - * If `byteOffset` is not a number, it will be coerced to a number. Any arguments - * that coerce to `NaN`, like `{}` or `undefined`, will search the whole buffer. - * This behavior matches [`String.prototype.lastIndexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf). - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const b = Buffer.from('abcdef'); - * - * // Passing a value that's a number, but not a valid byte. - * // Prints: 2, equivalent to searching for 99 or 'c'. - * console.log(b.lastIndexOf(99.9)); - * console.log(b.lastIndexOf(256 + 99)); - * - * // Passing a byteOffset that coerces to NaN. - * // Prints: 1, searching the whole buffer. - * console.log(b.lastIndexOf('b', undefined)); - * console.log(b.lastIndexOf('b', {})); - * - * // Passing a byteOffset that coerces to 0. - * // Prints: -1, equivalent to passing 0. - * console.log(b.lastIndexOf('b', null)); - * console.log(b.lastIndexOf('b', [])); - * ``` - * - * If `value` is an empty string or empty `Buffer`, `byteOffset` will be returned. - * @since v6.0.0 - * @param value What to search for. - * @param [byteOffset=buf.length - 1] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. - * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. - * @return The index of the last occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. - */ - lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; - /** - * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of `[index, byte]` pairs from the contents - * of `buf`. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * // Log the entire contents of a `Buffer`. - * - * const buf = Buffer.from('buffer'); - * - * for (const pair of buf.entries()) { - * console.log(pair); - * } - * // Prints: - * // [0, 98] - * // [1, 117] - * // [2, 102] - * // [3, 102] - * // [4, 101] - * // [5, 114] - * ``` - * @since v1.1.0 - */ - entries(): IterableIterator<[number, number]>; - /** - * Equivalent to `buf.indexOf() !== -1`. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.from('this is a buffer'); - * - * console.log(buf.includes('this')); - * // Prints: true - * console.log(buf.includes('is')); - * // Prints: true - * console.log(buf.includes(Buffer.from('a buffer'))); - * // Prints: true - * console.log(buf.includes(97)); - * // Prints: true (97 is the decimal ASCII value for 'a') - * console.log(buf.includes(Buffer.from('a buffer example'))); - * // Prints: false - * console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8))); - * // Prints: true - * console.log(buf.includes('this', 4)); - * // Prints: false - * ``` - * @since v5.3.0 - * @param value What to search for. - * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. - * @param [encoding='utf8'] If `value` is a string, this is its encoding. - * @return `true` if `value` was found in `buf`, `false` otherwise. - */ - includes(value: string | number | Buffer, byteOffset?: number, encoding?: BufferEncoding): boolean; - /** - * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of `buf` keys (indices). - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.from('buffer'); - * - * for (const key of buf.keys()) { - * console.log(key); - * } - * // Prints: - * // 0 - * // 1 - * // 2 - * // 3 - * // 4 - * // 5 - * ``` - * @since v1.1.0 - */ - keys(): IterableIterator; - /** - * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) for `buf` values (bytes). This function is - * called automatically when a `Buffer` is used in a `for..of` statement. - * - * ```js - * import { Buffer } from 'node:buffer'; - * - * const buf = Buffer.from('buffer'); - * - * for (const value of buf.values()) { - * console.log(value); - * } - * // Prints: - * // 98 - * // 117 - * // 102 - * // 102 - * // 101 - * // 114 - * - * for (const value of buf) { - * console.log(value); - * } - * // Prints: - * // 98 - * // 117 - * // 102 - * // 102 - * // 101 - * // 114 - * ``` - * @since v1.1.0 - */ - values(): IterableIterator; - } - var Buffer: BufferConstructor; - /** - * Decodes a string of Base64-encoded data into bytes, and encodes those bytes - * into a string using Latin-1 (ISO-8859-1). - * - * The `data` may be any JavaScript-value that can be coerced into a string. - * - * **This function is only provided for compatibility with legacy web platform APIs** - * **and should never be used in new code, because they use strings to represent** - * **binary data and predate the introduction of typed arrays in JavaScript.** - * **For code running using Node.js APIs, converting between base64-encoded strings** - * **and binary data should be performed using `Buffer.from(str, 'base64')` and`buf.toString('base64')`.** - * @since v15.13.0, v14.17.0 - * @legacy Use `Buffer.from(data, 'base64')` instead. - * @param data The Base64-encoded input string. - */ - function atob(data: string): string; - /** - * Decodes a string into bytes using Latin-1 (ISO-8859), and encodes those bytes - * into a string using Base64. - * - * The `data` may be any JavaScript-value that can be coerced into a string. - * - * **This function is only provided for compatibility with legacy web platform APIs** - * **and should never be used in new code, because they use strings to represent** - * **binary data and predate the introduction of typed arrays in JavaScript.** - * **For code running using Node.js APIs, converting between base64-encoded strings** - * **and binary data should be performed using `Buffer.from(str, 'base64')` and`buf.toString('base64')`.** - * @since v15.13.0, v14.17.0 - * @legacy Use `buf.toString('base64')` instead. - * @param data An ASCII (Latin1) string. - */ - function btoa(data: string): string; - interface Blob extends __Blob {} - /** - * `Blob` class is a global reference for `require('node:buffer').Blob` - * https://nodejs.org/api/buffer.html#class-blob - * @since v18.0.0 - */ - var Blob: typeof globalThis extends { - onmessage: any; - Blob: infer T; - } ? T - : typeof NodeBlob; - } -} -declare module "node:buffer" { - export * from "buffer"; -} diff --git a/node_modules/@types/node/ts4.8/child_process.d.ts b/node_modules/@types/node/ts4.8/child_process.d.ts deleted file mode 100644 index a97532b474dd66ee96bf1c13335136727f4c0398..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/child_process.d.ts +++ /dev/null @@ -1,1540 +0,0 @@ -/** - * The `node:child_process` module provides the ability to spawn subprocesses in - * a manner that is similar, but not identical, to [`popen(3)`](http://man7.org/linux/man-pages/man3/popen.3.html). This capability - * is primarily provided by the {@link spawn} function: - * - * ```js - * const { spawn } = require('node:child_process'); - * const ls = spawn('ls', ['-lh', '/usr']); - * - * ls.stdout.on('data', (data) => { - * console.log(`stdout: ${data}`); - * }); - * - * ls.stderr.on('data', (data) => { - * console.error(`stderr: ${data}`); - * }); - * - * ls.on('close', (code) => { - * console.log(`child process exited with code ${code}`); - * }); - * ``` - * - * By default, pipes for `stdin`, `stdout`, and `stderr` are established between - * the parent Node.js process and the spawned subprocess. These pipes have - * limited (and platform-specific) capacity. If the subprocess writes to - * stdout in excess of that limit without the output being captured, the - * subprocess blocks waiting for the pipe buffer to accept more data. This is - * identical to the behavior of pipes in the shell. Use the `{ stdio: 'ignore' }`option if the output will not be consumed. - * - * The command lookup is performed using the `options.env.PATH` environment - * variable if `env` is in the `options` object. Otherwise, `process.env.PATH` is - * used. If `options.env` is set without `PATH`, lookup on Unix is performed - * on a default search path search of `/usr/bin:/bin` (see your operating system's - * manual for execvpe/execvp), on Windows the current processes environment - * variable `PATH` is used. - * - * On Windows, environment variables are case-insensitive. Node.js - * lexicographically sorts the `env` keys and uses the first one that - * case-insensitively matches. Only first (in lexicographic order) entry will be - * passed to the subprocess. This might lead to issues on Windows when passing - * objects to the `env` option that have multiple variants of the same key, such as`PATH` and `Path`. - * - * The {@link spawn} method spawns the child process asynchronously, - * without blocking the Node.js event loop. The {@link spawnSync} function provides equivalent functionality in a synchronous manner that blocks - * the event loop until the spawned process either exits or is terminated. - * - * For convenience, the `node:child_process` module provides a handful of - * synchronous and asynchronous alternatives to {@link spawn} and {@link spawnSync}. Each of these alternatives are implemented on - * top of {@link spawn} or {@link spawnSync}. - * - * * {@link exec}: spawns a shell and runs a command within that - * shell, passing the `stdout` and `stderr` to a callback function when - * complete. - * * {@link execFile}: similar to {@link exec} except - * that it spawns the command directly without first spawning a shell by - * default. - * * {@link fork}: spawns a new Node.js process and invokes a - * specified module with an IPC communication channel established that allows - * sending messages between parent and child. - * * {@link execSync}: a synchronous version of {@link exec} that will block the Node.js event loop. - * * {@link execFileSync}: a synchronous version of {@link execFile} that will block the Node.js event loop. - * - * For certain use cases, such as automating shell scripts, the `synchronous counterparts` may be more convenient. In many cases, however, - * the synchronous methods can have significant impact on performance due to - * stalling the event loop while spawned processes complete. - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/child_process.js) - */ -declare module "child_process" { - import { ObjectEncodingOptions } from "node:fs"; - import { Abortable, EventEmitter } from "node:events"; - import * as net from "node:net"; - import { Pipe, Readable, Stream, Writable } from "node:stream"; - import { URL } from "node:url"; - type Serializable = string | object | number | boolean | bigint; - type SendHandle = net.Socket | net.Server; - /** - * Instances of the `ChildProcess` represent spawned child processes. - * - * Instances of `ChildProcess` are not intended to be created directly. Rather, - * use the {@link spawn}, {@link exec},{@link execFile}, or {@link fork} methods to create - * instances of `ChildProcess`. - * @since v2.2.0 - */ - class ChildProcess extends EventEmitter { - /** - * A `Writable Stream` that represents the child process's `stdin`. - * - * If a child process waits to read all of its input, the child will not continue - * until this stream has been closed via `end()`. - * - * If the child was spawned with `stdio[0]` set to anything other than `'pipe'`, - * then this will be `null`. - * - * `subprocess.stdin` is an alias for `subprocess.stdio[0]`. Both properties will - * refer to the same value. - * - * The `subprocess.stdin` property can be `null` or `undefined`if the child process could not be successfully spawned. - * @since v0.1.90 - */ - stdin: Writable | null; - /** - * A `Readable Stream` that represents the child process's `stdout`. - * - * If the child was spawned with `stdio[1]` set to anything other than `'pipe'`, - * then this will be `null`. - * - * `subprocess.stdout` is an alias for `subprocess.stdio[1]`. Both properties will - * refer to the same value. - * - * ```js - * const { spawn } = require('node:child_process'); - * - * const subprocess = spawn('ls'); - * - * subprocess.stdout.on('data', (data) => { - * console.log(`Received chunk ${data}`); - * }); - * ``` - * - * The `subprocess.stdout` property can be `null` or `undefined`if the child process could not be successfully spawned. - * @since v0.1.90 - */ - stdout: Readable | null; - /** - * A `Readable Stream` that represents the child process's `stderr`. - * - * If the child was spawned with `stdio[2]` set to anything other than `'pipe'`, - * then this will be `null`. - * - * `subprocess.stderr` is an alias for `subprocess.stdio[2]`. Both properties will - * refer to the same value. - * - * The `subprocess.stderr` property can be `null` or `undefined`if the child process could not be successfully spawned. - * @since v0.1.90 - */ - stderr: Readable | null; - /** - * The `subprocess.channel` property is a reference to the child's IPC channel. If - * no IPC channel exists, this property is `undefined`. - * @since v7.1.0 - */ - readonly channel?: Pipe | null | undefined; - /** - * A sparse array of pipes to the child process, corresponding with positions in - * the `stdio` option passed to {@link spawn} that have been set - * to the value `'pipe'`. `subprocess.stdio[0]`, `subprocess.stdio[1]`, and`subprocess.stdio[2]` are also available as `subprocess.stdin`,`subprocess.stdout`, and `subprocess.stderr`, - * respectively. - * - * In the following example, only the child's fd `1` (stdout) is configured as a - * pipe, so only the parent's `subprocess.stdio[1]` is a stream, all other values - * in the array are `null`. - * - * ```js - * const assert = require('node:assert'); - * const fs = require('node:fs'); - * const child_process = require('node:child_process'); - * - * const subprocess = child_process.spawn('ls', { - * stdio: [ - * 0, // Use parent's stdin for child. - * 'pipe', // Pipe child's stdout to parent. - * fs.openSync('err.out', 'w'), // Direct child's stderr to a file. - * ], - * }); - * - * assert.strictEqual(subprocess.stdio[0], null); - * assert.strictEqual(subprocess.stdio[0], subprocess.stdin); - * - * assert(subprocess.stdout); - * assert.strictEqual(subprocess.stdio[1], subprocess.stdout); - * - * assert.strictEqual(subprocess.stdio[2], null); - * assert.strictEqual(subprocess.stdio[2], subprocess.stderr); - * ``` - * - * The `subprocess.stdio` property can be `undefined` if the child process could - * not be successfully spawned. - * @since v0.7.10 - */ - readonly stdio: [ - Writable | null, - // stdin - Readable | null, - // stdout - Readable | null, - // stderr - Readable | Writable | null | undefined, - // extra - Readable | Writable | null | undefined, // extra - ]; - /** - * The `subprocess.killed` property indicates whether the child process - * successfully received a signal from `subprocess.kill()`. The `killed` property - * does not indicate that the child process has been terminated. - * @since v0.5.10 - */ - readonly killed: boolean; - /** - * Returns the process identifier (PID) of the child process. If the child process - * fails to spawn due to errors, then the value is `undefined` and `error` is - * emitted. - * - * ```js - * const { spawn } = require('node:child_process'); - * const grep = spawn('grep', ['ssh']); - * - * console.log(`Spawned child pid: ${grep.pid}`); - * grep.stdin.end(); - * ``` - * @since v0.1.90 - */ - readonly pid?: number | undefined; - /** - * The `subprocess.connected` property indicates whether it is still possible to - * send and receive messages from a child process. When `subprocess.connected` is`false`, it is no longer possible to send or receive messages. - * @since v0.7.2 - */ - readonly connected: boolean; - /** - * The `subprocess.exitCode` property indicates the exit code of the child process. - * If the child process is still running, the field will be `null`. - */ - readonly exitCode: number | null; - /** - * The `subprocess.signalCode` property indicates the signal received by - * the child process if any, else `null`. - */ - readonly signalCode: NodeJS.Signals | null; - /** - * The `subprocess.spawnargs` property represents the full list of command-line - * arguments the child process was launched with. - */ - readonly spawnargs: string[]; - /** - * The `subprocess.spawnfile` property indicates the executable file name of - * the child process that is launched. - * - * For {@link fork}, its value will be equal to `process.execPath`. - * For {@link spawn}, its value will be the name of - * the executable file. - * For {@link exec}, its value will be the name of the shell - * in which the child process is launched. - */ - readonly spawnfile: string; - /** - * The `subprocess.kill()` method sends a signal to the child process. If no - * argument is given, the process will be sent the `'SIGTERM'` signal. See [`signal(7)`](http://man7.org/linux/man-pages/man7/signal.7.html) for a list of available signals. This function - * returns `true` if [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) succeeds, and `false` otherwise. - * - * ```js - * const { spawn } = require('node:child_process'); - * const grep = spawn('grep', ['ssh']); - * - * grep.on('close', (code, signal) => { - * console.log( - * `child process terminated due to receipt of signal ${signal}`); - * }); - * - * // Send SIGHUP to process. - * grep.kill('SIGHUP'); - * ``` - * - * The `ChildProcess` object may emit an `'error'` event if the signal - * cannot be delivered. Sending a signal to a child process that has already exited - * is not an error but may have unforeseen consequences. Specifically, if the - * process identifier (PID) has been reassigned to another process, the signal will - * be delivered to that process instead which can have unexpected results. - * - * While the function is called `kill`, the signal delivered to the child process - * may not actually terminate the process. - * - * See [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for reference. - * - * On Windows, where POSIX signals do not exist, the `signal` argument will be - * ignored, and the process will be killed forcefully and abruptly (similar to`'SIGKILL'`). - * See `Signal Events` for more details. - * - * On Linux, child processes of child processes will not be terminated - * when attempting to kill their parent. This is likely to happen when running a - * new process in a shell or with the use of the `shell` option of `ChildProcess`: - * - * ```js - * 'use strict'; - * const { spawn } = require('node:child_process'); - * - * const subprocess = spawn( - * 'sh', - * [ - * '-c', - * `node -e "setInterval(() => { - * console.log(process.pid, 'is alive') - * }, 500);"`, - * ], { - * stdio: ['inherit', 'inherit', 'inherit'], - * }, - * ); - * - * setTimeout(() => { - * subprocess.kill(); // Does not terminate the Node.js process in the shell. - * }, 2000); - * ``` - * @since v0.1.90 - */ - kill(signal?: NodeJS.Signals | number): boolean; - /** - * Calls {@link ChildProcess.kill} with `'SIGTERM'`. - * @since v20.5.0 - */ - [Symbol.dispose](): void; - /** - * When an IPC channel has been established between the parent and child ( - * i.e. when using {@link fork}), the `subprocess.send()` method can - * be used to send messages to the child process. When the child process is a - * Node.js instance, these messages can be received via the `'message'` event. - * - * The message goes through serialization and parsing. The resulting - * message might not be the same as what is originally sent. - * - * For example, in the parent script: - * - * ```js - * const cp = require('node:child_process'); - * const n = cp.fork(`${__dirname}/sub.js`); - * - * n.on('message', (m) => { - * console.log('PARENT got message:', m); - * }); - * - * // Causes the child to print: CHILD got message: { hello: 'world' } - * n.send({ hello: 'world' }); - * ``` - * - * And then the child script, `'sub.js'` might look like this: - * - * ```js - * process.on('message', (m) => { - * console.log('CHILD got message:', m); - * }); - * - * // Causes the parent to print: PARENT got message: { foo: 'bar', baz: null } - * process.send({ foo: 'bar', baz: NaN }); - * ``` - * - * Child Node.js processes will have a `process.send()` method of their own - * that allows the child to send messages back to the parent. - * - * There is a special case when sending a `{cmd: 'NODE_foo'}` message. Messages - * containing a `NODE_` prefix in the `cmd` property are reserved for use within - * Node.js core and will not be emitted in the child's `'message'` event. Rather, such messages are emitted using the`'internalMessage'` event and are consumed internally by Node.js. - * Applications should avoid using such messages or listening for`'internalMessage'` events as it is subject to change without notice. - * - * The optional `sendHandle` argument that may be passed to `subprocess.send()` is - * for passing a TCP server or socket object to the child process. The child will - * receive the object as the second argument passed to the callback function - * registered on the `'message'` event. Any data that is received - * and buffered in the socket will not be sent to the child. - * - * The optional `callback` is a function that is invoked after the message is - * sent but before the child may have received it. The function is called with a - * single argument: `null` on success, or an `Error` object on failure. - * - * If no `callback` function is provided and the message cannot be sent, an`'error'` event will be emitted by the `ChildProcess` object. This can - * happen, for instance, when the child process has already exited. - * - * `subprocess.send()` will return `false` if the channel has closed or when the - * backlog of unsent messages exceeds a threshold that makes it unwise to send - * more. Otherwise, the method returns `true`. The `callback` function can be - * used to implement flow control. - * - * #### Example: sending a server object - * - * The `sendHandle` argument can be used, for instance, to pass the handle of - * a TCP server object to the child process as illustrated in the example below: - * - * ```js - * const subprocess = require('node:child_process').fork('subprocess.js'); - * - * // Open up the server object and send the handle. - * const server = require('node:net').createServer(); - * server.on('connection', (socket) => { - * socket.end('handled by parent'); - * }); - * server.listen(1337, () => { - * subprocess.send('server', server); - * }); - * ``` - * - * The child would then receive the server object as: - * - * ```js - * process.on('message', (m, server) => { - * if (m === 'server') { - * server.on('connection', (socket) => { - * socket.end('handled by child'); - * }); - * } - * }); - * ``` - * - * Once the server is now shared between the parent and child, some connections - * can be handled by the parent and some by the child. - * - * While the example above uses a server created using the `node:net` module,`node:dgram` module servers use exactly the same workflow with the exceptions of - * listening on a `'message'` event instead of `'connection'` and using`server.bind()` instead of `server.listen()`. This is, however, only - * supported on Unix platforms. - * - * #### Example: sending a socket object - * - * Similarly, the `sendHandler` argument can be used to pass the handle of a - * socket to the child process. The example below spawns two children that each - * handle connections with "normal" or "special" priority: - * - * ```js - * const { fork } = require('node:child_process'); - * const normal = fork('subprocess.js', ['normal']); - * const special = fork('subprocess.js', ['special']); - * - * // Open up the server and send sockets to child. Use pauseOnConnect to prevent - * // the sockets from being read before they are sent to the child process. - * const server = require('node:net').createServer({ pauseOnConnect: true }); - * server.on('connection', (socket) => { - * - * // If this is special priority... - * if (socket.remoteAddress === '74.125.127.100') { - * special.send('socket', socket); - * return; - * } - * // This is normal priority. - * normal.send('socket', socket); - * }); - * server.listen(1337); - * ``` - * - * The `subprocess.js` would receive the socket handle as the second argument - * passed to the event callback function: - * - * ```js - * process.on('message', (m, socket) => { - * if (m === 'socket') { - * if (socket) { - * // Check that the client socket exists. - * // It is possible for the socket to be closed between the time it is - * // sent and the time it is received in the child process. - * socket.end(`Request handled with ${process.argv[2]} priority`); - * } - * } - * }); - * ``` - * - * Do not use `.maxConnections` on a socket that has been passed to a subprocess. - * The parent cannot track when the socket is destroyed. - * - * Any `'message'` handlers in the subprocess should verify that `socket` exists, - * as the connection may have been closed during the time it takes to send the - * connection to the child. - * @since v0.5.9 - * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties: - */ - send(message: Serializable, callback?: (error: Error | null) => void): boolean; - send(message: Serializable, sendHandle?: SendHandle, callback?: (error: Error | null) => void): boolean; - send( - message: Serializable, - sendHandle?: SendHandle, - options?: MessageOptions, - callback?: (error: Error | null) => void, - ): boolean; - /** - * Closes the IPC channel between parent and child, allowing the child to exit - * gracefully once there are no other connections keeping it alive. After calling - * this method the `subprocess.connected` and `process.connected` properties in - * both the parent and child (respectively) will be set to `false`, and it will be - * no longer possible to pass messages between the processes. - * - * The `'disconnect'` event will be emitted when there are no messages in the - * process of being received. This will most often be triggered immediately after - * calling `subprocess.disconnect()`. - * - * When the child process is a Node.js instance (e.g. spawned using {@link fork}), the `process.disconnect()` method can be invoked - * within the child process to close the IPC channel as well. - * @since v0.7.2 - */ - disconnect(): void; - /** - * By default, the parent will wait for the detached child to exit. To prevent the - * parent from waiting for a given `subprocess` to exit, use the`subprocess.unref()` method. Doing so will cause the parent's event loop to not - * include the child in its reference count, allowing the parent to exit - * independently of the child, unless there is an established IPC channel between - * the child and the parent. - * - * ```js - * const { spawn } = require('node:child_process'); - * - * const subprocess = spawn(process.argv[0], ['child_program.js'], { - * detached: true, - * stdio: 'ignore', - * }); - * - * subprocess.unref(); - * ``` - * @since v0.7.10 - */ - unref(): void; - /** - * Calling `subprocess.ref()` after making a call to `subprocess.unref()` will - * restore the removed reference count for the child process, forcing the parent - * to wait for the child to exit before exiting itself. - * - * ```js - * const { spawn } = require('node:child_process'); - * - * const subprocess = spawn(process.argv[0], ['child_program.js'], { - * detached: true, - * stdio: 'ignore', - * }); - * - * subprocess.unref(); - * subprocess.ref(); - * ``` - * @since v0.7.10 - */ - ref(): void; - /** - * events.EventEmitter - * 1. close - * 2. disconnect - * 3. error - * 4. exit - * 5. message - * 6. spawn - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; - addListener(event: "disconnect", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; - addListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; - addListener(event: "spawn", listener: () => void): this; - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "close", code: number | null, signal: NodeJS.Signals | null): boolean; - emit(event: "disconnect"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "exit", code: number | null, signal: NodeJS.Signals | null): boolean; - emit(event: "message", message: Serializable, sendHandle: SendHandle): boolean; - emit(event: "spawn", listener: () => void): boolean; - on(event: string, listener: (...args: any[]) => void): this; - on(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; - on(event: "disconnect", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; - on(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; - on(event: "spawn", listener: () => void): this; - once(event: string, listener: (...args: any[]) => void): this; - once(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; - once(event: "disconnect", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; - once(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; - once(event: "spawn", listener: () => void): this; - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; - prependListener(event: "disconnect", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; - prependListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; - prependListener(event: "spawn", listener: () => void): this; - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener( - event: "close", - listener: (code: number | null, signal: NodeJS.Signals | null) => void, - ): this; - prependOnceListener(event: "disconnect", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener( - event: "exit", - listener: (code: number | null, signal: NodeJS.Signals | null) => void, - ): this; - prependOnceListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; - prependOnceListener(event: "spawn", listener: () => void): this; - } - // return this object when stdio option is undefined or not specified - interface ChildProcessWithoutNullStreams extends ChildProcess { - stdin: Writable; - stdout: Readable; - stderr: Readable; - readonly stdio: [ - Writable, - Readable, - Readable, - // stderr - Readable | Writable | null | undefined, - // extra, no modification - Readable | Writable | null | undefined, // extra, no modification - ]; - } - // return this object when stdio option is a tuple of 3 - interface ChildProcessByStdio - extends ChildProcess - { - stdin: I; - stdout: O; - stderr: E; - readonly stdio: [ - I, - O, - E, - Readable | Writable | null | undefined, - // extra, no modification - Readable | Writable | null | undefined, // extra, no modification - ]; - } - interface MessageOptions { - keepOpen?: boolean | undefined; - } - type IOType = "overlapped" | "pipe" | "ignore" | "inherit"; - type StdioOptions = IOType | Array; - type SerializationType = "json" | "advanced"; - interface MessagingOptions extends Abortable { - /** - * Specify the kind of serialization used for sending messages between processes. - * @default 'json' - */ - serialization?: SerializationType | undefined; - /** - * The signal value to be used when the spawned process will be killed by the abort signal. - * @default 'SIGTERM' - */ - killSignal?: NodeJS.Signals | number | undefined; - /** - * In milliseconds the maximum amount of time the process is allowed to run. - */ - timeout?: number | undefined; - } - interface ProcessEnvOptions { - uid?: number | undefined; - gid?: number | undefined; - cwd?: string | URL | undefined; - env?: NodeJS.ProcessEnv | undefined; - } - interface CommonOptions extends ProcessEnvOptions { - /** - * @default false - */ - windowsHide?: boolean | undefined; - /** - * @default 0 - */ - timeout?: number | undefined; - } - interface CommonSpawnOptions extends CommonOptions, MessagingOptions, Abortable { - argv0?: string | undefined; - /** - * Can be set to 'pipe', 'inherit', 'overlapped', or 'ignore', or an array of these strings. - * If passed as an array, the first element is used for `stdin`, the second for - * `stdout`, and the third for `stderr`. A fourth element can be used to - * specify the `stdio` behavior beyond the standard streams. See - * {@link ChildProcess.stdio} for more information. - * - * @default 'pipe' - */ - stdio?: StdioOptions | undefined; - shell?: boolean | string | undefined; - windowsVerbatimArguments?: boolean | undefined; - } - interface SpawnOptions extends CommonSpawnOptions { - detached?: boolean | undefined; - } - interface SpawnOptionsWithoutStdio extends SpawnOptions { - stdio?: StdioPipeNamed | StdioPipe[] | undefined; - } - type StdioNull = "inherit" | "ignore" | Stream; - type StdioPipeNamed = "pipe" | "overlapped"; - type StdioPipe = undefined | null | StdioPipeNamed; - interface SpawnOptionsWithStdioTuple< - Stdin extends StdioNull | StdioPipe, - Stdout extends StdioNull | StdioPipe, - Stderr extends StdioNull | StdioPipe, - > extends SpawnOptions { - stdio: [Stdin, Stdout, Stderr]; - } - /** - * The `child_process.spawn()` method spawns a new process using the given`command`, with command-line arguments in `args`. If omitted, `args` defaults - * to an empty array. - * - * **If the `shell` option is enabled, do not pass unsanitized user input to this** - * **function. Any input containing shell metacharacters may be used to trigger** - * **arbitrary command execution.** - * - * A third argument may be used to specify additional options, with these defaults: - * - * ```js - * const defaults = { - * cwd: undefined, - * env: process.env, - * }; - * ``` - * - * Use `cwd` to specify the working directory from which the process is spawned. - * If not given, the default is to inherit the current working directory. If given, - * but the path does not exist, the child process emits an `ENOENT` error - * and exits immediately. `ENOENT` is also emitted when the command - * does not exist. - * - * Use `env` to specify environment variables that will be visible to the new - * process, the default is `process.env`. - * - * `undefined` values in `env` will be ignored. - * - * Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the - * exit code: - * - * ```js - * const { spawn } = require('node:child_process'); - * const ls = spawn('ls', ['-lh', '/usr']); - * - * ls.stdout.on('data', (data) => { - * console.log(`stdout: ${data}`); - * }); - * - * ls.stderr.on('data', (data) => { - * console.error(`stderr: ${data}`); - * }); - * - * ls.on('close', (code) => { - * console.log(`child process exited with code ${code}`); - * }); - * ``` - * - * Example: A very elaborate way to run `ps ax | grep ssh` - * - * ```js - * const { spawn } = require('node:child_process'); - * const ps = spawn('ps', ['ax']); - * const grep = spawn('grep', ['ssh']); - * - * ps.stdout.on('data', (data) => { - * grep.stdin.write(data); - * }); - * - * ps.stderr.on('data', (data) => { - * console.error(`ps stderr: ${data}`); - * }); - * - * ps.on('close', (code) => { - * if (code !== 0) { - * console.log(`ps process exited with code ${code}`); - * } - * grep.stdin.end(); - * }); - * - * grep.stdout.on('data', (data) => { - * console.log(data.toString()); - * }); - * - * grep.stderr.on('data', (data) => { - * console.error(`grep stderr: ${data}`); - * }); - * - * grep.on('close', (code) => { - * if (code !== 0) { - * console.log(`grep process exited with code ${code}`); - * } - * }); - * ``` - * - * Example of checking for failed `spawn`: - * - * ```js - * const { spawn } = require('node:child_process'); - * const subprocess = spawn('bad_command'); - * - * subprocess.on('error', (err) => { - * console.error('Failed to start subprocess.'); - * }); - * ``` - * - * Certain platforms (macOS, Linux) will use the value of `argv[0]` for the process - * title while others (Windows, SunOS) will use `command`. - * - * Node.js overwrites `argv[0]` with `process.execPath` on startup, so`process.argv[0]` in a Node.js child process will not match the `argv0`parameter passed to `spawn` from the parent. Retrieve - * it with the`process.argv0` property instead. - * - * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except - * the error passed to the callback will be an `AbortError`: - * - * ```js - * const { spawn } = require('node:child_process'); - * const controller = new AbortController(); - * const { signal } = controller; - * const grep = spawn('grep', ['ssh'], { signal }); - * grep.on('error', (err) => { - * // This will be called with err being an AbortError if the controller aborts - * }); - * controller.abort(); // Stops the child process - * ``` - * @since v0.1.90 - * @param command The command to run. - * @param args List of string arguments. - */ - function spawn(command: string, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams; - function spawn( - command: string, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn(command: string, options: SpawnOptions): ChildProcess; - // overloads of spawn with 'args' - function spawn( - command: string, - args?: readonly string[], - options?: SpawnOptionsWithoutStdio, - ): ChildProcessWithoutNullStreams; - function spawn( - command: string, - args: readonly string[], - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - args: readonly string[], - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - args: readonly string[], - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - args: readonly string[], - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - args: readonly string[], - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - args: readonly string[], - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - args: readonly string[], - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - args: readonly string[], - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn(command: string, args: readonly string[], options: SpawnOptions): ChildProcess; - interface ExecOptions extends CommonOptions { - shell?: string | undefined; - signal?: AbortSignal | undefined; - maxBuffer?: number | undefined; - killSignal?: NodeJS.Signals | number | undefined; - } - interface ExecOptionsWithStringEncoding extends ExecOptions { - encoding: BufferEncoding; - } - interface ExecOptionsWithBufferEncoding extends ExecOptions { - encoding: BufferEncoding | null; // specify `null`. - } - interface ExecException extends Error { - cmd?: string | undefined; - killed?: boolean | undefined; - code?: number | undefined; - signal?: NodeJS.Signals | undefined; - } - /** - * Spawns a shell then executes the `command` within that shell, buffering any - * generated output. The `command` string passed to the exec function is processed - * directly by the shell and special characters (vary based on [shell](https://en.wikipedia.org/wiki/List_of_command-line_interpreters)) - * need to be dealt with accordingly: - * - * ```js - * const { exec } = require('node:child_process'); - * - * exec('"/path/to/test file/test.sh" arg1 arg2'); - * // Double quotes are used so that the space in the path is not interpreted as - * // a delimiter of multiple arguments. - * - * exec('echo "The \\$HOME variable is $HOME"'); - * // The $HOME variable is escaped in the first instance, but not in the second. - * ``` - * - * **Never pass unsanitized user input to this function. Any input containing shell** - * **metacharacters may be used to trigger arbitrary command execution.** - * - * If a `callback` function is provided, it is called with the arguments`(error, stdout, stderr)`. On success, `error` will be `null`. On error,`error` will be an instance of `Error`. The - * `error.code` property will be - * the exit code of the process. By convention, any exit code other than `0`indicates an error. `error.signal` will be the signal that terminated the - * process. - * - * The `stdout` and `stderr` arguments passed to the callback will contain the - * stdout and stderr output of the child process. By default, Node.js will decode - * the output as UTF-8 and pass strings to the callback. The `encoding` option - * can be used to specify the character encoding used to decode the stdout and - * stderr output. If `encoding` is `'buffer'`, or an unrecognized character - * encoding, `Buffer` objects will be passed to the callback instead. - * - * ```js - * const { exec } = require('node:child_process'); - * exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => { - * if (error) { - * console.error(`exec error: ${error}`); - * return; - * } - * console.log(`stdout: ${stdout}`); - * console.error(`stderr: ${stderr}`); - * }); - * ``` - * - * If `timeout` is greater than `0`, the parent will send the signal - * identified by the `killSignal` property (the default is `'SIGTERM'`) if the - * child runs longer than `timeout` milliseconds. - * - * Unlike the [`exec(3)`](http://man7.org/linux/man-pages/man3/exec.3.html) POSIX system call, `child_process.exec()` does not replace - * the existing process and uses a shell to execute the command. - * - * If this method is invoked as its `util.promisify()` ed version, it returns - * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned`ChildProcess` instance is attached to the `Promise` as a `child` property. In - * case of an error (including any error resulting in an exit code other than 0), a - * rejected promise is returned, with the same `error` object given in the - * callback, but with two additional properties `stdout` and `stderr`. - * - * ```js - * const util = require('node:util'); - * const exec = util.promisify(require('node:child_process').exec); - * - * async function lsExample() { - * const { stdout, stderr } = await exec('ls'); - * console.log('stdout:', stdout); - * console.error('stderr:', stderr); - * } - * lsExample(); - * ``` - * - * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except - * the error passed to the callback will be an `AbortError`: - * - * ```js - * const { exec } = require('node:child_process'); - * const controller = new AbortController(); - * const { signal } = controller; - * const child = exec('grep ssh', { signal }, (error) => { - * console.error(error); // an AbortError - * }); - * controller.abort(); - * ``` - * @since v0.1.90 - * @param command The command to run, with space-separated arguments. - * @param callback called with the output when process terminates. - */ - function exec( - command: string, - callback?: (error: ExecException | null, stdout: string, stderr: string) => void, - ): ChildProcess; - // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. - function exec( - command: string, - options: { - encoding: "buffer" | null; - } & ExecOptions, - callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void, - ): ChildProcess; - // `options` with well known `encoding` means stdout/stderr are definitely `string`. - function exec( - command: string, - options: { - encoding: BufferEncoding; - } & ExecOptions, - callback?: (error: ExecException | null, stdout: string, stderr: string) => void, - ): ChildProcess; - // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. - // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. - function exec( - command: string, - options: { - encoding: BufferEncoding; - } & ExecOptions, - callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void, - ): ChildProcess; - // `options` without an `encoding` means stdout/stderr are definitely `string`. - function exec( - command: string, - options: ExecOptions, - callback?: (error: ExecException | null, stdout: string, stderr: string) => void, - ): ChildProcess; - // fallback if nothing else matches. Worst case is always `string | Buffer`. - function exec( - command: string, - options: (ObjectEncodingOptions & ExecOptions) | undefined | null, - callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void, - ): ChildProcess; - interface PromiseWithChild extends Promise { - child: ChildProcess; - } - namespace exec { - function __promisify__(command: string): PromiseWithChild<{ - stdout: string; - stderr: string; - }>; - function __promisify__( - command: string, - options: { - encoding: "buffer" | null; - } & ExecOptions, - ): PromiseWithChild<{ - stdout: Buffer; - stderr: Buffer; - }>; - function __promisify__( - command: string, - options: { - encoding: BufferEncoding; - } & ExecOptions, - ): PromiseWithChild<{ - stdout: string; - stderr: string; - }>; - function __promisify__( - command: string, - options: ExecOptions, - ): PromiseWithChild<{ - stdout: string; - stderr: string; - }>; - function __promisify__( - command: string, - options?: (ObjectEncodingOptions & ExecOptions) | null, - ): PromiseWithChild<{ - stdout: string | Buffer; - stderr: string | Buffer; - }>; - } - interface ExecFileOptions extends CommonOptions, Abortable { - maxBuffer?: number | undefined; - killSignal?: NodeJS.Signals | number | undefined; - windowsVerbatimArguments?: boolean | undefined; - shell?: boolean | string | undefined; - signal?: AbortSignal | undefined; - } - interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { - encoding: BufferEncoding; - } - interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { - encoding: "buffer" | null; - } - interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions { - encoding: BufferEncoding; - } - type ExecFileException = - & Omit - & Omit - & { code?: string | number | undefined | null }; - /** - * The `child_process.execFile()` function is similar to {@link exec} except that it does not spawn a shell by default. Rather, the specified - * executable `file` is spawned directly as a new process making it slightly more - * efficient than {@link exec}. - * - * The same options as {@link exec} are supported. Since a shell is - * not spawned, behaviors such as I/O redirection and file globbing are not - * supported. - * - * ```js - * const { execFile } = require('node:child_process'); - * const child = execFile('node', ['--version'], (error, stdout, stderr) => { - * if (error) { - * throw error; - * } - * console.log(stdout); - * }); - * ``` - * - * The `stdout` and `stderr` arguments passed to the callback will contain the - * stdout and stderr output of the child process. By default, Node.js will decode - * the output as UTF-8 and pass strings to the callback. The `encoding` option - * can be used to specify the character encoding used to decode the stdout and - * stderr output. If `encoding` is `'buffer'`, or an unrecognized character - * encoding, `Buffer` objects will be passed to the callback instead. - * - * If this method is invoked as its `util.promisify()` ed version, it returns - * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned`ChildProcess` instance is attached to the `Promise` as a `child` property. In - * case of an error (including any error resulting in an exit code other than 0), a - * rejected promise is returned, with the same `error` object given in the - * callback, but with two additional properties `stdout` and `stderr`. - * - * ```js - * const util = require('node:util'); - * const execFile = util.promisify(require('node:child_process').execFile); - * async function getVersion() { - * const { stdout } = await execFile('node', ['--version']); - * console.log(stdout); - * } - * getVersion(); - * ``` - * - * **If the `shell` option is enabled, do not pass unsanitized user input to this** - * **function. Any input containing shell metacharacters may be used to trigger** - * **arbitrary command execution.** - * - * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except - * the error passed to the callback will be an `AbortError`: - * - * ```js - * const { execFile } = require('node:child_process'); - * const controller = new AbortController(); - * const { signal } = controller; - * const child = execFile('node', ['--version'], { signal }, (error) => { - * console.error(error); // an AbortError - * }); - * controller.abort(); - * ``` - * @since v0.1.91 - * @param file The name or path of the executable file to run. - * @param args List of string arguments. - * @param callback Called with the output when process terminates. - */ - function execFile(file: string): ChildProcess; - function execFile( - file: string, - options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, - ): ChildProcess; - function execFile(file: string, args?: readonly string[] | null): ChildProcess; - function execFile( - file: string, - args: readonly string[] | undefined | null, - options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, - ): ChildProcess; - // no `options` definitely means stdout/stderr are `string`. - function execFile( - file: string, - callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, - ): ChildProcess; - function execFile( - file: string, - args: readonly string[] | undefined | null, - callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, - ): ChildProcess; - // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. - function execFile( - file: string, - options: ExecFileOptionsWithBufferEncoding, - callback: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void, - ): ChildProcess; - function execFile( - file: string, - args: readonly string[] | undefined | null, - options: ExecFileOptionsWithBufferEncoding, - callback: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void, - ): ChildProcess; - // `options` with well known `encoding` means stdout/stderr are definitely `string`. - function execFile( - file: string, - options: ExecFileOptionsWithStringEncoding, - callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, - ): ChildProcess; - function execFile( - file: string, - args: readonly string[] | undefined | null, - options: ExecFileOptionsWithStringEncoding, - callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, - ): ChildProcess; - // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. - // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. - function execFile( - file: string, - options: ExecFileOptionsWithOtherEncoding, - callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void, - ): ChildProcess; - function execFile( - file: string, - args: readonly string[] | undefined | null, - options: ExecFileOptionsWithOtherEncoding, - callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void, - ): ChildProcess; - // `options` without an `encoding` means stdout/stderr are definitely `string`. - function execFile( - file: string, - options: ExecFileOptions, - callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, - ): ChildProcess; - function execFile( - file: string, - args: readonly string[] | undefined | null, - options: ExecFileOptions, - callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, - ): ChildProcess; - // fallback if nothing else matches. Worst case is always `string | Buffer`. - function execFile( - file: string, - options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, - callback: - | ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) - | undefined - | null, - ): ChildProcess; - function execFile( - file: string, - args: readonly string[] | undefined | null, - options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, - callback: - | ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) - | undefined - | null, - ): ChildProcess; - namespace execFile { - function __promisify__(file: string): PromiseWithChild<{ - stdout: string; - stderr: string; - }>; - function __promisify__( - file: string, - args: readonly string[] | undefined | null, - ): PromiseWithChild<{ - stdout: string; - stderr: string; - }>; - function __promisify__( - file: string, - options: ExecFileOptionsWithBufferEncoding, - ): PromiseWithChild<{ - stdout: Buffer; - stderr: Buffer; - }>; - function __promisify__( - file: string, - args: readonly string[] | undefined | null, - options: ExecFileOptionsWithBufferEncoding, - ): PromiseWithChild<{ - stdout: Buffer; - stderr: Buffer; - }>; - function __promisify__( - file: string, - options: ExecFileOptionsWithStringEncoding, - ): PromiseWithChild<{ - stdout: string; - stderr: string; - }>; - function __promisify__( - file: string, - args: readonly string[] | undefined | null, - options: ExecFileOptionsWithStringEncoding, - ): PromiseWithChild<{ - stdout: string; - stderr: string; - }>; - function __promisify__( - file: string, - options: ExecFileOptionsWithOtherEncoding, - ): PromiseWithChild<{ - stdout: string | Buffer; - stderr: string | Buffer; - }>; - function __promisify__( - file: string, - args: readonly string[] | undefined | null, - options: ExecFileOptionsWithOtherEncoding, - ): PromiseWithChild<{ - stdout: string | Buffer; - stderr: string | Buffer; - }>; - function __promisify__( - file: string, - options: ExecFileOptions, - ): PromiseWithChild<{ - stdout: string; - stderr: string; - }>; - function __promisify__( - file: string, - args: readonly string[] | undefined | null, - options: ExecFileOptions, - ): PromiseWithChild<{ - stdout: string; - stderr: string; - }>; - function __promisify__( - file: string, - options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, - ): PromiseWithChild<{ - stdout: string | Buffer; - stderr: string | Buffer; - }>; - function __promisify__( - file: string, - args: readonly string[] | undefined | null, - options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, - ): PromiseWithChild<{ - stdout: string | Buffer; - stderr: string | Buffer; - }>; - } - interface ForkOptions extends ProcessEnvOptions, MessagingOptions, Abortable { - execPath?: string | undefined; - execArgv?: string[] | undefined; - silent?: boolean | undefined; - /** - * Can be set to 'pipe', 'inherit', 'overlapped', or 'ignore', or an array of these strings. - * If passed as an array, the first element is used for `stdin`, the second for - * `stdout`, and the third for `stderr`. A fourth element can be used to - * specify the `stdio` behavior beyond the standard streams. See - * {@link ChildProcess.stdio} for more information. - * - * @default 'pipe' - */ - stdio?: StdioOptions | undefined; - detached?: boolean | undefined; - windowsVerbatimArguments?: boolean | undefined; - } - /** - * The `child_process.fork()` method is a special case of {@link spawn} used specifically to spawn new Node.js processes. - * Like {@link spawn}, a `ChildProcess` object is returned. The - * returned `ChildProcess` will have an additional communication channel - * built-in that allows messages to be passed back and forth between the parent and - * child. See `subprocess.send()` for details. - * - * Keep in mind that spawned Node.js child processes are - * independent of the parent with exception of the IPC communication channel - * that is established between the two. Each process has its own memory, with - * their own V8 instances. Because of the additional resource allocations - * required, spawning a large number of child Node.js processes is not - * recommended. - * - * By default, `child_process.fork()` will spawn new Node.js instances using the `process.execPath` of the parent process. The `execPath` property in the`options` object allows for an alternative - * execution path to be used. - * - * Node.js processes launched with a custom `execPath` will communicate with the - * parent process using the file descriptor (fd) identified using the - * environment variable `NODE_CHANNEL_FD` on the child process. - * - * Unlike the [`fork(2)`](http://man7.org/linux/man-pages/man2/fork.2.html) POSIX system call, `child_process.fork()` does not clone the - * current process. - * - * The `shell` option available in {@link spawn} is not supported by`child_process.fork()` and will be ignored if set. - * - * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except - * the error passed to the callback will be an `AbortError`: - * - * ```js - * if (process.argv[2] === 'child') { - * setTimeout(() => { - * console.log(`Hello from ${process.argv[2]}!`); - * }, 1_000); - * } else { - * const { fork } = require('node:child_process'); - * const controller = new AbortController(); - * const { signal } = controller; - * const child = fork(__filename, ['child'], { signal }); - * child.on('error', (err) => { - * // This will be called with err being an AbortError if the controller aborts - * }); - * controller.abort(); // Stops the child process - * } - * ``` - * @since v0.5.0 - * @param modulePath The module to run in the child. - * @param args List of string arguments. - */ - function fork(modulePath: string, options?: ForkOptions): ChildProcess; - function fork(modulePath: string, args?: readonly string[], options?: ForkOptions): ChildProcess; - interface SpawnSyncOptions extends CommonSpawnOptions { - input?: string | NodeJS.ArrayBufferView | undefined; - maxBuffer?: number | undefined; - encoding?: BufferEncoding | "buffer" | null | undefined; - } - interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { - encoding: BufferEncoding; - } - interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { - encoding?: "buffer" | null | undefined; - } - interface SpawnSyncReturns { - pid: number; - output: Array; - stdout: T; - stderr: T; - status: number | null; - signal: NodeJS.Signals | null; - error?: Error | undefined; - } - /** - * The `child_process.spawnSync()` method is generally identical to {@link spawn} with the exception that the function will not return - * until the child process has fully closed. When a timeout has been encountered - * and `killSignal` is sent, the method won't return until the process has - * completely exited. If the process intercepts and handles the `SIGTERM` signal - * and doesn't exit, the parent process will wait until the child process has - * exited. - * - * **If the `shell` option is enabled, do not pass unsanitized user input to this** - * **function. Any input containing shell metacharacters may be used to trigger** - * **arbitrary command execution.** - * @since v0.11.12 - * @param command The command to run. - * @param args List of string arguments. - */ - function spawnSync(command: string): SpawnSyncReturns; - function spawnSync(command: string, options: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; - function spawnSync(command: string, options: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; - function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; - function spawnSync(command: string, args: readonly string[]): SpawnSyncReturns; - function spawnSync( - command: string, - args: readonly string[], - options: SpawnSyncOptionsWithStringEncoding, - ): SpawnSyncReturns; - function spawnSync( - command: string, - args: readonly string[], - options: SpawnSyncOptionsWithBufferEncoding, - ): SpawnSyncReturns; - function spawnSync( - command: string, - args?: readonly string[], - options?: SpawnSyncOptions, - ): SpawnSyncReturns; - interface CommonExecOptions extends CommonOptions { - input?: string | NodeJS.ArrayBufferView | undefined; - /** - * Can be set to 'pipe', 'inherit, or 'ignore', or an array of these strings. - * If passed as an array, the first element is used for `stdin`, the second for - * `stdout`, and the third for `stderr`. A fourth element can be used to - * specify the `stdio` behavior beyond the standard streams. See - * {@link ChildProcess.stdio} for more information. - * - * @default 'pipe' - */ - stdio?: StdioOptions | undefined; - killSignal?: NodeJS.Signals | number | undefined; - maxBuffer?: number | undefined; - encoding?: BufferEncoding | "buffer" | null | undefined; - } - interface ExecSyncOptions extends CommonExecOptions { - shell?: string | undefined; - } - interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { - encoding: BufferEncoding; - } - interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { - encoding?: "buffer" | null | undefined; - } - /** - * The `child_process.execSync()` method is generally identical to {@link exec} with the exception that the method will not return - * until the child process has fully closed. When a timeout has been encountered - * and `killSignal` is sent, the method won't return until the process has - * completely exited. If the child process intercepts and handles the `SIGTERM`signal and doesn't exit, the parent process will wait until the child process - * has exited. - * - * If the process times out or has a non-zero exit code, this method will throw. - * The `Error` object will contain the entire result from {@link spawnSync}. - * - * **Never pass unsanitized user input to this function. Any input containing shell** - * **metacharacters may be used to trigger arbitrary command execution.** - * @since v0.11.12 - * @param command The command to run. - * @return The stdout from the command. - */ - function execSync(command: string): Buffer; - function execSync(command: string, options: ExecSyncOptionsWithStringEncoding): string; - function execSync(command: string, options: ExecSyncOptionsWithBufferEncoding): Buffer; - function execSync(command: string, options?: ExecSyncOptions): string | Buffer; - interface ExecFileSyncOptions extends CommonExecOptions { - shell?: boolean | string | undefined; - } - interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { - encoding: BufferEncoding; - } - interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { - encoding?: "buffer" | null; // specify `null`. - } - /** - * The `child_process.execFileSync()` method is generally identical to {@link execFile} with the exception that the method will not - * return until the child process has fully closed. When a timeout has been - * encountered and `killSignal` is sent, the method won't return until the process - * has completely exited. - * - * If the child process intercepts and handles the `SIGTERM` signal and - * does not exit, the parent process will still wait until the child process has - * exited. - * - * If the process times out or has a non-zero exit code, this method will throw an `Error` that will include the full result of the underlying {@link spawnSync}. - * - * **If the `shell` option is enabled, do not pass unsanitized user input to this** - * **function. Any input containing shell metacharacters may be used to trigger** - * **arbitrary command execution.** - * @since v0.11.12 - * @param file The name or path of the executable file to run. - * @param args List of string arguments. - * @return The stdout from the command. - */ - function execFileSync(file: string): Buffer; - function execFileSync(file: string, options: ExecFileSyncOptionsWithStringEncoding): string; - function execFileSync(file: string, options: ExecFileSyncOptionsWithBufferEncoding): Buffer; - function execFileSync(file: string, options?: ExecFileSyncOptions): string | Buffer; - function execFileSync(file: string, args: readonly string[]): Buffer; - function execFileSync( - file: string, - args: readonly string[], - options: ExecFileSyncOptionsWithStringEncoding, - ): string; - function execFileSync( - file: string, - args: readonly string[], - options: ExecFileSyncOptionsWithBufferEncoding, - ): Buffer; - function execFileSync(file: string, args?: readonly string[], options?: ExecFileSyncOptions): string | Buffer; -} -declare module "node:child_process" { - export * from "child_process"; -} diff --git a/node_modules/@types/node/ts4.8/cluster.d.ts b/node_modules/@types/node/ts4.8/cluster.d.ts deleted file mode 100644 index 39cd56ad3c6e2fa946dc94c84e581e385eab2627..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/cluster.d.ts +++ /dev/null @@ -1,432 +0,0 @@ -/** - * Clusters of Node.js processes can be used to run multiple instances of Node.js - * that can distribute workloads among their application threads. When process - * isolation is not needed, use the `worker_threads` module instead, which - * allows running multiple application threads within a single Node.js instance. - * - * The cluster module allows easy creation of child processes that all share - * server ports. - * - * ```js - * import cluster from 'node:cluster'; - * import http from 'node:http'; - * import { availableParallelism } from 'node:os'; - * import process from 'node:process'; - * - * const numCPUs = availableParallelism(); - * - * if (cluster.isPrimary) { - * console.log(`Primary ${process.pid} is running`); - * - * // Fork workers. - * for (let i = 0; i < numCPUs; i++) { - * cluster.fork(); - * } - * - * cluster.on('exit', (worker, code, signal) => { - * console.log(`worker ${worker.process.pid} died`); - * }); - * } else { - * // Workers can share any TCP connection - * // In this case it is an HTTP server - * http.createServer((req, res) => { - * res.writeHead(200); - * res.end('hello world\n'); - * }).listen(8000); - * - * console.log(`Worker ${process.pid} started`); - * } - * ``` - * - * Running Node.js will now share port 8000 between the workers: - * - * ```console - * $ node server.js - * Primary 3596 is running - * Worker 4324 started - * Worker 4520 started - * Worker 6056 started - * Worker 5644 started - * ``` - * - * On Windows, it is not yet possible to set up a named pipe server in a worker. - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/cluster.js) - */ -declare module "cluster" { - import * as child from "node:child_process"; - import EventEmitter = require("node:events"); - import * as net from "node:net"; - type SerializationType = "json" | "advanced"; - export interface ClusterSettings { - execArgv?: string[] | undefined; // default: process.execArgv - exec?: string | undefined; - args?: string[] | undefined; - silent?: boolean | undefined; - stdio?: any[] | undefined; - uid?: number | undefined; - gid?: number | undefined; - inspectPort?: number | (() => number) | undefined; - serialization?: SerializationType | undefined; - cwd?: string | undefined; - windowsHide?: boolean | undefined; - } - export interface Address { - address: string; - port: number; - addressType: number | "udp4" | "udp6"; // 4, 6, -1, "udp4", "udp6" - } - /** - * A `Worker` object contains all public information and method about a worker. - * In the primary it can be obtained using `cluster.workers`. In a worker - * it can be obtained using `cluster.worker`. - * @since v0.7.0 - */ - export class Worker extends EventEmitter { - /** - * Each new worker is given its own unique id, this id is stored in the`id`. - * - * While a worker is alive, this is the key that indexes it in`cluster.workers`. - * @since v0.8.0 - */ - id: number; - /** - * All workers are created using `child_process.fork()`, the returned object - * from this function is stored as `.process`. In a worker, the global `process`is stored. - * - * See: `Child Process module`. - * - * Workers will call `process.exit(0)` if the `'disconnect'` event occurs - * on `process` and `.exitedAfterDisconnect` is not `true`. This protects against - * accidental disconnection. - * @since v0.7.0 - */ - process: child.ChildProcess; - /** - * Send a message to a worker or primary, optionally with a handle. - * - * In the primary, this sends a message to a specific worker. It is identical to `ChildProcess.send()`. - * - * In a worker, this sends a message to the primary. It is identical to`process.send()`. - * - * This example will echo back all messages from the primary: - * - * ```js - * if (cluster.isPrimary) { - * const worker = cluster.fork(); - * worker.send('hi there'); - * - * } else if (cluster.isWorker) { - * process.on('message', (msg) => { - * process.send(msg); - * }); - * } - * ``` - * @since v0.7.0 - * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties: - */ - send(message: child.Serializable, callback?: (error: Error | null) => void): boolean; - send( - message: child.Serializable, - sendHandle: child.SendHandle, - callback?: (error: Error | null) => void, - ): boolean; - send( - message: child.Serializable, - sendHandle: child.SendHandle, - options?: child.MessageOptions, - callback?: (error: Error | null) => void, - ): boolean; - /** - * This function will kill the worker. In the primary worker, it does this by - * disconnecting the `worker.process`, and once disconnected, killing with`signal`. In the worker, it does it by killing the process with `signal`. - * - * The `kill()` function kills the worker process without waiting for a graceful - * disconnect, it has the same behavior as `worker.process.kill()`. - * - * This method is aliased as `worker.destroy()` for backwards compatibility. - * - * In a worker, `process.kill()` exists, but it is not this function; - * it is `kill()`. - * @since v0.9.12 - * @param [signal='SIGTERM'] Name of the kill signal to send to the worker process. - */ - kill(signal?: string): void; - destroy(signal?: string): void; - /** - * In a worker, this function will close all servers, wait for the `'close'` event - * on those servers, and then disconnect the IPC channel. - * - * In the primary, an internal message is sent to the worker causing it to call`.disconnect()` on itself. - * - * Causes `.exitedAfterDisconnect` to be set. - * - * After a server is closed, it will no longer accept new connections, - * but connections may be accepted by any other listening worker. Existing - * connections will be allowed to close as usual. When no more connections exist, - * see `server.close()`, the IPC channel to the worker will close allowing it - * to die gracefully. - * - * The above applies _only_ to server connections, client connections are not - * automatically closed by workers, and disconnect does not wait for them to close - * before exiting. - * - * In a worker, `process.disconnect` exists, but it is not this function; - * it is `disconnect()`. - * - * Because long living server connections may block workers from disconnecting, it - * may be useful to send a message, so application specific actions may be taken to - * close them. It also may be useful to implement a timeout, killing a worker if - * the `'disconnect'` event has not been emitted after some time. - * - * ```js - * if (cluster.isPrimary) { - * const worker = cluster.fork(); - * let timeout; - * - * worker.on('listening', (address) => { - * worker.send('shutdown'); - * worker.disconnect(); - * timeout = setTimeout(() => { - * worker.kill(); - * }, 2000); - * }); - * - * worker.on('disconnect', () => { - * clearTimeout(timeout); - * }); - * - * } else if (cluster.isWorker) { - * const net = require('node:net'); - * const server = net.createServer((socket) => { - * // Connections never end - * }); - * - * server.listen(8000); - * - * process.on('message', (msg) => { - * if (msg === 'shutdown') { - * // Initiate graceful close of any connections to server - * } - * }); - * } - * ``` - * @since v0.7.7 - * @return A reference to `worker`. - */ - disconnect(): void; - /** - * This function returns `true` if the worker is connected to its primary via its - * IPC channel, `false` otherwise. A worker is connected to its primary after it - * has been created. It is disconnected after the `'disconnect'` event is emitted. - * @since v0.11.14 - */ - isConnected(): boolean; - /** - * This function returns `true` if the worker's process has terminated (either - * because of exiting or being signaled). Otherwise, it returns `false`. - * - * ```js - * import cluster from 'node:cluster'; - * import http from 'node:http'; - * import { availableParallelism } from 'node:os'; - * import process from 'node:process'; - * - * const numCPUs = availableParallelism(); - * - * if (cluster.isPrimary) { - * console.log(`Primary ${process.pid} is running`); - * - * // Fork workers. - * for (let i = 0; i < numCPUs; i++) { - * cluster.fork(); - * } - * - * cluster.on('fork', (worker) => { - * console.log('worker is dead:', worker.isDead()); - * }); - * - * cluster.on('exit', (worker, code, signal) => { - * console.log('worker is dead:', worker.isDead()); - * }); - * } else { - * // Workers can share any TCP connection. In this case, it is an HTTP server. - * http.createServer((req, res) => { - * res.writeHead(200); - * res.end(`Current process\n ${process.pid}`); - * process.kill(process.pid); - * }).listen(8000); - * } - * ``` - * @since v0.11.14 - */ - isDead(): boolean; - /** - * This property is `true` if the worker exited due to `.disconnect()`. - * If the worker exited any other way, it is `false`. If the - * worker has not exited, it is `undefined`. - * - * The boolean `worker.exitedAfterDisconnect` allows distinguishing between - * voluntary and accidental exit, the primary may choose not to respawn a worker - * based on this value. - * - * ```js - * cluster.on('exit', (worker, code, signal) => { - * if (worker.exitedAfterDisconnect === true) { - * console.log('Oh, it was just voluntary – no need to worry'); - * } - * }); - * - * // kill worker - * worker.kill(); - * ``` - * @since v6.0.0 - */ - exitedAfterDisconnect: boolean; - /** - * events.EventEmitter - * 1. disconnect - * 2. error - * 3. exit - * 4. listening - * 5. message - * 6. online - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "disconnect", listener: () => void): this; - addListener(event: "error", listener: (error: Error) => void): this; - addListener(event: "exit", listener: (code: number, signal: string) => void): this; - addListener(event: "listening", listener: (address: Address) => void): this; - addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - addListener(event: "online", listener: () => void): this; - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "disconnect"): boolean; - emit(event: "error", error: Error): boolean; - emit(event: "exit", code: number, signal: string): boolean; - emit(event: "listening", address: Address): boolean; - emit(event: "message", message: any, handle: net.Socket | net.Server): boolean; - emit(event: "online"): boolean; - on(event: string, listener: (...args: any[]) => void): this; - on(event: "disconnect", listener: () => void): this; - on(event: "error", listener: (error: Error) => void): this; - on(event: "exit", listener: (code: number, signal: string) => void): this; - on(event: "listening", listener: (address: Address) => void): this; - on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - on(event: "online", listener: () => void): this; - once(event: string, listener: (...args: any[]) => void): this; - once(event: "disconnect", listener: () => void): this; - once(event: "error", listener: (error: Error) => void): this; - once(event: "exit", listener: (code: number, signal: string) => void): this; - once(event: "listening", listener: (address: Address) => void): this; - once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - once(event: "online", listener: () => void): this; - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "disconnect", listener: () => void): this; - prependListener(event: "error", listener: (error: Error) => void): this; - prependListener(event: "exit", listener: (code: number, signal: string) => void): this; - prependListener(event: "listening", listener: (address: Address) => void): this; - prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - prependListener(event: "online", listener: () => void): this; - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "disconnect", listener: () => void): this; - prependOnceListener(event: "error", listener: (error: Error) => void): this; - prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; - prependOnceListener(event: "listening", listener: (address: Address) => void): this; - prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - prependOnceListener(event: "online", listener: () => void): this; - } - export interface Cluster extends EventEmitter { - disconnect(callback?: () => void): void; - fork(env?: any): Worker; - /** @deprecated since v16.0.0 - use isPrimary. */ - readonly isMaster: boolean; - readonly isPrimary: boolean; - readonly isWorker: boolean; - schedulingPolicy: number; - readonly settings: ClusterSettings; - /** @deprecated since v16.0.0 - use setupPrimary. */ - setupMaster(settings?: ClusterSettings): void; - /** - * `setupPrimary` is used to change the default 'fork' behavior. Once called, the settings will be present in cluster.settings. - */ - setupPrimary(settings?: ClusterSettings): void; - readonly worker?: Worker | undefined; - readonly workers?: NodeJS.Dict | undefined; - readonly SCHED_NONE: number; - readonly SCHED_RR: number; - /** - * events.EventEmitter - * 1. disconnect - * 2. exit - * 3. fork - * 4. listening - * 5. message - * 6. online - * 7. setup - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "disconnect", listener: (worker: Worker) => void): this; - addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; - addListener(event: "fork", listener: (worker: Worker) => void): this; - addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; - addListener( - event: "message", - listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void, - ): this; // the handle is a net.Socket or net.Server object, or undefined. - addListener(event: "online", listener: (worker: Worker) => void): this; - addListener(event: "setup", listener: (settings: ClusterSettings) => void): this; - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "disconnect", worker: Worker): boolean; - emit(event: "exit", worker: Worker, code: number, signal: string): boolean; - emit(event: "fork", worker: Worker): boolean; - emit(event: "listening", worker: Worker, address: Address): boolean; - emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean; - emit(event: "online", worker: Worker): boolean; - emit(event: "setup", settings: ClusterSettings): boolean; - on(event: string, listener: (...args: any[]) => void): this; - on(event: "disconnect", listener: (worker: Worker) => void): this; - on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; - on(event: "fork", listener: (worker: Worker) => void): this; - on(event: "listening", listener: (worker: Worker, address: Address) => void): this; - on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - on(event: "online", listener: (worker: Worker) => void): this; - on(event: "setup", listener: (settings: ClusterSettings) => void): this; - once(event: string, listener: (...args: any[]) => void): this; - once(event: "disconnect", listener: (worker: Worker) => void): this; - once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; - once(event: "fork", listener: (worker: Worker) => void): this; - once(event: "listening", listener: (worker: Worker, address: Address) => void): this; - once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - once(event: "online", listener: (worker: Worker) => void): this; - once(event: "setup", listener: (settings: ClusterSettings) => void): this; - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "disconnect", listener: (worker: Worker) => void): this; - prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; - prependListener(event: "fork", listener: (worker: Worker) => void): this; - prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; - // the handle is a net.Socket or net.Server object, or undefined. - prependListener( - event: "message", - listener: (worker: Worker, message: any, handle?: net.Socket | net.Server) => void, - ): this; - prependListener(event: "online", listener: (worker: Worker) => void): this; - prependListener(event: "setup", listener: (settings: ClusterSettings) => void): this; - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this; - prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; - prependOnceListener(event: "fork", listener: (worker: Worker) => void): this; - prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; - // the handle is a net.Socket or net.Server object, or undefined. - prependOnceListener( - event: "message", - listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void, - ): this; - prependOnceListener(event: "online", listener: (worker: Worker) => void): this; - prependOnceListener(event: "setup", listener: (settings: ClusterSettings) => void): this; - } - const cluster: Cluster; - export default cluster; -} -declare module "node:cluster" { - export * from "cluster"; - export { default as default } from "cluster"; -} diff --git a/node_modules/@types/node/ts4.8/console.d.ts b/node_modules/@types/node/ts4.8/console.d.ts deleted file mode 100644 index bcc345042058790cbb22a77c89c62cab472ab86d..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/console.d.ts +++ /dev/null @@ -1,415 +0,0 @@ -/** - * The `node:console` module provides a simple debugging console that is similar to - * the JavaScript console mechanism provided by web browsers. - * - * The module exports two specific components: - * - * * A `Console` class with methods such as `console.log()`, `console.error()`, and`console.warn()` that can be used to write to any Node.js stream. - * * A global `console` instance configured to write to `process.stdout` and `process.stderr`. The global `console` can be used without calling`require('node:console')`. - * - * _**Warning**_: The global console object's methods are neither consistently - * synchronous like the browser APIs they resemble, nor are they consistently - * asynchronous like all other Node.js streams. See the `note on process I/O` for - * more information. - * - * Example using the global `console`: - * - * ```js - * console.log('hello world'); - * // Prints: hello world, to stdout - * console.log('hello %s', 'world'); - * // Prints: hello world, to stdout - * console.error(new Error('Whoops, something bad happened')); - * // Prints error message and stack trace to stderr: - * // Error: Whoops, something bad happened - * // at [eval]:5:15 - * // at Script.runInThisContext (node:vm:132:18) - * // at Object.runInThisContext (node:vm:309:38) - * // at node:internal/process/execution:77:19 - * // at [eval]-wrapper:6:22 - * // at evalScript (node:internal/process/execution:76:60) - * // at node:internal/main/eval_string:23:3 - * - * const name = 'Will Robinson'; - * console.warn(`Danger ${name}! Danger!`); - * // Prints: Danger Will Robinson! Danger!, to stderr - * ``` - * - * Example using the `Console` class: - * - * ```js - * const out = getStreamSomehow(); - * const err = getStreamSomehow(); - * const myConsole = new console.Console(out, err); - * - * myConsole.log('hello world'); - * // Prints: hello world, to out - * myConsole.log('hello %s', 'world'); - * // Prints: hello world, to out - * myConsole.error(new Error('Whoops, something bad happened')); - * // Prints: [Error: Whoops, something bad happened], to err - * - * const name = 'Will Robinson'; - * myConsole.warn(`Danger ${name}! Danger!`); - * // Prints: Danger Will Robinson! Danger!, to err - * ``` - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/console.js) - */ -declare module "console" { - import console = require("node:console"); - export = console; -} -declare module "node:console" { - import { InspectOptions } from "node:util"; - global { - // This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build - interface Console { - Console: console.ConsoleConstructor; - /** - * `console.assert()` writes a message if `value` is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) or omitted. It only - * writes a message and does not otherwise affect execution. The output always - * starts with `"Assertion failed"`. If provided, `message` is formatted using `util.format()`. - * - * If `value` is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), nothing happens. - * - * ```js - * console.assert(true, 'does nothing'); - * - * console.assert(false, 'Whoops %s work', 'didn\'t'); - * // Assertion failed: Whoops didn't work - * - * console.assert(); - * // Assertion failed - * ``` - * @since v0.1.101 - * @param value The value tested for being truthy. - * @param message All arguments besides `value` are used as error message. - */ - assert(value: any, message?: string, ...optionalParams: any[]): void; - /** - * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the - * TTY. When `stdout` is not a TTY, this method does nothing. - * - * The specific operation of `console.clear()` can vary across operating systems - * and terminal types. For most Linux operating systems, `console.clear()`operates similarly to the `clear` shell command. On Windows, `console.clear()`will clear only the output in the - * current terminal viewport for the Node.js - * binary. - * @since v8.3.0 - */ - clear(): void; - /** - * Maintains an internal counter specific to `label` and outputs to `stdout` the - * number of times `console.count()` has been called with the given `label`. - * - * ```js - * > console.count() - * default: 1 - * undefined - * > console.count('default') - * default: 2 - * undefined - * > console.count('abc') - * abc: 1 - * undefined - * > console.count('xyz') - * xyz: 1 - * undefined - * > console.count('abc') - * abc: 2 - * undefined - * > console.count() - * default: 3 - * undefined - * > - * ``` - * @since v8.3.0 - * @param [label='default'] The display label for the counter. - */ - count(label?: string): void; - /** - * Resets the internal counter specific to `label`. - * - * ```js - * > console.count('abc'); - * abc: 1 - * undefined - * > console.countReset('abc'); - * undefined - * > console.count('abc'); - * abc: 1 - * undefined - * > - * ``` - * @since v8.3.0 - * @param [label='default'] The display label for the counter. - */ - countReset(label?: string): void; - /** - * The `console.debug()` function is an alias for {@link log}. - * @since v8.0.0 - */ - debug(message?: any, ...optionalParams: any[]): void; - /** - * Uses `util.inspect()` on `obj` and prints the resulting string to `stdout`. - * This function bypasses any custom `inspect()` function defined on `obj`. - * @since v0.1.101 - */ - dir(obj: any, options?: InspectOptions): void; - /** - * This method calls `console.log()` passing it the arguments received. - * This method does not produce any XML formatting. - * @since v8.0.0 - */ - dirxml(...data: any[]): void; - /** - * Prints to `stderr` with newline. Multiple arguments can be passed, with the - * first used as the primary message and all additional used as substitution - * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to `util.format()`). - * - * ```js - * const code = 5; - * console.error('error #%d', code); - * // Prints: error #5, to stderr - * console.error('error', code); - * // Prints: error 5, to stderr - * ``` - * - * If formatting elements (e.g. `%d`) are not found in the first string then `util.inspect()` is called on each argument and the resulting string - * values are concatenated. See `util.format()` for more information. - * @since v0.1.100 - */ - error(message?: any, ...optionalParams: any[]): void; - /** - * Increases indentation of subsequent lines by spaces for `groupIndentation`length. - * - * If one or more `label`s are provided, those are printed first without the - * additional indentation. - * @since v8.5.0 - */ - group(...label: any[]): void; - /** - * An alias for {@link group}. - * @since v8.5.0 - */ - groupCollapsed(...label: any[]): void; - /** - * Decreases indentation of subsequent lines by spaces for `groupIndentation`length. - * @since v8.5.0 - */ - groupEnd(): void; - /** - * The `console.info()` function is an alias for {@link log}. - * @since v0.1.100 - */ - info(message?: any, ...optionalParams: any[]): void; - /** - * Prints to `stdout` with newline. Multiple arguments can be passed, with the - * first used as the primary message and all additional used as substitution - * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to `util.format()`). - * - * ```js - * const count = 5; - * console.log('count: %d', count); - * // Prints: count: 5, to stdout - * console.log('count:', count); - * // Prints: count: 5, to stdout - * ``` - * - * See `util.format()` for more information. - * @since v0.1.100 - */ - log(message?: any, ...optionalParams: any[]): void; - /** - * Try to construct a table with the columns of the properties of `tabularData`(or use `properties`) and rows of `tabularData` and log it. Falls back to just - * logging the argument if it can't be parsed as tabular. - * - * ```js - * // These can't be parsed as tabular data - * console.table(Symbol()); - * // Symbol() - * - * console.table(undefined); - * // undefined - * - * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]); - * // ┌─────────┬─────┬─────┐ - * // │ (index) │ a │ b │ - * // ├─────────┼─────┼─────┤ - * // │ 0 │ 1 │ 'Y' │ - * // │ 1 │ 'Z' │ 2 │ - * // └─────────┴─────┴─────┘ - * - * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']); - * // ┌─────────┬─────┐ - * // │ (index) │ a │ - * // ├─────────┼─────┤ - * // │ 0 │ 1 │ - * // │ 1 │ 'Z' │ - * // └─────────┴─────┘ - * ``` - * @since v10.0.0 - * @param properties Alternate properties for constructing the table. - */ - table(tabularData: any, properties?: readonly string[]): void; - /** - * Starts a timer that can be used to compute the duration of an operation. Timers - * are identified by a unique `label`. Use the same `label` when calling {@link timeEnd} to stop the timer and output the elapsed time in - * suitable time units to `stdout`. For example, if the elapsed - * time is 3869ms, `console.timeEnd()` displays "3.869s". - * @since v0.1.104 - * @param [label='default'] - */ - time(label?: string): void; - /** - * Stops a timer that was previously started by calling {@link time} and - * prints the result to `stdout`: - * - * ```js - * console.time('bunch-of-stuff'); - * // Do a bunch of stuff. - * console.timeEnd('bunch-of-stuff'); - * // Prints: bunch-of-stuff: 225.438ms - * ``` - * @since v0.1.104 - * @param [label='default'] - */ - timeEnd(label?: string): void; - /** - * For a timer that was previously started by calling {@link time}, prints - * the elapsed time and other `data` arguments to `stdout`: - * - * ```js - * console.time('process'); - * const value = expensiveProcess1(); // Returns 42 - * console.timeLog('process', value); - * // Prints "process: 365.227ms 42". - * doExpensiveProcess2(value); - * console.timeEnd('process'); - * ``` - * @since v10.7.0 - * @param [label='default'] - */ - timeLog(label?: string, ...data: any[]): void; - /** - * Prints to `stderr` the string `'Trace: '`, followed by the `util.format()` formatted message and stack trace to the current position in the code. - * - * ```js - * console.trace('Show me'); - * // Prints: (stack trace will vary based on where trace is called) - * // Trace: Show me - * // at repl:2:9 - * // at REPLServer.defaultEval (repl.js:248:27) - * // at bound (domain.js:287:14) - * // at REPLServer.runBound [as eval] (domain.js:300:12) - * // at REPLServer. (repl.js:412:12) - * // at emitOne (events.js:82:20) - * // at REPLServer.emit (events.js:169:7) - * // at REPLServer.Interface._onLine (readline.js:210:10) - * // at REPLServer.Interface._line (readline.js:549:8) - * // at REPLServer.Interface._ttyWrite (readline.js:826:14) - * ``` - * @since v0.1.104 - */ - trace(message?: any, ...optionalParams: any[]): void; - /** - * The `console.warn()` function is an alias for {@link error}. - * @since v0.1.100 - */ - warn(message?: any, ...optionalParams: any[]): void; - // --- Inspector mode only --- - /** - * This method does not display anything unless used in the inspector. - * Starts a JavaScript CPU profile with an optional label. - */ - profile(label?: string): void; - /** - * This method does not display anything unless used in the inspector. - * Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector. - */ - profileEnd(label?: string): void; - /** - * This method does not display anything unless used in the inspector. - * Adds an event with the label `label` to the Timeline panel of the inspector. - */ - timeStamp(label?: string): void; - } - /** - * The `console` module provides a simple debugging console that is similar to the - * JavaScript console mechanism provided by web browsers. - * - * The module exports two specific components: - * - * * A `Console` class with methods such as `console.log()`, `console.error()` and`console.warn()` that can be used to write to any Node.js stream. - * * A global `console` instance configured to write to `process.stdout` and `process.stderr`. The global `console` can be used without calling`require('console')`. - * - * _**Warning**_: The global console object's methods are neither consistently - * synchronous like the browser APIs they resemble, nor are they consistently - * asynchronous like all other Node.js streams. See the `note on process I/O` for - * more information. - * - * Example using the global `console`: - * - * ```js - * console.log('hello world'); - * // Prints: hello world, to stdout - * console.log('hello %s', 'world'); - * // Prints: hello world, to stdout - * console.error(new Error('Whoops, something bad happened')); - * // Prints error message and stack trace to stderr: - * // Error: Whoops, something bad happened - * // at [eval]:5:15 - * // at Script.runInThisContext (node:vm:132:18) - * // at Object.runInThisContext (node:vm:309:38) - * // at node:internal/process/execution:77:19 - * // at [eval]-wrapper:6:22 - * // at evalScript (node:internal/process/execution:76:60) - * // at node:internal/main/eval_string:23:3 - * - * const name = 'Will Robinson'; - * console.warn(`Danger ${name}! Danger!`); - * // Prints: Danger Will Robinson! Danger!, to stderr - * ``` - * - * Example using the `Console` class: - * - * ```js - * const out = getStreamSomehow(); - * const err = getStreamSomehow(); - * const myConsole = new console.Console(out, err); - * - * myConsole.log('hello world'); - * // Prints: hello world, to out - * myConsole.log('hello %s', 'world'); - * // Prints: hello world, to out - * myConsole.error(new Error('Whoops, something bad happened')); - * // Prints: [Error: Whoops, something bad happened], to err - * - * const name = 'Will Robinson'; - * myConsole.warn(`Danger ${name}! Danger!`); - * // Prints: Danger Will Robinson! Danger!, to err - * ``` - * @see [source](https://github.com/nodejs/node/blob/v16.4.2/lib/console.js) - */ - namespace console { - interface ConsoleConstructorOptions { - stdout: NodeJS.WritableStream; - stderr?: NodeJS.WritableStream | undefined; - ignoreErrors?: boolean | undefined; - colorMode?: boolean | "auto" | undefined; - inspectOptions?: InspectOptions | undefined; - /** - * Set group indentation - * @default 2 - */ - groupIndentation?: number | undefined; - } - interface ConsoleConstructor { - prototype: Console; - new(stdout: NodeJS.WritableStream, stderr?: NodeJS.WritableStream, ignoreErrors?: boolean): Console; - new(options: ConsoleConstructorOptions): Console; - } - } - var console: Console; - } - export = globalThis.console; -} diff --git a/node_modules/@types/node/ts4.8/constants.d.ts b/node_modules/@types/node/ts4.8/constants.d.ts deleted file mode 100644 index c3ac2b826436020bc945c03bb85c9a9479245f2f..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/constants.d.ts +++ /dev/null @@ -1,19 +0,0 @@ -/** @deprecated since v6.3.0 - use constants property exposed by the relevant module instead. */ -declare module "constants" { - import { constants as osConstants, SignalConstants } from "node:os"; - import { constants as cryptoConstants } from "node:crypto"; - import { constants as fsConstants } from "node:fs"; - - const exp: - & typeof osConstants.errno - & typeof osConstants.priority - & SignalConstants - & typeof cryptoConstants - & typeof fsConstants; - export = exp; -} - -declare module "node:constants" { - import constants = require("constants"); - export = constants; -} diff --git a/node_modules/@types/node/ts4.8/crypto.d.ts b/node_modules/@types/node/ts4.8/crypto.d.ts deleted file mode 100644 index f392681174edd31c0e7c6317cc0c03fedd948a72..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/crypto.d.ts +++ /dev/null @@ -1,4478 +0,0 @@ -/** - * The `node:crypto` module provides cryptographic functionality that includes a - * set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify - * functions. - * - * ```js - * const { createHmac } = await import('node:crypto'); - * - * const secret = 'abcdefg'; - * const hash = createHmac('sha256', secret) - * .update('I love cupcakes') - * .digest('hex'); - * console.log(hash); - * // Prints: - * // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e - * ``` - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/crypto.js) - */ -declare module "crypto" { - import * as stream from "node:stream"; - import { PeerCertificate } from "node:tls"; - /** - * SPKAC is a Certificate Signing Request mechanism originally implemented by - * Netscape and was specified formally as part of HTML5's `keygen` element. - * - * `` is deprecated since [HTML 5.2](https://www.w3.org/TR/html52/changes.html#features-removed) and new projects - * should not use this element anymore. - * - * The `node:crypto` module provides the `Certificate` class for working with SPKAC - * data. The most common usage is handling output generated by the HTML5`` element. Node.js uses [OpenSSL's SPKAC - * implementation](https://www.openssl.org/docs/man3.0/man1/openssl-spkac.html) internally. - * @since v0.11.8 - */ - class Certificate { - /** - * ```js - * const { Certificate } = await import('node:crypto'); - * const spkac = getSpkacSomehow(); - * const challenge = Certificate.exportChallenge(spkac); - * console.log(challenge.toString('utf8')); - * // Prints: the challenge as a UTF8 string - * ``` - * @since v9.0.0 - * @param encoding The `encoding` of the `spkac` string. - * @return The challenge component of the `spkac` data structure, which includes a public key and a challenge. - */ - static exportChallenge(spkac: BinaryLike): Buffer; - /** - * ```js - * const { Certificate } = await import('node:crypto'); - * const spkac = getSpkacSomehow(); - * const publicKey = Certificate.exportPublicKey(spkac); - * console.log(publicKey); - * // Prints: the public key as - * ``` - * @since v9.0.0 - * @param encoding The `encoding` of the `spkac` string. - * @return The public key component of the `spkac` data structure, which includes a public key and a challenge. - */ - static exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer; - /** - * ```js - * import { Buffer } from 'node:buffer'; - * const { Certificate } = await import('node:crypto'); - * - * const spkac = getSpkacSomehow(); - * console.log(Certificate.verifySpkac(Buffer.from(spkac))); - * // Prints: true or false - * ``` - * @since v9.0.0 - * @param encoding The `encoding` of the `spkac` string. - * @return `true` if the given `spkac` data structure is valid, `false` otherwise. - */ - static verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; - /** - * @deprecated - * @param spkac - * @returns The challenge component of the `spkac` data structure, - * which includes a public key and a challenge. - */ - exportChallenge(spkac: BinaryLike): Buffer; - /** - * @deprecated - * @param spkac - * @param encoding The encoding of the spkac string. - * @returns The public key component of the `spkac` data structure, - * which includes a public key and a challenge. - */ - exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer; - /** - * @deprecated - * @param spkac - * @returns `true` if the given `spkac` data structure is valid, - * `false` otherwise. - */ - verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; - } - namespace constants { - // https://nodejs.org/dist/latest-v20.x/docs/api/crypto.html#crypto-constants - const OPENSSL_VERSION_NUMBER: number; - /** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */ - const SSL_OP_ALL: number; - /** Instructs OpenSSL to allow a non-[EC]DHE-based key exchange mode for TLS v1.3 */ - const SSL_OP_ALLOW_NO_DHE_KEX: number; - /** Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ - const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; - /** Attempts to use the server's preferences instead of the client's when selecting a cipher. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ - const SSL_OP_CIPHER_SERVER_PREFERENCE: number; - /** Instructs OpenSSL to use Cisco's "speshul" version of DTLS_BAD_VER. */ - const SSL_OP_CISCO_ANYCONNECT: number; - /** Instructs OpenSSL to turn on cookie exchange. */ - const SSL_OP_COOKIE_EXCHANGE: number; - /** Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft. */ - const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; - /** Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. */ - const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; - /** Allows initial connection to servers that do not support RI. */ - const SSL_OP_LEGACY_SERVER_CONNECT: number; - /** Instructs OpenSSL to disable support for SSL/TLS compression. */ - const SSL_OP_NO_COMPRESSION: number; - /** Instructs OpenSSL to disable encrypt-then-MAC. */ - const SSL_OP_NO_ENCRYPT_THEN_MAC: number; - const SSL_OP_NO_QUERY_MTU: number; - /** Instructs OpenSSL to disable renegotiation. */ - const SSL_OP_NO_RENEGOTIATION: number; - /** Instructs OpenSSL to always start a new session when performing renegotiation. */ - const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; - /** Instructs OpenSSL to turn off SSL v2 */ - const SSL_OP_NO_SSLv2: number; - /** Instructs OpenSSL to turn off SSL v3 */ - const SSL_OP_NO_SSLv3: number; - /** Instructs OpenSSL to disable use of RFC4507bis tickets. */ - const SSL_OP_NO_TICKET: number; - /** Instructs OpenSSL to turn off TLS v1 */ - const SSL_OP_NO_TLSv1: number; - /** Instructs OpenSSL to turn off TLS v1.1 */ - const SSL_OP_NO_TLSv1_1: number; - /** Instructs OpenSSL to turn off TLS v1.2 */ - const SSL_OP_NO_TLSv1_2: number; - /** Instructs OpenSSL to turn off TLS v1.3 */ - const SSL_OP_NO_TLSv1_3: number; - /** Instructs OpenSSL server to prioritize ChaCha20-Poly1305 when the client does. This option has no effect if `SSL_OP_CIPHER_SERVER_PREFERENCE` is not enabled. */ - const SSL_OP_PRIORITIZE_CHACHA: number; - /** Instructs OpenSSL to disable version rollback attack detection. */ - const SSL_OP_TLS_ROLLBACK_BUG: number; - const ENGINE_METHOD_RSA: number; - const ENGINE_METHOD_DSA: number; - const ENGINE_METHOD_DH: number; - const ENGINE_METHOD_RAND: number; - const ENGINE_METHOD_EC: number; - const ENGINE_METHOD_CIPHERS: number; - const ENGINE_METHOD_DIGESTS: number; - const ENGINE_METHOD_PKEY_METHS: number; - const ENGINE_METHOD_PKEY_ASN1_METHS: number; - const ENGINE_METHOD_ALL: number; - const ENGINE_METHOD_NONE: number; - const DH_CHECK_P_NOT_SAFE_PRIME: number; - const DH_CHECK_P_NOT_PRIME: number; - const DH_UNABLE_TO_CHECK_GENERATOR: number; - const DH_NOT_SUITABLE_GENERATOR: number; - const RSA_PKCS1_PADDING: number; - const RSA_SSLV23_PADDING: number; - const RSA_NO_PADDING: number; - const RSA_PKCS1_OAEP_PADDING: number; - const RSA_X931_PADDING: number; - const RSA_PKCS1_PSS_PADDING: number; - /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size when signing or verifying. */ - const RSA_PSS_SALTLEN_DIGEST: number; - /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data. */ - const RSA_PSS_SALTLEN_MAX_SIGN: number; - /** Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature. */ - const RSA_PSS_SALTLEN_AUTO: number; - const POINT_CONVERSION_COMPRESSED: number; - const POINT_CONVERSION_UNCOMPRESSED: number; - const POINT_CONVERSION_HYBRID: number; - /** Specifies the built-in default cipher list used by Node.js (colon-separated values). */ - const defaultCoreCipherList: string; - /** Specifies the active default cipher list used by the current Node.js process (colon-separated values). */ - const defaultCipherList: string; - } - interface HashOptions extends stream.TransformOptions { - /** - * For XOF hash functions such as `shake256`, the - * outputLength option can be used to specify the desired output length in bytes. - */ - outputLength?: number | undefined; - } - /** @deprecated since v10.0.0 */ - const fips: boolean; - /** - * Creates and returns a `Hash` object that can be used to generate hash digests - * using the given `algorithm`. Optional `options` argument controls stream - * behavior. For XOF hash functions such as `'shake256'`, the `outputLength` option - * can be used to specify the desired output length in bytes. - * - * The `algorithm` is dependent on the available algorithms supported by the - * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. - * On recent releases of OpenSSL, `openssl list -digest-algorithms` will - * display the available digest algorithms. - * - * Example: generating the sha256 sum of a file - * - * ```js - * import { - * createReadStream, - * } from 'node:fs'; - * import { argv } from 'node:process'; - * const { - * createHash, - * } = await import('node:crypto'); - * - * const filename = argv[2]; - * - * const hash = createHash('sha256'); - * - * const input = createReadStream(filename); - * input.on('readable', () => { - * // Only one element is going to be produced by the - * // hash stream. - * const data = input.read(); - * if (data) - * hash.update(data); - * else { - * console.log(`${hash.digest('hex')} ${filename}`); - * } - * }); - * ``` - * @since v0.1.92 - * @param options `stream.transform` options - */ - function createHash(algorithm: string, options?: HashOptions): Hash; - /** - * Creates and returns an `Hmac` object that uses the given `algorithm` and `key`. - * Optional `options` argument controls stream behavior. - * - * The `algorithm` is dependent on the available algorithms supported by the - * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. - * On recent releases of OpenSSL, `openssl list -digest-algorithms` will - * display the available digest algorithms. - * - * The `key` is the HMAC key used to generate the cryptographic HMAC hash. If it is - * a `KeyObject`, its type must be `secret`. If it is a string, please consider `caveats when using strings as inputs to cryptographic APIs`. If it was - * obtained from a cryptographically secure source of entropy, such as {@link randomBytes} or {@link generateKey}, its length should not - * exceed the block size of `algorithm` (e.g., 512 bits for SHA-256). - * - * Example: generating the sha256 HMAC of a file - * - * ```js - * import { - * createReadStream, - * } from 'node:fs'; - * import { argv } from 'node:process'; - * const { - * createHmac, - * } = await import('node:crypto'); - * - * const filename = argv[2]; - * - * const hmac = createHmac('sha256', 'a secret'); - * - * const input = createReadStream(filename); - * input.on('readable', () => { - * // Only one element is going to be produced by the - * // hash stream. - * const data = input.read(); - * if (data) - * hmac.update(data); - * else { - * console.log(`${hmac.digest('hex')} ${filename}`); - * } - * }); - * ``` - * @since v0.1.94 - * @param options `stream.transform` options - */ - function createHmac(algorithm: string, key: BinaryLike | KeyObject, options?: stream.TransformOptions): Hmac; - // https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings - type BinaryToTextEncoding = "base64" | "base64url" | "hex" | "binary"; - type CharacterEncoding = "utf8" | "utf-8" | "utf16le" | "utf-16le" | "latin1"; - type LegacyCharacterEncoding = "ascii" | "binary" | "ucs2" | "ucs-2"; - type Encoding = BinaryToTextEncoding | CharacterEncoding | LegacyCharacterEncoding; - type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid"; - /** - * The `Hash` class is a utility for creating hash digests of data. It can be - * used in one of two ways: - * - * * As a `stream` that is both readable and writable, where data is written - * to produce a computed hash digest on the readable side, or - * * Using the `hash.update()` and `hash.digest()` methods to produce the - * computed hash. - * - * The {@link createHash} method is used to create `Hash` instances. `Hash`objects are not to be created directly using the `new` keyword. - * - * Example: Using `Hash` objects as streams: - * - * ```js - * const { - * createHash, - * } = await import('node:crypto'); - * - * const hash = createHash('sha256'); - * - * hash.on('readable', () => { - * // Only one element is going to be produced by the - * // hash stream. - * const data = hash.read(); - * if (data) { - * console.log(data.toString('hex')); - * // Prints: - * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 - * } - * }); - * - * hash.write('some data to hash'); - * hash.end(); - * ``` - * - * Example: Using `Hash` and piped streams: - * - * ```js - * import { createReadStream } from 'node:fs'; - * import { stdout } from 'node:process'; - * const { createHash } = await import('node:crypto'); - * - * const hash = createHash('sha256'); - * - * const input = createReadStream('test.js'); - * input.pipe(hash).setEncoding('hex').pipe(stdout); - * ``` - * - * Example: Using the `hash.update()` and `hash.digest()` methods: - * - * ```js - * const { - * createHash, - * } = await import('node:crypto'); - * - * const hash = createHash('sha256'); - * - * hash.update('some data to hash'); - * console.log(hash.digest('hex')); - * // Prints: - * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 - * ``` - * @since v0.1.92 - */ - class Hash extends stream.Transform { - private constructor(); - /** - * Creates a new `Hash` object that contains a deep copy of the internal state - * of the current `Hash` object. - * - * The optional `options` argument controls stream behavior. For XOF hash - * functions such as `'shake256'`, the `outputLength` option can be used to - * specify the desired output length in bytes. - * - * An error is thrown when an attempt is made to copy the `Hash` object after - * its `hash.digest()` method has been called. - * - * ```js - * // Calculate a rolling hash. - * const { - * createHash, - * } = await import('node:crypto'); - * - * const hash = createHash('sha256'); - * - * hash.update('one'); - * console.log(hash.copy().digest('hex')); - * - * hash.update('two'); - * console.log(hash.copy().digest('hex')); - * - * hash.update('three'); - * console.log(hash.copy().digest('hex')); - * - * // Etc. - * ``` - * @since v13.1.0 - * @param options `stream.transform` options - */ - copy(options?: HashOptions): Hash; - /** - * Updates the hash content with the given `data`, the encoding of which - * is given in `inputEncoding`. - * If `encoding` is not provided, and the `data` is a string, an - * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. - * - * This can be called many times with new data as it is streamed. - * @since v0.1.92 - * @param inputEncoding The `encoding` of the `data` string. - */ - update(data: BinaryLike): Hash; - update(data: string, inputEncoding: Encoding): Hash; - /** - * Calculates the digest of all of the data passed to be hashed (using the `hash.update()` method). - * If `encoding` is provided a string will be returned; otherwise - * a `Buffer` is returned. - * - * The `Hash` object can not be used again after `hash.digest()` method has been - * called. Multiple calls will cause an error to be thrown. - * @since v0.1.92 - * @param encoding The `encoding` of the return value. - */ - digest(): Buffer; - digest(encoding: BinaryToTextEncoding): string; - } - /** - * The `Hmac` class is a utility for creating cryptographic HMAC digests. It can - * be used in one of two ways: - * - * * As a `stream` that is both readable and writable, where data is written - * to produce a computed HMAC digest on the readable side, or - * * Using the `hmac.update()` and `hmac.digest()` methods to produce the - * computed HMAC digest. - * - * The {@link createHmac} method is used to create `Hmac` instances. `Hmac`objects are not to be created directly using the `new` keyword. - * - * Example: Using `Hmac` objects as streams: - * - * ```js - * const { - * createHmac, - * } = await import('node:crypto'); - * - * const hmac = createHmac('sha256', 'a secret'); - * - * hmac.on('readable', () => { - * // Only one element is going to be produced by the - * // hash stream. - * const data = hmac.read(); - * if (data) { - * console.log(data.toString('hex')); - * // Prints: - * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e - * } - * }); - * - * hmac.write('some data to hash'); - * hmac.end(); - * ``` - * - * Example: Using `Hmac` and piped streams: - * - * ```js - * import { createReadStream } from 'node:fs'; - * import { stdout } from 'node:process'; - * const { - * createHmac, - * } = await import('node:crypto'); - * - * const hmac = createHmac('sha256', 'a secret'); - * - * const input = createReadStream('test.js'); - * input.pipe(hmac).pipe(stdout); - * ``` - * - * Example: Using the `hmac.update()` and `hmac.digest()` methods: - * - * ```js - * const { - * createHmac, - * } = await import('node:crypto'); - * - * const hmac = createHmac('sha256', 'a secret'); - * - * hmac.update('some data to hash'); - * console.log(hmac.digest('hex')); - * // Prints: - * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e - * ``` - * @since v0.1.94 - */ - class Hmac extends stream.Transform { - private constructor(); - /** - * Updates the `Hmac` content with the given `data`, the encoding of which - * is given in `inputEncoding`. - * If `encoding` is not provided, and the `data` is a string, an - * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. - * - * This can be called many times with new data as it is streamed. - * @since v0.1.94 - * @param inputEncoding The `encoding` of the `data` string. - */ - update(data: BinaryLike): Hmac; - update(data: string, inputEncoding: Encoding): Hmac; - /** - * Calculates the HMAC digest of all of the data passed using `hmac.update()`. - * If `encoding` is - * provided a string is returned; otherwise a `Buffer` is returned; - * - * The `Hmac` object can not be used again after `hmac.digest()` has been - * called. Multiple calls to `hmac.digest()` will result in an error being thrown. - * @since v0.1.94 - * @param encoding The `encoding` of the return value. - */ - digest(): Buffer; - digest(encoding: BinaryToTextEncoding): string; - } - type KeyObjectType = "secret" | "public" | "private"; - interface KeyExportOptions { - type: "pkcs1" | "spki" | "pkcs8" | "sec1"; - format: T; - cipher?: string | undefined; - passphrase?: string | Buffer | undefined; - } - interface JwkKeyExportOptions { - format: "jwk"; - } - interface JsonWebKey { - crv?: string | undefined; - d?: string | undefined; - dp?: string | undefined; - dq?: string | undefined; - e?: string | undefined; - k?: string | undefined; - kty?: string | undefined; - n?: string | undefined; - p?: string | undefined; - q?: string | undefined; - qi?: string | undefined; - x?: string | undefined; - y?: string | undefined; - [key: string]: unknown; - } - interface AsymmetricKeyDetails { - /** - * Key size in bits (RSA, DSA). - */ - modulusLength?: number | undefined; - /** - * Public exponent (RSA). - */ - publicExponent?: bigint | undefined; - /** - * Name of the message digest (RSA-PSS). - */ - hashAlgorithm?: string | undefined; - /** - * Name of the message digest used by MGF1 (RSA-PSS). - */ - mgf1HashAlgorithm?: string | undefined; - /** - * Minimal salt length in bytes (RSA-PSS). - */ - saltLength?: number | undefined; - /** - * Size of q in bits (DSA). - */ - divisorLength?: number | undefined; - /** - * Name of the curve (EC). - */ - namedCurve?: string | undefined; - } - /** - * Node.js uses a `KeyObject` class to represent a symmetric or asymmetric key, - * and each kind of key exposes different functions. The {@link createSecretKey}, {@link createPublicKey} and {@link createPrivateKey} methods are used to create `KeyObject`instances. `KeyObject` - * objects are not to be created directly using the `new`keyword. - * - * Most applications should consider using the new `KeyObject` API instead of - * passing keys as strings or `Buffer`s due to improved security features. - * - * `KeyObject` instances can be passed to other threads via `postMessage()`. - * The receiver obtains a cloned `KeyObject`, and the `KeyObject` does not need to - * be listed in the `transferList` argument. - * @since v11.6.0 - */ - class KeyObject { - private constructor(); - /** - * Example: Converting a `CryptoKey` instance to a `KeyObject`: - * - * ```js - * const { KeyObject } = await import('node:crypto'); - * const { subtle } = globalThis.crypto; - * - * const key = await subtle.generateKey({ - * name: 'HMAC', - * hash: 'SHA-256', - * length: 256, - * }, true, ['sign', 'verify']); - * - * const keyObject = KeyObject.from(key); - * console.log(keyObject.symmetricKeySize); - * // Prints: 32 (symmetric key size in bytes) - * ``` - * @since v15.0.0 - */ - static from(key: webcrypto.CryptoKey): KeyObject; - /** - * For asymmetric keys, this property represents the type of the key. Supported key - * types are: - * - * * `'rsa'` (OID 1.2.840.113549.1.1.1) - * * `'rsa-pss'` (OID 1.2.840.113549.1.1.10) - * * `'dsa'` (OID 1.2.840.10040.4.1) - * * `'ec'` (OID 1.2.840.10045.2.1) - * * `'x25519'` (OID 1.3.101.110) - * * `'x448'` (OID 1.3.101.111) - * * `'ed25519'` (OID 1.3.101.112) - * * `'ed448'` (OID 1.3.101.113) - * * `'dh'` (OID 1.2.840.113549.1.3.1) - * - * This property is `undefined` for unrecognized `KeyObject` types and symmetric - * keys. - * @since v11.6.0 - */ - asymmetricKeyType?: KeyType | undefined; - /** - * For asymmetric keys, this property represents the size of the embedded key in - * bytes. This property is `undefined` for symmetric keys. - */ - asymmetricKeySize?: number | undefined; - /** - * This property exists only on asymmetric keys. Depending on the type of the key, - * this object contains information about the key. None of the information obtained - * through this property can be used to uniquely identify a key or to compromise - * the security of the key. - * - * For RSA-PSS keys, if the key material contains a `RSASSA-PSS-params` sequence, - * the `hashAlgorithm`, `mgf1HashAlgorithm`, and `saltLength` properties will be - * set. - * - * Other key details might be exposed via this API using additional attributes. - * @since v15.7.0 - */ - asymmetricKeyDetails?: AsymmetricKeyDetails | undefined; - /** - * For symmetric keys, the following encoding options can be used: - * - * For public keys, the following encoding options can be used: - * - * For private keys, the following encoding options can be used: - * - * The result type depends on the selected encoding format, when PEM the - * result is a string, when DER it will be a buffer containing the data - * encoded as DER, when [JWK](https://tools.ietf.org/html/rfc7517) it will be an object. - * - * When [JWK](https://tools.ietf.org/html/rfc7517) encoding format was selected, all other encoding options are - * ignored. - * - * PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of - * the `cipher` and `format` options. The PKCS#8 `type` can be used with any`format` to encrypt any key algorithm (RSA, EC, or DH) by specifying a`cipher`. PKCS#1 and SEC1 can only be - * encrypted by specifying a `cipher`when the PEM `format` is used. For maximum compatibility, use PKCS#8 for - * encrypted private keys. Since PKCS#8 defines its own - * encryption mechanism, PEM-level encryption is not supported when encrypting - * a PKCS#8 key. See [RFC 5208](https://www.rfc-editor.org/rfc/rfc5208.txt) for PKCS#8 encryption and [RFC 1421](https://www.rfc-editor.org/rfc/rfc1421.txt) for - * PKCS#1 and SEC1 encryption. - * @since v11.6.0 - */ - export(options: KeyExportOptions<"pem">): string | Buffer; - export(options?: KeyExportOptions<"der">): Buffer; - export(options?: JwkKeyExportOptions): JsonWebKey; - /** - * Returns `true` or `false` depending on whether the keys have exactly the same - * type, value, and parameters. This method is not [constant time](https://en.wikipedia.org/wiki/Timing_attack). - * @since v17.7.0, v16.15.0 - * @param otherKeyObject A `KeyObject` with which to compare `keyObject`. - */ - equals(otherKeyObject: KeyObject): boolean; - /** - * For secret keys, this property represents the size of the key in bytes. This - * property is `undefined` for asymmetric keys. - * @since v11.6.0 - */ - symmetricKeySize?: number | undefined; - /** - * Depending on the type of this `KeyObject`, this property is either`'secret'` for secret (symmetric) keys, `'public'` for public (asymmetric) keys - * or `'private'` for private (asymmetric) keys. - * @since v11.6.0 - */ - type: KeyObjectType; - } - type CipherCCMTypes = "aes-128-ccm" | "aes-192-ccm" | "aes-256-ccm" | "chacha20-poly1305"; - type CipherGCMTypes = "aes-128-gcm" | "aes-192-gcm" | "aes-256-gcm"; - type CipherOCBTypes = "aes-128-ocb" | "aes-192-ocb" | "aes-256-ocb"; - type BinaryLike = string | NodeJS.ArrayBufferView; - type CipherKey = BinaryLike | KeyObject; - interface CipherCCMOptions extends stream.TransformOptions { - authTagLength: number; - } - interface CipherGCMOptions extends stream.TransformOptions { - authTagLength?: number | undefined; - } - interface CipherOCBOptions extends stream.TransformOptions { - authTagLength: number; - } - /** - * Creates and returns a `Cipher` object that uses the given `algorithm` and`password`. - * - * The `options` argument controls stream behavior and is optional except when a - * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the - * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication - * tag that will be returned by `getAuthTag()` and defaults to 16 bytes. - * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. - * - * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On - * recent OpenSSL releases, `openssl list -cipher-algorithms` will - * display the available cipher algorithms. - * - * The `password` is used to derive the cipher key and initialization vector (IV). - * The value must be either a `'latin1'` encoded string, a `Buffer`, a`TypedArray`, or a `DataView`. - * - * **This function is semantically insecure for all** - * **supported ciphers and fatally flawed for ciphers in counter mode (such as CTR,** - * **GCM, or CCM).** - * - * The implementation of `crypto.createCipher()` derives keys using the OpenSSL - * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man3.0/man3/EVP_BytesToKey.html) with the digest algorithm set to MD5, one - * iteration, and no salt. The lack of salt allows dictionary attacks as the same - * password always creates the same key. The low iteration count and - * non-cryptographically secure hash algorithm allow passwords to be tested very - * rapidly. - * - * In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man3.0/man3/EVP_BytesToKey.html) it is recommended that - * developers derive a key and IV on - * their own using {@link scrypt} and to use {@link createCipheriv} to create the `Cipher` object. Users should not use ciphers with counter mode - * (e.g. CTR, GCM, or CCM) in `crypto.createCipher()`. A warning is emitted when - * they are used in order to avoid the risk of IV reuse that causes - * vulnerabilities. For the case when IV is reused in GCM, see [Nonce-Disrespecting Adversaries](https://github.com/nonce-disrespect/nonce-disrespect) for details. - * @since v0.1.94 - * @deprecated Since v10.0.0 - Use {@link createCipheriv} instead. - * @param options `stream.transform` options - */ - function createCipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): CipherCCM; - /** @deprecated since v10.0.0 use `createCipheriv()` */ - function createCipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): CipherGCM; - /** @deprecated since v10.0.0 use `createCipheriv()` */ - function createCipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Cipher; - /** - * Creates and returns a `Cipher` object, with the given `algorithm`, `key` and - * initialization vector (`iv`). - * - * The `options` argument controls stream behavior and is optional except when a - * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the - * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication - * tag that will be returned by `getAuthTag()` and defaults to 16 bytes. - * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. - * - * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On - * recent OpenSSL releases, `openssl list -cipher-algorithms` will - * display the available cipher algorithms. - * - * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded - * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be - * a `KeyObject` of type `secret`. If the cipher does not need - * an initialization vector, `iv` may be `null`. - * - * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. - * - * Initialization vectors should be unpredictable and unique; ideally, they will be - * cryptographically random. They do not have to be secret: IVs are typically just - * added to ciphertext messages unencrypted. It may sound contradictory that - * something has to be unpredictable and unique, but does not have to be secret; - * remember that an attacker must not be able to predict ahead of time what a - * given IV will be. - * @since v0.1.94 - * @param options `stream.transform` options - */ - function createCipheriv( - algorithm: CipherCCMTypes, - key: CipherKey, - iv: BinaryLike, - options: CipherCCMOptions, - ): CipherCCM; - function createCipheriv( - algorithm: CipherOCBTypes, - key: CipherKey, - iv: BinaryLike, - options: CipherOCBOptions, - ): CipherOCB; - function createCipheriv( - algorithm: CipherGCMTypes, - key: CipherKey, - iv: BinaryLike, - options?: CipherGCMOptions, - ): CipherGCM; - function createCipheriv( - algorithm: string, - key: CipherKey, - iv: BinaryLike | null, - options?: stream.TransformOptions, - ): Cipher; - /** - * Instances of the `Cipher` class are used to encrypt data. The class can be - * used in one of two ways: - * - * * As a `stream` that is both readable and writable, where plain unencrypted - * data is written to produce encrypted data on the readable side, or - * * Using the `cipher.update()` and `cipher.final()` methods to produce - * the encrypted data. - * - * The {@link createCipher} or {@link createCipheriv} methods are - * used to create `Cipher` instances. `Cipher` objects are not to be created - * directly using the `new` keyword. - * - * Example: Using `Cipher` objects as streams: - * - * ```js - * const { - * scrypt, - * randomFill, - * createCipheriv, - * } = await import('node:crypto'); - * - * const algorithm = 'aes-192-cbc'; - * const password = 'Password used to generate key'; - * - * // First, we'll generate the key. The key length is dependent on the algorithm. - * // In this case for aes192, it is 24 bytes (192 bits). - * scrypt(password, 'salt', 24, (err, key) => { - * if (err) throw err; - * // Then, we'll generate a random initialization vector - * randomFill(new Uint8Array(16), (err, iv) => { - * if (err) throw err; - * - * // Once we have the key and iv, we can create and use the cipher... - * const cipher = createCipheriv(algorithm, key, iv); - * - * let encrypted = ''; - * cipher.setEncoding('hex'); - * - * cipher.on('data', (chunk) => encrypted += chunk); - * cipher.on('end', () => console.log(encrypted)); - * - * cipher.write('some clear text data'); - * cipher.end(); - * }); - * }); - * ``` - * - * Example: Using `Cipher` and piped streams: - * - * ```js - * import { - * createReadStream, - * createWriteStream, - * } from 'node:fs'; - * - * import { - * pipeline, - * } from 'node:stream'; - * - * const { - * scrypt, - * randomFill, - * createCipheriv, - * } = await import('node:crypto'); - * - * const algorithm = 'aes-192-cbc'; - * const password = 'Password used to generate key'; - * - * // First, we'll generate the key. The key length is dependent on the algorithm. - * // In this case for aes192, it is 24 bytes (192 bits). - * scrypt(password, 'salt', 24, (err, key) => { - * if (err) throw err; - * // Then, we'll generate a random initialization vector - * randomFill(new Uint8Array(16), (err, iv) => { - * if (err) throw err; - * - * const cipher = createCipheriv(algorithm, key, iv); - * - * const input = createReadStream('test.js'); - * const output = createWriteStream('test.enc'); - * - * pipeline(input, cipher, output, (err) => { - * if (err) throw err; - * }); - * }); - * }); - * ``` - * - * Example: Using the `cipher.update()` and `cipher.final()` methods: - * - * ```js - * const { - * scrypt, - * randomFill, - * createCipheriv, - * } = await import('node:crypto'); - * - * const algorithm = 'aes-192-cbc'; - * const password = 'Password used to generate key'; - * - * // First, we'll generate the key. The key length is dependent on the algorithm. - * // In this case for aes192, it is 24 bytes (192 bits). - * scrypt(password, 'salt', 24, (err, key) => { - * if (err) throw err; - * // Then, we'll generate a random initialization vector - * randomFill(new Uint8Array(16), (err, iv) => { - * if (err) throw err; - * - * const cipher = createCipheriv(algorithm, key, iv); - * - * let encrypted = cipher.update('some clear text data', 'utf8', 'hex'); - * encrypted += cipher.final('hex'); - * console.log(encrypted); - * }); - * }); - * ``` - * @since v0.1.94 - */ - class Cipher extends stream.Transform { - private constructor(); - /** - * Updates the cipher with `data`. If the `inputEncoding` argument is given, - * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`, `TypedArray`, or`DataView`. If `data` is a `Buffer`, - * `TypedArray`, or `DataView`, then`inputEncoding` is ignored. - * - * The `outputEncoding` specifies the output format of the enciphered - * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned. - * - * The `cipher.update()` method can be called multiple times with new data until `cipher.final()` is called. Calling `cipher.update()` after `cipher.final()` will result in an error being - * thrown. - * @since v0.1.94 - * @param inputEncoding The `encoding` of the data. - * @param outputEncoding The `encoding` of the return value. - */ - update(data: BinaryLike): Buffer; - update(data: string, inputEncoding: Encoding): Buffer; - update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; - update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; - /** - * Once the `cipher.final()` method has been called, the `Cipher` object can no - * longer be used to encrypt data. Attempts to call `cipher.final()` more than - * once will result in an error being thrown. - * @since v0.1.94 - * @param outputEncoding The `encoding` of the return value. - * @return Any remaining enciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. - */ - final(): Buffer; - final(outputEncoding: BufferEncoding): string; - /** - * When using block encryption algorithms, the `Cipher` class will automatically - * add padding to the input data to the appropriate block size. To disable the - * default padding call `cipher.setAutoPadding(false)`. - * - * When `autoPadding` is `false`, the length of the entire input data must be a - * multiple of the cipher's block size or `cipher.final()` will throw an error. - * Disabling automatic padding is useful for non-standard padding, for instance - * using `0x0` instead of PKCS padding. - * - * The `cipher.setAutoPadding()` method must be called before `cipher.final()`. - * @since v0.7.1 - * @param [autoPadding=true] - * @return for method chaining. - */ - setAutoPadding(autoPadding?: boolean): this; - } - interface CipherCCM extends Cipher { - setAAD( - buffer: NodeJS.ArrayBufferView, - options: { - plaintextLength: number; - }, - ): this; - getAuthTag(): Buffer; - } - interface CipherGCM extends Cipher { - setAAD( - buffer: NodeJS.ArrayBufferView, - options?: { - plaintextLength: number; - }, - ): this; - getAuthTag(): Buffer; - } - interface CipherOCB extends Cipher { - setAAD( - buffer: NodeJS.ArrayBufferView, - options?: { - plaintextLength: number; - }, - ): this; - getAuthTag(): Buffer; - } - /** - * Creates and returns a `Decipher` object that uses the given `algorithm` and`password` (key). - * - * The `options` argument controls stream behavior and is optional except when a - * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the - * authentication tag in bytes, see `CCM mode`. - * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. - * - * **This function is semantically insecure for all** - * **supported ciphers and fatally flawed for ciphers in counter mode (such as CTR,** - * **GCM, or CCM).** - * - * The implementation of `crypto.createDecipher()` derives keys using the OpenSSL - * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man3.0/man3/EVP_BytesToKey.html) with the digest algorithm set to MD5, one - * iteration, and no salt. The lack of salt allows dictionary attacks as the same - * password always creates the same key. The low iteration count and - * non-cryptographically secure hash algorithm allow passwords to be tested very - * rapidly. - * - * In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man3.0/man3/EVP_BytesToKey.html) it is recommended that - * developers derive a key and IV on - * their own using {@link scrypt} and to use {@link createDecipheriv} to create the `Decipher` object. - * @since v0.1.94 - * @deprecated Since v10.0.0 - Use {@link createDecipheriv} instead. - * @param options `stream.transform` options - */ - function createDecipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): DecipherCCM; - /** @deprecated since v10.0.0 use `createDecipheriv()` */ - function createDecipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): DecipherGCM; - /** @deprecated since v10.0.0 use `createDecipheriv()` */ - function createDecipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Decipher; - /** - * Creates and returns a `Decipher` object that uses the given `algorithm`, `key`and initialization vector (`iv`). - * - * The `options` argument controls stream behavior and is optional except when a - * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the - * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to restrict accepted authentication tags - * to those with the specified length. - * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. - * - * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On - * recent OpenSSL releases, `openssl list -cipher-algorithms` will - * display the available cipher algorithms. - * - * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded - * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be - * a `KeyObject` of type `secret`. If the cipher does not need - * an initialization vector, `iv` may be `null`. - * - * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. - * - * Initialization vectors should be unpredictable and unique; ideally, they will be - * cryptographically random. They do not have to be secret: IVs are typically just - * added to ciphertext messages unencrypted. It may sound contradictory that - * something has to be unpredictable and unique, but does not have to be secret; - * remember that an attacker must not be able to predict ahead of time what a given - * IV will be. - * @since v0.1.94 - * @param options `stream.transform` options - */ - function createDecipheriv( - algorithm: CipherCCMTypes, - key: CipherKey, - iv: BinaryLike, - options: CipherCCMOptions, - ): DecipherCCM; - function createDecipheriv( - algorithm: CipherOCBTypes, - key: CipherKey, - iv: BinaryLike, - options: CipherOCBOptions, - ): DecipherOCB; - function createDecipheriv( - algorithm: CipherGCMTypes, - key: CipherKey, - iv: BinaryLike, - options?: CipherGCMOptions, - ): DecipherGCM; - function createDecipheriv( - algorithm: string, - key: CipherKey, - iv: BinaryLike | null, - options?: stream.TransformOptions, - ): Decipher; - /** - * Instances of the `Decipher` class are used to decrypt data. The class can be - * used in one of two ways: - * - * * As a `stream` that is both readable and writable, where plain encrypted - * data is written to produce unencrypted data on the readable side, or - * * Using the `decipher.update()` and `decipher.final()` methods to - * produce the unencrypted data. - * - * The {@link createDecipher} or {@link createDecipheriv} methods are - * used to create `Decipher` instances. `Decipher` objects are not to be created - * directly using the `new` keyword. - * - * Example: Using `Decipher` objects as streams: - * - * ```js - * import { Buffer } from 'node:buffer'; - * const { - * scryptSync, - * createDecipheriv, - * } = await import('node:crypto'); - * - * const algorithm = 'aes-192-cbc'; - * const password = 'Password used to generate key'; - * // Key length is dependent on the algorithm. In this case for aes192, it is - * // 24 bytes (192 bits). - * // Use the async `crypto.scrypt()` instead. - * const key = scryptSync(password, 'salt', 24); - * // The IV is usually passed along with the ciphertext. - * const iv = Buffer.alloc(16, 0); // Initialization vector. - * - * const decipher = createDecipheriv(algorithm, key, iv); - * - * let decrypted = ''; - * decipher.on('readable', () => { - * let chunk; - * while (null !== (chunk = decipher.read())) { - * decrypted += chunk.toString('utf8'); - * } - * }); - * decipher.on('end', () => { - * console.log(decrypted); - * // Prints: some clear text data - * }); - * - * // Encrypted with same algorithm, key and iv. - * const encrypted = - * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; - * decipher.write(encrypted, 'hex'); - * decipher.end(); - * ``` - * - * Example: Using `Decipher` and piped streams: - * - * ```js - * import { - * createReadStream, - * createWriteStream, - * } from 'node:fs'; - * import { Buffer } from 'node:buffer'; - * const { - * scryptSync, - * createDecipheriv, - * } = await import('node:crypto'); - * - * const algorithm = 'aes-192-cbc'; - * const password = 'Password used to generate key'; - * // Use the async `crypto.scrypt()` instead. - * const key = scryptSync(password, 'salt', 24); - * // The IV is usually passed along with the ciphertext. - * const iv = Buffer.alloc(16, 0); // Initialization vector. - * - * const decipher = createDecipheriv(algorithm, key, iv); - * - * const input = createReadStream('test.enc'); - * const output = createWriteStream('test.js'); - * - * input.pipe(decipher).pipe(output); - * ``` - * - * Example: Using the `decipher.update()` and `decipher.final()` methods: - * - * ```js - * import { Buffer } from 'node:buffer'; - * const { - * scryptSync, - * createDecipheriv, - * } = await import('node:crypto'); - * - * const algorithm = 'aes-192-cbc'; - * const password = 'Password used to generate key'; - * // Use the async `crypto.scrypt()` instead. - * const key = scryptSync(password, 'salt', 24); - * // The IV is usually passed along with the ciphertext. - * const iv = Buffer.alloc(16, 0); // Initialization vector. - * - * const decipher = createDecipheriv(algorithm, key, iv); - * - * // Encrypted using same algorithm, key and iv. - * const encrypted = - * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; - * let decrypted = decipher.update(encrypted, 'hex', 'utf8'); - * decrypted += decipher.final('utf8'); - * console.log(decrypted); - * // Prints: some clear text data - * ``` - * @since v0.1.94 - */ - class Decipher extends stream.Transform { - private constructor(); - /** - * Updates the decipher with `data`. If the `inputEncoding` argument is given, - * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`. If `data` is a `Buffer` then `inputEncoding` is - * ignored. - * - * The `outputEncoding` specifies the output format of the enciphered - * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned. - * - * The `decipher.update()` method can be called multiple times with new data until `decipher.final()` is called. Calling `decipher.update()` after `decipher.final()` will result in an error - * being thrown. - * @since v0.1.94 - * @param inputEncoding The `encoding` of the `data` string. - * @param outputEncoding The `encoding` of the return value. - */ - update(data: NodeJS.ArrayBufferView): Buffer; - update(data: string, inputEncoding: Encoding): Buffer; - update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; - update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; - /** - * Once the `decipher.final()` method has been called, the `Decipher` object can - * no longer be used to decrypt data. Attempts to call `decipher.final()` more - * than once will result in an error being thrown. - * @since v0.1.94 - * @param outputEncoding The `encoding` of the return value. - * @return Any remaining deciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. - */ - final(): Buffer; - final(outputEncoding: BufferEncoding): string; - /** - * When data has been encrypted without standard block padding, calling`decipher.setAutoPadding(false)` will disable automatic padding to prevent `decipher.final()` from checking for and - * removing padding. - * - * Turning auto padding off will only work if the input data's length is a - * multiple of the ciphers block size. - * - * The `decipher.setAutoPadding()` method must be called before `decipher.final()`. - * @since v0.7.1 - * @param [autoPadding=true] - * @return for method chaining. - */ - setAutoPadding(auto_padding?: boolean): this; - } - interface DecipherCCM extends Decipher { - setAuthTag(buffer: NodeJS.ArrayBufferView): this; - setAAD( - buffer: NodeJS.ArrayBufferView, - options: { - plaintextLength: number; - }, - ): this; - } - interface DecipherGCM extends Decipher { - setAuthTag(buffer: NodeJS.ArrayBufferView): this; - setAAD( - buffer: NodeJS.ArrayBufferView, - options?: { - plaintextLength: number; - }, - ): this; - } - interface DecipherOCB extends Decipher { - setAuthTag(buffer: NodeJS.ArrayBufferView): this; - setAAD( - buffer: NodeJS.ArrayBufferView, - options?: { - plaintextLength: number; - }, - ): this; - } - interface PrivateKeyInput { - key: string | Buffer; - format?: KeyFormat | undefined; - type?: "pkcs1" | "pkcs8" | "sec1" | undefined; - passphrase?: string | Buffer | undefined; - encoding?: string | undefined; - } - interface PublicKeyInput { - key: string | Buffer; - format?: KeyFormat | undefined; - type?: "pkcs1" | "spki" | undefined; - encoding?: string | undefined; - } - /** - * Asynchronously generates a new random secret key of the given `length`. The`type` will determine which validations will be performed on the `length`. - * - * ```js - * const { - * generateKey, - * } = await import('node:crypto'); - * - * generateKey('hmac', { length: 512 }, (err, key) => { - * if (err) throw err; - * console.log(key.export().toString('hex')); // 46e..........620 - * }); - * ``` - * - * The size of a generated HMAC key should not exceed the block size of the - * underlying hash function. See {@link createHmac} for more information. - * @since v15.0.0 - * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. - */ - function generateKey( - type: "hmac" | "aes", - options: { - length: number; - }, - callback: (err: Error | null, key: KeyObject) => void, - ): void; - /** - * Synchronously generates a new random secret key of the given `length`. The`type` will determine which validations will be performed on the `length`. - * - * ```js - * const { - * generateKeySync, - * } = await import('node:crypto'); - * - * const key = generateKeySync('hmac', { length: 512 }); - * console.log(key.export().toString('hex')); // e89..........41e - * ``` - * - * The size of a generated HMAC key should not exceed the block size of the - * underlying hash function. See {@link createHmac} for more information. - * @since v15.0.0 - * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. - */ - function generateKeySync( - type: "hmac" | "aes", - options: { - length: number; - }, - ): KeyObject; - interface JsonWebKeyInput { - key: JsonWebKey; - format: "jwk"; - } - /** - * Creates and returns a new key object containing a private key. If `key` is a - * string or `Buffer`, `format` is assumed to be `'pem'`; otherwise, `key`must be an object with the properties described above. - * - * If the private key is encrypted, a `passphrase` must be specified. The length - * of the passphrase is limited to 1024 bytes. - * @since v11.6.0 - */ - function createPrivateKey(key: PrivateKeyInput | string | Buffer | JsonWebKeyInput): KeyObject; - /** - * Creates and returns a new key object containing a public key. If `key` is a - * string or `Buffer`, `format` is assumed to be `'pem'`; if `key` is a `KeyObject`with type `'private'`, the public key is derived from the given private key; - * otherwise, `key` must be an object with the properties described above. - * - * If the format is `'pem'`, the `'key'` may also be an X.509 certificate. - * - * Because public keys can be derived from private keys, a private key may be - * passed instead of a public key. In that case, this function behaves as if {@link createPrivateKey} had been called, except that the type of the - * returned `KeyObject` will be `'public'` and that the private key cannot be - * extracted from the returned `KeyObject`. Similarly, if a `KeyObject` with type`'private'` is given, a new `KeyObject` with type `'public'` will be returned - * and it will be impossible to extract the private key from the returned object. - * @since v11.6.0 - */ - function createPublicKey(key: PublicKeyInput | string | Buffer | KeyObject | JsonWebKeyInput): KeyObject; - /** - * Creates and returns a new key object containing a secret key for symmetric - * encryption or `Hmac`. - * @since v11.6.0 - * @param encoding The string encoding when `key` is a string. - */ - function createSecretKey(key: NodeJS.ArrayBufferView): KeyObject; - function createSecretKey(key: string, encoding: BufferEncoding): KeyObject; - /** - * Creates and returns a `Sign` object that uses the given `algorithm`. Use {@link getHashes} to obtain the names of the available digest algorithms. - * Optional `options` argument controls the `stream.Writable` behavior. - * - * In some cases, a `Sign` instance can be created using the name of a signature - * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use - * the corresponding digest algorithm. This does not work for all signature - * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest - * algorithm names. - * @since v0.1.92 - * @param options `stream.Writable` options - */ - function createSign(algorithm: string, options?: stream.WritableOptions): Sign; - type DSAEncoding = "der" | "ieee-p1363"; - interface SigningOptions { - /** - * @see crypto.constants.RSA_PKCS1_PADDING - */ - padding?: number | undefined; - saltLength?: number | undefined; - dsaEncoding?: DSAEncoding | undefined; - } - interface SignPrivateKeyInput extends PrivateKeyInput, SigningOptions {} - interface SignKeyObjectInput extends SigningOptions { - key: KeyObject; - } - interface VerifyPublicKeyInput extends PublicKeyInput, SigningOptions {} - interface VerifyKeyObjectInput extends SigningOptions { - key: KeyObject; - } - interface VerifyJsonWebKeyInput extends JsonWebKeyInput, SigningOptions {} - type KeyLike = string | Buffer | KeyObject; - /** - * The `Sign` class is a utility for generating signatures. It can be used in one - * of two ways: - * - * * As a writable `stream`, where data to be signed is written and the `sign.sign()` method is used to generate and return the signature, or - * * Using the `sign.update()` and `sign.sign()` methods to produce the - * signature. - * - * The {@link createSign} method is used to create `Sign` instances. The - * argument is the string name of the hash function to use. `Sign` objects are not - * to be created directly using the `new` keyword. - * - * Example: Using `Sign` and `Verify` objects as streams: - * - * ```js - * const { - * generateKeyPairSync, - * createSign, - * createVerify, - * } = await import('node:crypto'); - * - * const { privateKey, publicKey } = generateKeyPairSync('ec', { - * namedCurve: 'sect239k1', - * }); - * - * const sign = createSign('SHA256'); - * sign.write('some data to sign'); - * sign.end(); - * const signature = sign.sign(privateKey, 'hex'); - * - * const verify = createVerify('SHA256'); - * verify.write('some data to sign'); - * verify.end(); - * console.log(verify.verify(publicKey, signature, 'hex')); - * // Prints: true - * ``` - * - * Example: Using the `sign.update()` and `verify.update()` methods: - * - * ```js - * const { - * generateKeyPairSync, - * createSign, - * createVerify, - * } = await import('node:crypto'); - * - * const { privateKey, publicKey } = generateKeyPairSync('rsa', { - * modulusLength: 2048, - * }); - * - * const sign = createSign('SHA256'); - * sign.update('some data to sign'); - * sign.end(); - * const signature = sign.sign(privateKey); - * - * const verify = createVerify('SHA256'); - * verify.update('some data to sign'); - * verify.end(); - * console.log(verify.verify(publicKey, signature)); - * // Prints: true - * ``` - * @since v0.1.92 - */ - class Sign extends stream.Writable { - private constructor(); - /** - * Updates the `Sign` content with the given `data`, the encoding of which - * is given in `inputEncoding`. - * If `encoding` is not provided, and the `data` is a string, an - * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. - * - * This can be called many times with new data as it is streamed. - * @since v0.1.92 - * @param inputEncoding The `encoding` of the `data` string. - */ - update(data: BinaryLike): this; - update(data: string, inputEncoding: Encoding): this; - /** - * Calculates the signature on all the data passed through using either `sign.update()` or `sign.write()`. - * - * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an - * object, the following additional properties can be passed: - * - * If `outputEncoding` is provided a string is returned; otherwise a `Buffer` is returned. - * - * The `Sign` object can not be again used after `sign.sign()` method has been - * called. Multiple calls to `sign.sign()` will result in an error being thrown. - * @since v0.1.92 - */ - sign(privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput): Buffer; - sign( - privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, - outputFormat: BinaryToTextEncoding, - ): string; - } - /** - * Creates and returns a `Verify` object that uses the given algorithm. - * Use {@link getHashes} to obtain an array of names of the available - * signing algorithms. Optional `options` argument controls the`stream.Writable` behavior. - * - * In some cases, a `Verify` instance can be created using the name of a signature - * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use - * the corresponding digest algorithm. This does not work for all signature - * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest - * algorithm names. - * @since v0.1.92 - * @param options `stream.Writable` options - */ - function createVerify(algorithm: string, options?: stream.WritableOptions): Verify; - /** - * The `Verify` class is a utility for verifying signatures. It can be used in one - * of two ways: - * - * * As a writable `stream` where written data is used to validate against the - * supplied signature, or - * * Using the `verify.update()` and `verify.verify()` methods to verify - * the signature. - * - * The {@link createVerify} method is used to create `Verify` instances.`Verify` objects are not to be created directly using the `new` keyword. - * - * See `Sign` for examples. - * @since v0.1.92 - */ - class Verify extends stream.Writable { - private constructor(); - /** - * Updates the `Verify` content with the given `data`, the encoding of which - * is given in `inputEncoding`. - * If `inputEncoding` is not provided, and the `data` is a string, an - * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. - * - * This can be called many times with new data as it is streamed. - * @since v0.1.92 - * @param inputEncoding The `encoding` of the `data` string. - */ - update(data: BinaryLike): Verify; - update(data: string, inputEncoding: Encoding): Verify; - /** - * Verifies the provided data using the given `object` and `signature`. - * - * If `object` is not a `KeyObject`, this function behaves as if`object` had been passed to {@link createPublicKey}. If it is an - * object, the following additional properties can be passed: - * - * The `signature` argument is the previously calculated signature for the data, in - * the `signatureEncoding`. - * If a `signatureEncoding` is specified, the `signature` is expected to be a - * string; otherwise `signature` is expected to be a `Buffer`,`TypedArray`, or `DataView`. - * - * The `verify` object can not be used again after `verify.verify()` has been - * called. Multiple calls to `verify.verify()` will result in an error being - * thrown. - * - * Because public keys can be derived from private keys, a private key may - * be passed instead of a public key. - * @since v0.1.92 - */ - verify( - object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, - signature: NodeJS.ArrayBufferView, - ): boolean; - verify( - object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, - signature: string, - signature_format?: BinaryToTextEncoding, - ): boolean; - } - /** - * Creates a `DiffieHellman` key exchange object using the supplied `prime` and an - * optional specific `generator`. - * - * The `generator` argument can be a number, string, or `Buffer`. If`generator` is not specified, the value `2` is used. - * - * If `primeEncoding` is specified, `prime` is expected to be a string; otherwise - * a `Buffer`, `TypedArray`, or `DataView` is expected. - * - * If `generatorEncoding` is specified, `generator` is expected to be a string; - * otherwise a number, `Buffer`, `TypedArray`, or `DataView` is expected. - * @since v0.11.12 - * @param primeEncoding The `encoding` of the `prime` string. - * @param [generator=2] - * @param generatorEncoding The `encoding` of the `generator` string. - */ - function createDiffieHellman(primeLength: number, generator?: number): DiffieHellman; - function createDiffieHellman( - prime: ArrayBuffer | NodeJS.ArrayBufferView, - generator?: number | ArrayBuffer | NodeJS.ArrayBufferView, - ): DiffieHellman; - function createDiffieHellman( - prime: ArrayBuffer | NodeJS.ArrayBufferView, - generator: string, - generatorEncoding: BinaryToTextEncoding, - ): DiffieHellman; - function createDiffieHellman( - prime: string, - primeEncoding: BinaryToTextEncoding, - generator?: number | ArrayBuffer | NodeJS.ArrayBufferView, - ): DiffieHellman; - function createDiffieHellman( - prime: string, - primeEncoding: BinaryToTextEncoding, - generator: string, - generatorEncoding: BinaryToTextEncoding, - ): DiffieHellman; - /** - * The `DiffieHellman` class is a utility for creating Diffie-Hellman key - * exchanges. - * - * Instances of the `DiffieHellman` class can be created using the {@link createDiffieHellman} function. - * - * ```js - * import assert from 'node:assert'; - * - * const { - * createDiffieHellman, - * } = await import('node:crypto'); - * - * // Generate Alice's keys... - * const alice = createDiffieHellman(2048); - * const aliceKey = alice.generateKeys(); - * - * // Generate Bob's keys... - * const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator()); - * const bobKey = bob.generateKeys(); - * - * // Exchange and generate the secret... - * const aliceSecret = alice.computeSecret(bobKey); - * const bobSecret = bob.computeSecret(aliceKey); - * - * // OK - * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); - * ``` - * @since v0.5.0 - */ - class DiffieHellman { - private constructor(); - /** - * Generates private and public Diffie-Hellman key values unless they have been - * generated or computed already, and returns - * the public key in the specified `encoding`. This key should be - * transferred to the other party. - * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. - * - * This function is a thin wrapper around [`DH_generate_key()`](https://www.openssl.org/docs/man3.0/man3/DH_generate_key.html). In particular, - * once a private key has been generated or set, calling this function only updates - * the public key but does not generate a new private key. - * @since v0.5.0 - * @param encoding The `encoding` of the return value. - */ - generateKeys(): Buffer; - generateKeys(encoding: BinaryToTextEncoding): string; - /** - * Computes the shared secret using `otherPublicKey` as the other - * party's public key and returns the computed shared secret. The supplied - * key is interpreted using the specified `inputEncoding`, and secret is - * encoded using specified `outputEncoding`. - * If the `inputEncoding` is not - * provided, `otherPublicKey` is expected to be a `Buffer`,`TypedArray`, or `DataView`. - * - * If `outputEncoding` is given a string is returned; otherwise, a `Buffer` is returned. - * @since v0.5.0 - * @param inputEncoding The `encoding` of an `otherPublicKey` string. - * @param outputEncoding The `encoding` of the return value. - */ - computeSecret(otherPublicKey: NodeJS.ArrayBufferView, inputEncoding?: null, outputEncoding?: null): Buffer; - computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding, outputEncoding?: null): Buffer; - computeSecret( - otherPublicKey: NodeJS.ArrayBufferView, - inputEncoding: null, - outputEncoding: BinaryToTextEncoding, - ): string; - computeSecret( - otherPublicKey: string, - inputEncoding: BinaryToTextEncoding, - outputEncoding: BinaryToTextEncoding, - ): string; - /** - * Returns the Diffie-Hellman prime in the specified `encoding`. - * If `encoding` is provided a string is - * returned; otherwise a `Buffer` is returned. - * @since v0.5.0 - * @param encoding The `encoding` of the return value. - */ - getPrime(): Buffer; - getPrime(encoding: BinaryToTextEncoding): string; - /** - * Returns the Diffie-Hellman generator in the specified `encoding`. - * If `encoding` is provided a string is - * returned; otherwise a `Buffer` is returned. - * @since v0.5.0 - * @param encoding The `encoding` of the return value. - */ - getGenerator(): Buffer; - getGenerator(encoding: BinaryToTextEncoding): string; - /** - * Returns the Diffie-Hellman public key in the specified `encoding`. - * If `encoding` is provided a - * string is returned; otherwise a `Buffer` is returned. - * @since v0.5.0 - * @param encoding The `encoding` of the return value. - */ - getPublicKey(): Buffer; - getPublicKey(encoding: BinaryToTextEncoding): string; - /** - * Returns the Diffie-Hellman private key in the specified `encoding`. - * If `encoding` is provided a - * string is returned; otherwise a `Buffer` is returned. - * @since v0.5.0 - * @param encoding The `encoding` of the return value. - */ - getPrivateKey(): Buffer; - getPrivateKey(encoding: BinaryToTextEncoding): string; - /** - * Sets the Diffie-Hellman public key. If the `encoding` argument is provided,`publicKey` is expected - * to be a string. If no `encoding` is provided, `publicKey` is expected - * to be a `Buffer`, `TypedArray`, or `DataView`. - * @since v0.5.0 - * @param encoding The `encoding` of the `publicKey` string. - */ - setPublicKey(publicKey: NodeJS.ArrayBufferView): void; - setPublicKey(publicKey: string, encoding: BufferEncoding): void; - /** - * Sets the Diffie-Hellman private key. If the `encoding` argument is provided,`privateKey` is expected - * to be a string. If no `encoding` is provided, `privateKey` is expected - * to be a `Buffer`, `TypedArray`, or `DataView`. - * - * This function does not automatically compute the associated public key. Either `diffieHellman.setPublicKey()` or `diffieHellman.generateKeys()` can be - * used to manually provide the public key or to automatically derive it. - * @since v0.5.0 - * @param encoding The `encoding` of the `privateKey` string. - */ - setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; - setPrivateKey(privateKey: string, encoding: BufferEncoding): void; - /** - * A bit field containing any warnings and/or errors resulting from a check - * performed during initialization of the `DiffieHellman` object. - * - * The following values are valid for this property (as defined in `node:constants` module): - * - * * `DH_CHECK_P_NOT_SAFE_PRIME` - * * `DH_CHECK_P_NOT_PRIME` - * * `DH_UNABLE_TO_CHECK_GENERATOR` - * * `DH_NOT_SUITABLE_GENERATOR` - * @since v0.11.12 - */ - verifyError: number; - } - /** - * The `DiffieHellmanGroup` class takes a well-known modp group as its argument. - * It works the same as `DiffieHellman`, except that it does not allow changing its keys after creation. - * In other words, it does not implement `setPublicKey()` or `setPrivateKey()` methods. - * - * ```js - * const { createDiffieHellmanGroup } = await import('node:crypto'); - * const dh = createDiffieHellmanGroup('modp1'); - * ``` - * The name (e.g. `'modp1'`) is taken from [RFC 2412](https://www.rfc-editor.org/rfc/rfc2412.txt) (modp1 and 2) and [RFC 3526](https://www.rfc-editor.org/rfc/rfc3526.txt): - * ```bash - * $ perl -ne 'print "$1\n" if /"(modp\d+)"/' src/node_crypto_groups.h - * modp1 # 768 bits - * modp2 # 1024 bits - * modp5 # 1536 bits - * modp14 # 2048 bits - * modp15 # etc. - * modp16 - * modp17 - * modp18 - * ``` - * @since v0.7.5 - */ - const DiffieHellmanGroup: DiffieHellmanGroupConstructor; - interface DiffieHellmanGroupConstructor { - new(name: string): DiffieHellmanGroup; - (name: string): DiffieHellmanGroup; - readonly prototype: DiffieHellmanGroup; - } - type DiffieHellmanGroup = Omit; - /** - * Creates a predefined `DiffieHellmanGroup` key exchange object. The - * supported groups are listed in the documentation for `DiffieHellmanGroup`. - * - * The returned object mimics the interface of objects created by {@link createDiffieHellman}, but will not allow changing - * the keys (with `diffieHellman.setPublicKey()`, for example). The - * advantage of using this method is that the parties do not have to - * generate nor exchange a group modulus beforehand, saving both processor - * and communication time. - * - * Example (obtaining a shared secret): - * - * ```js - * const { - * getDiffieHellman, - * } = await import('node:crypto'); - * const alice = getDiffieHellman('modp14'); - * const bob = getDiffieHellman('modp14'); - * - * alice.generateKeys(); - * bob.generateKeys(); - * - * const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); - * const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); - * - * // aliceSecret and bobSecret should be the same - * console.log(aliceSecret === bobSecret); - * ``` - * @since v0.7.5 - */ - function getDiffieHellman(groupName: string): DiffieHellmanGroup; - /** - * An alias for {@link getDiffieHellman} - * @since v0.9.3 - */ - function createDiffieHellmanGroup(name: string): DiffieHellmanGroup; - /** - * Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2) - * implementation. A selected HMAC digest algorithm specified by `digest` is - * applied to derive a key of the requested byte length (`keylen`) from the`password`, `salt` and `iterations`. - * - * The supplied `callback` function is called with two arguments: `err` and`derivedKey`. If an error occurs while deriving the key, `err` will be set; - * otherwise `err` will be `null`. By default, the successfully generated`derivedKey` will be passed to the callback as a `Buffer`. An error will be - * thrown if any of the input arguments specify invalid values or types. - * - * The `iterations` argument must be a number set as high as possible. The - * higher the number of iterations, the more secure the derived key will be, - * but will take a longer amount of time to complete. - * - * The `salt` should be as unique as possible. It is recommended that a salt is - * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. - * - * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. - * - * ```js - * const { - * pbkdf2, - * } = await import('node:crypto'); - * - * pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { - * if (err) throw err; - * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' - * }); - * ``` - * - * An array of supported digest functions can be retrieved using {@link getHashes}. - * - * This API uses libuv's threadpool, which can have surprising and - * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. - * @since v0.5.5 - */ - function pbkdf2( - password: BinaryLike, - salt: BinaryLike, - iterations: number, - keylen: number, - digest: string, - callback: (err: Error | null, derivedKey: Buffer) => void, - ): void; - /** - * Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2) - * implementation. A selected HMAC digest algorithm specified by `digest` is - * applied to derive a key of the requested byte length (`keylen`) from the`password`, `salt` and `iterations`. - * - * If an error occurs an `Error` will be thrown, otherwise the derived key will be - * returned as a `Buffer`. - * - * The `iterations` argument must be a number set as high as possible. The - * higher the number of iterations, the more secure the derived key will be, - * but will take a longer amount of time to complete. - * - * The `salt` should be as unique as possible. It is recommended that a salt is - * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. - * - * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. - * - * ```js - * const { - * pbkdf2Sync, - * } = await import('node:crypto'); - * - * const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512'); - * console.log(key.toString('hex')); // '3745e48...08d59ae' - * ``` - * - * An array of supported digest functions can be retrieved using {@link getHashes}. - * @since v0.9.3 - */ - function pbkdf2Sync( - password: BinaryLike, - salt: BinaryLike, - iterations: number, - keylen: number, - digest: string, - ): Buffer; - /** - * Generates cryptographically strong pseudorandom data. The `size` argument - * is a number indicating the number of bytes to generate. - * - * If a `callback` function is provided, the bytes are generated asynchronously - * and the `callback` function is invoked with two arguments: `err` and `buf`. - * If an error occurs, `err` will be an `Error` object; otherwise it is `null`. The`buf` argument is a `Buffer` containing the generated bytes. - * - * ```js - * // Asynchronous - * const { - * randomBytes, - * } = await import('node:crypto'); - * - * randomBytes(256, (err, buf) => { - * if (err) throw err; - * console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`); - * }); - * ``` - * - * If the `callback` function is not provided, the random bytes are generated - * synchronously and returned as a `Buffer`. An error will be thrown if - * there is a problem generating the bytes. - * - * ```js - * // Synchronous - * const { - * randomBytes, - * } = await import('node:crypto'); - * - * const buf = randomBytes(256); - * console.log( - * `${buf.length} bytes of random data: ${buf.toString('hex')}`); - * ``` - * - * The `crypto.randomBytes()` method will not complete until there is - * sufficient entropy available. - * This should normally never take longer than a few milliseconds. The only time - * when generating the random bytes may conceivably block for a longer period of - * time is right after boot, when the whole system is still low on entropy. - * - * This API uses libuv's threadpool, which can have surprising and - * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. - * - * The asynchronous version of `crypto.randomBytes()` is carried out in a single - * threadpool request. To minimize threadpool task length variation, partition - * large `randomBytes` requests when doing so as part of fulfilling a client - * request. - * @since v0.5.8 - * @param size The number of bytes to generate. The `size` must not be larger than `2**31 - 1`. - * @return if the `callback` function is not provided. - */ - function randomBytes(size: number): Buffer; - function randomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; - function pseudoRandomBytes(size: number): Buffer; - function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; - /** - * Return a random integer `n` such that `min <= n < max`. This - * implementation avoids [modulo bias](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modulo_bias). - * - * The range (`max - min`) must be less than 248. `min` and `max` must - * be [safe integers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger). - * - * If the `callback` function is not provided, the random integer is - * generated synchronously. - * - * ```js - * // Asynchronous - * const { - * randomInt, - * } = await import('node:crypto'); - * - * randomInt(3, (err, n) => { - * if (err) throw err; - * console.log(`Random number chosen from (0, 1, 2): ${n}`); - * }); - * ``` - * - * ```js - * // Synchronous - * const { - * randomInt, - * } = await import('node:crypto'); - * - * const n = randomInt(3); - * console.log(`Random number chosen from (0, 1, 2): ${n}`); - * ``` - * - * ```js - * // With `min` argument - * const { - * randomInt, - * } = await import('node:crypto'); - * - * const n = randomInt(1, 7); - * console.log(`The dice rolled: ${n}`); - * ``` - * @since v14.10.0, v12.19.0 - * @param [min=0] Start of random range (inclusive). - * @param max End of random range (exclusive). - * @param callback `function(err, n) {}`. - */ - function randomInt(max: number): number; - function randomInt(min: number, max: number): number; - function randomInt(max: number, callback: (err: Error | null, value: number) => void): void; - function randomInt(min: number, max: number, callback: (err: Error | null, value: number) => void): void; - /** - * Synchronous version of {@link randomFill}. - * - * ```js - * import { Buffer } from 'node:buffer'; - * const { randomFillSync } = await import('node:crypto'); - * - * const buf = Buffer.alloc(10); - * console.log(randomFillSync(buf).toString('hex')); - * - * randomFillSync(buf, 5); - * console.log(buf.toString('hex')); - * - * // The above is equivalent to the following: - * randomFillSync(buf, 5, 5); - * console.log(buf.toString('hex')); - * ``` - * - * Any `ArrayBuffer`, `TypedArray` or `DataView` instance may be passed as`buffer`. - * - * ```js - * import { Buffer } from 'node:buffer'; - * const { randomFillSync } = await import('node:crypto'); - * - * const a = new Uint32Array(10); - * console.log(Buffer.from(randomFillSync(a).buffer, - * a.byteOffset, a.byteLength).toString('hex')); - * - * const b = new DataView(new ArrayBuffer(10)); - * console.log(Buffer.from(randomFillSync(b).buffer, - * b.byteOffset, b.byteLength).toString('hex')); - * - * const c = new ArrayBuffer(10); - * console.log(Buffer.from(randomFillSync(c)).toString('hex')); - * ``` - * @since v7.10.0, v6.13.0 - * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. - * @param [offset=0] - * @param [size=buffer.length - offset] - * @return The object passed as `buffer` argument. - */ - function randomFillSync(buffer: T, offset?: number, size?: number): T; - /** - * This function is similar to {@link randomBytes} but requires the first - * argument to be a `Buffer` that will be filled. It also - * requires that a callback is passed in. - * - * If the `callback` function is not provided, an error will be thrown. - * - * ```js - * import { Buffer } from 'node:buffer'; - * const { randomFill } = await import('node:crypto'); - * - * const buf = Buffer.alloc(10); - * randomFill(buf, (err, buf) => { - * if (err) throw err; - * console.log(buf.toString('hex')); - * }); - * - * randomFill(buf, 5, (err, buf) => { - * if (err) throw err; - * console.log(buf.toString('hex')); - * }); - * - * // The above is equivalent to the following: - * randomFill(buf, 5, 5, (err, buf) => { - * if (err) throw err; - * console.log(buf.toString('hex')); - * }); - * ``` - * - * Any `ArrayBuffer`, `TypedArray`, or `DataView` instance may be passed as`buffer`. - * - * While this includes instances of `Float32Array` and `Float64Array`, this - * function should not be used to generate random floating-point numbers. The - * result may contain `+Infinity`, `-Infinity`, and `NaN`, and even if the array - * contains finite numbers only, they are not drawn from a uniform random - * distribution and have no meaningful lower or upper bounds. - * - * ```js - * import { Buffer } from 'node:buffer'; - * const { randomFill } = await import('node:crypto'); - * - * const a = new Uint32Array(10); - * randomFill(a, (err, buf) => { - * if (err) throw err; - * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) - * .toString('hex')); - * }); - * - * const b = new DataView(new ArrayBuffer(10)); - * randomFill(b, (err, buf) => { - * if (err) throw err; - * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) - * .toString('hex')); - * }); - * - * const c = new ArrayBuffer(10); - * randomFill(c, (err, buf) => { - * if (err) throw err; - * console.log(Buffer.from(buf).toString('hex')); - * }); - * ``` - * - * This API uses libuv's threadpool, which can have surprising and - * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. - * - * The asynchronous version of `crypto.randomFill()` is carried out in a single - * threadpool request. To minimize threadpool task length variation, partition - * large `randomFill` requests when doing so as part of fulfilling a client - * request. - * @since v7.10.0, v6.13.0 - * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. - * @param [offset=0] - * @param [size=buffer.length - offset] - * @param callback `function(err, buf) {}`. - */ - function randomFill( - buffer: T, - callback: (err: Error | null, buf: T) => void, - ): void; - function randomFill( - buffer: T, - offset: number, - callback: (err: Error | null, buf: T) => void, - ): void; - function randomFill( - buffer: T, - offset: number, - size: number, - callback: (err: Error | null, buf: T) => void, - ): void; - interface ScryptOptions { - cost?: number | undefined; - blockSize?: number | undefined; - parallelization?: number | undefined; - N?: number | undefined; - r?: number | undefined; - p?: number | undefined; - maxmem?: number | undefined; - } - /** - * Provides an asynchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based - * key derivation function that is designed to be expensive computationally and - * memory-wise in order to make brute-force attacks unrewarding. - * - * The `salt` should be as unique as possible. It is recommended that a salt is - * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. - * - * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. - * - * The `callback` function is called with two arguments: `err` and `derivedKey`.`err` is an exception object when key derivation fails, otherwise `err` is`null`. `derivedKey` is passed to the - * callback as a `Buffer`. - * - * An exception is thrown when any of the input arguments specify invalid values - * or types. - * - * ```js - * const { - * scrypt, - * } = await import('node:crypto'); - * - * // Using the factory defaults. - * scrypt('password', 'salt', 64, (err, derivedKey) => { - * if (err) throw err; - * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' - * }); - * // Using a custom N parameter. Must be a power of two. - * scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => { - * if (err) throw err; - * console.log(derivedKey.toString('hex')); // '3745e48...aa39b34' - * }); - * ``` - * @since v10.5.0 - */ - function scrypt( - password: BinaryLike, - salt: BinaryLike, - keylen: number, - callback: (err: Error | null, derivedKey: Buffer) => void, - ): void; - function scrypt( - password: BinaryLike, - salt: BinaryLike, - keylen: number, - options: ScryptOptions, - callback: (err: Error | null, derivedKey: Buffer) => void, - ): void; - /** - * Provides a synchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based - * key derivation function that is designed to be expensive computationally and - * memory-wise in order to make brute-force attacks unrewarding. - * - * The `salt` should be as unique as possible. It is recommended that a salt is - * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. - * - * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. - * - * An exception is thrown when key derivation fails, otherwise the derived key is - * returned as a `Buffer`. - * - * An exception is thrown when any of the input arguments specify invalid values - * or types. - * - * ```js - * const { - * scryptSync, - * } = await import('node:crypto'); - * // Using the factory defaults. - * - * const key1 = scryptSync('password', 'salt', 64); - * console.log(key1.toString('hex')); // '3745e48...08d59ae' - * // Using a custom N parameter. Must be a power of two. - * const key2 = scryptSync('password', 'salt', 64, { N: 1024 }); - * console.log(key2.toString('hex')); // '3745e48...aa39b34' - * ``` - * @since v10.5.0 - */ - function scryptSync(password: BinaryLike, salt: BinaryLike, keylen: number, options?: ScryptOptions): Buffer; - interface RsaPublicKey { - key: KeyLike; - padding?: number | undefined; - } - interface RsaPrivateKey { - key: KeyLike; - passphrase?: string | undefined; - /** - * @default 'sha1' - */ - oaepHash?: string | undefined; - oaepLabel?: NodeJS.TypedArray | undefined; - padding?: number | undefined; - } - /** - * Encrypts the content of `buffer` with `key` and returns a new `Buffer` with encrypted content. The returned data can be decrypted using - * the corresponding private key, for example using {@link privateDecrypt}. - * - * If `key` is not a `KeyObject`, this function behaves as if`key` had been passed to {@link createPublicKey}. If it is an - * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_OAEP_PADDING`. - * - * Because RSA public keys can be derived from private keys, a private key may - * be passed instead of a public key. - * @since v0.11.14 - */ - function publicEncrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; - /** - * Decrypts `buffer` with `key`.`buffer` was previously encrypted using - * the corresponding private key, for example using {@link privateEncrypt}. - * - * If `key` is not a `KeyObject`, this function behaves as if`key` had been passed to {@link createPublicKey}. If it is an - * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_PADDING`. - * - * Because RSA public keys can be derived from private keys, a private key may - * be passed instead of a public key. - * @since v1.1.0 - */ - function publicDecrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; - /** - * Decrypts `buffer` with `privateKey`. `buffer` was previously encrypted using - * the corresponding public key, for example using {@link publicEncrypt}. - * - * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an - * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_OAEP_PADDING`. - * @since v0.11.14 - */ - function privateDecrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; - /** - * Encrypts `buffer` with `privateKey`. The returned data can be decrypted using - * the corresponding public key, for example using {@link publicDecrypt}. - * - * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an - * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_PADDING`. - * @since v1.1.0 - */ - function privateEncrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; - /** - * ```js - * const { - * getCiphers, - * } = await import('node:crypto'); - * - * console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...] - * ``` - * @since v0.9.3 - * @return An array with the names of the supported cipher algorithms. - */ - function getCiphers(): string[]; - /** - * ```js - * const { - * getCurves, - * } = await import('node:crypto'); - * - * console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] - * ``` - * @since v2.3.0 - * @return An array with the names of the supported elliptic curves. - */ - function getCurves(): string[]; - /** - * @since v10.0.0 - * @return `1` if and only if a FIPS compliant crypto provider is currently in use, `0` otherwise. A future semver-major release may change the return type of this API to a {boolean}. - */ - function getFips(): 1 | 0; - /** - * Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build. - * Throws an error if FIPS mode is not available. - * @since v10.0.0 - * @param bool `true` to enable FIPS mode. - */ - function setFips(bool: boolean): void; - /** - * ```js - * const { - * getHashes, - * } = await import('node:crypto'); - * - * console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] - * ``` - * @since v0.9.3 - * @return An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`. Hash algorithms are also called "digest" algorithms. - */ - function getHashes(): string[]; - /** - * The `ECDH` class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH) - * key exchanges. - * - * Instances of the `ECDH` class can be created using the {@link createECDH} function. - * - * ```js - * import assert from 'node:assert'; - * - * const { - * createECDH, - * } = await import('node:crypto'); - * - * // Generate Alice's keys... - * const alice = createECDH('secp521r1'); - * const aliceKey = alice.generateKeys(); - * - * // Generate Bob's keys... - * const bob = createECDH('secp521r1'); - * const bobKey = bob.generateKeys(); - * - * // Exchange and generate the secret... - * const aliceSecret = alice.computeSecret(bobKey); - * const bobSecret = bob.computeSecret(aliceKey); - * - * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); - * // OK - * ``` - * @since v0.11.14 - */ - class ECDH { - private constructor(); - /** - * Converts the EC Diffie-Hellman public key specified by `key` and `curve` to the - * format specified by `format`. The `format` argument specifies point encoding - * and can be `'compressed'`, `'uncompressed'` or `'hybrid'`. The supplied key is - * interpreted using the specified `inputEncoding`, and the returned key is encoded - * using the specified `outputEncoding`. - * - * Use {@link getCurves} to obtain a list of available curve names. - * On recent OpenSSL releases, `openssl ecparam -list_curves` will also display - * the name and description of each available elliptic curve. - * - * If `format` is not specified the point will be returned in `'uncompressed'`format. - * - * If the `inputEncoding` is not provided, `key` is expected to be a `Buffer`,`TypedArray`, or `DataView`. - * - * Example (uncompressing a key): - * - * ```js - * const { - * createECDH, - * ECDH, - * } = await import('node:crypto'); - * - * const ecdh = createECDH('secp256k1'); - * ecdh.generateKeys(); - * - * const compressedKey = ecdh.getPublicKey('hex', 'compressed'); - * - * const uncompressedKey = ECDH.convertKey(compressedKey, - * 'secp256k1', - * 'hex', - * 'hex', - * 'uncompressed'); - * - * // The converted key and the uncompressed public key should be the same - * console.log(uncompressedKey === ecdh.getPublicKey('hex')); - * ``` - * @since v10.0.0 - * @param inputEncoding The `encoding` of the `key` string. - * @param outputEncoding The `encoding` of the return value. - * @param [format='uncompressed'] - */ - static convertKey( - key: BinaryLike, - curve: string, - inputEncoding?: BinaryToTextEncoding, - outputEncoding?: "latin1" | "hex" | "base64" | "base64url", - format?: "uncompressed" | "compressed" | "hybrid", - ): Buffer | string; - /** - * Generates private and public EC Diffie-Hellman key values, and returns - * the public key in the specified `format` and `encoding`. This key should be - * transferred to the other party. - * - * The `format` argument specifies point encoding and can be `'compressed'` or`'uncompressed'`. If `format` is not specified, the point will be returned in`'uncompressed'` format. - * - * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. - * @since v0.11.14 - * @param encoding The `encoding` of the return value. - * @param [format='uncompressed'] - */ - generateKeys(): Buffer; - generateKeys(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; - /** - * Computes the shared secret using `otherPublicKey` as the other - * party's public key and returns the computed shared secret. The supplied - * key is interpreted using specified `inputEncoding`, and the returned secret - * is encoded using the specified `outputEncoding`. - * If the `inputEncoding` is not - * provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or`DataView`. - * - * If `outputEncoding` is given a string will be returned; otherwise a `Buffer` is returned. - * - * `ecdh.computeSecret` will throw an`ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY` error when `otherPublicKey`lies outside of the elliptic curve. Since `otherPublicKey` is - * usually supplied from a remote user over an insecure network, - * be sure to handle this exception accordingly. - * @since v0.11.14 - * @param inputEncoding The `encoding` of the `otherPublicKey` string. - * @param outputEncoding The `encoding` of the return value. - */ - computeSecret(otherPublicKey: NodeJS.ArrayBufferView): Buffer; - computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding): Buffer; - computeSecret(otherPublicKey: NodeJS.ArrayBufferView, outputEncoding: BinaryToTextEncoding): string; - computeSecret( - otherPublicKey: string, - inputEncoding: BinaryToTextEncoding, - outputEncoding: BinaryToTextEncoding, - ): string; - /** - * If `encoding` is specified, a string is returned; otherwise a `Buffer` is - * returned. - * @since v0.11.14 - * @param encoding The `encoding` of the return value. - * @return The EC Diffie-Hellman in the specified `encoding`. - */ - getPrivateKey(): Buffer; - getPrivateKey(encoding: BinaryToTextEncoding): string; - /** - * The `format` argument specifies point encoding and can be `'compressed'` or`'uncompressed'`. If `format` is not specified the point will be returned in`'uncompressed'` format. - * - * If `encoding` is specified, a string is returned; otherwise a `Buffer` is - * returned. - * @since v0.11.14 - * @param encoding The `encoding` of the return value. - * @param [format='uncompressed'] - * @return The EC Diffie-Hellman public key in the specified `encoding` and `format`. - */ - getPublicKey(encoding?: null, format?: ECDHKeyFormat): Buffer; - getPublicKey(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; - /** - * Sets the EC Diffie-Hellman private key. - * If `encoding` is provided, `privateKey` is expected - * to be a string; otherwise `privateKey` is expected to be a `Buffer`,`TypedArray`, or `DataView`. - * - * If `privateKey` is not valid for the curve specified when the `ECDH` object was - * created, an error is thrown. Upon setting the private key, the associated - * public point (key) is also generated and set in the `ECDH` object. - * @since v0.11.14 - * @param encoding The `encoding` of the `privateKey` string. - */ - setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; - setPrivateKey(privateKey: string, encoding: BinaryToTextEncoding): void; - } - /** - * Creates an Elliptic Curve Diffie-Hellman (`ECDH`) key exchange object using a - * predefined curve specified by the `curveName` string. Use {@link getCurves} to obtain a list of available curve names. On recent - * OpenSSL releases, `openssl ecparam -list_curves` will also display the name - * and description of each available elliptic curve. - * @since v0.11.14 - */ - function createECDH(curveName: string): ECDH; - /** - * This function compares the underlying bytes that represent the given`ArrayBuffer`, `TypedArray`, or `DataView` instances using a constant-time - * algorithm. - * - * This function does not leak timing information that - * would allow an attacker to guess one of the values. This is suitable for - * comparing HMAC digests or secret values like authentication cookies or [capability urls](https://www.w3.org/TR/capability-urls/). - * - * `a` and `b` must both be `Buffer`s, `TypedArray`s, or `DataView`s, and they - * must have the same byte length. An error is thrown if `a` and `b` have - * different byte lengths. - * - * If at least one of `a` and `b` is a `TypedArray` with more than one byte per - * entry, such as `Uint16Array`, the result will be computed using the platform - * byte order. - * - * **When both of the inputs are `Float32Array`s or`Float64Array`s, this function might return unexpected results due to IEEE 754** - * **encoding of floating-point numbers. In particular, neither `x === y` nor`Object.is(x, y)` implies that the byte representations of two floating-point** - * **numbers `x` and `y` are equal.** - * - * Use of `crypto.timingSafeEqual` does not guarantee that the _surrounding_ code - * is timing-safe. Care should be taken to ensure that the surrounding code does - * not introduce timing vulnerabilities. - * @since v6.6.0 - */ - function timingSafeEqual(a: NodeJS.ArrayBufferView, b: NodeJS.ArrayBufferView): boolean; - type KeyType = "rsa" | "rsa-pss" | "dsa" | "ec" | "ed25519" | "ed448" | "x25519" | "x448"; - type KeyFormat = "pem" | "der" | "jwk"; - interface BasePrivateKeyEncodingOptions { - format: T; - cipher?: string | undefined; - passphrase?: string | undefined; - } - interface KeyPairKeyObjectResult { - publicKey: KeyObject; - privateKey: KeyObject; - } - interface ED25519KeyPairKeyObjectOptions {} - interface ED448KeyPairKeyObjectOptions {} - interface X25519KeyPairKeyObjectOptions {} - interface X448KeyPairKeyObjectOptions {} - interface ECKeyPairKeyObjectOptions { - /** - * Name of the curve to use - */ - namedCurve: string; - /** - * Must be `'named'` or `'explicit'`. Default: `'named'`. - */ - paramEncoding?: "explicit" | "named" | undefined; - } - interface RSAKeyPairKeyObjectOptions { - /** - * Key size in bits - */ - modulusLength: number; - /** - * Public exponent - * @default 0x10001 - */ - publicExponent?: number | undefined; - } - interface RSAPSSKeyPairKeyObjectOptions { - /** - * Key size in bits - */ - modulusLength: number; - /** - * Public exponent - * @default 0x10001 - */ - publicExponent?: number | undefined; - /** - * Name of the message digest - */ - hashAlgorithm?: string; - /** - * Name of the message digest used by MGF1 - */ - mgf1HashAlgorithm?: string; - /** - * Minimal salt length in bytes - */ - saltLength?: string; - } - interface DSAKeyPairKeyObjectOptions { - /** - * Key size in bits - */ - modulusLength: number; - /** - * Size of q in bits - */ - divisorLength: number; - } - interface RSAKeyPairOptions { - /** - * Key size in bits - */ - modulusLength: number; - /** - * Public exponent - * @default 0x10001 - */ - publicExponent?: number | undefined; - publicKeyEncoding: { - type: "pkcs1" | "spki"; - format: PubF; - }; - privateKeyEncoding: BasePrivateKeyEncodingOptions & { - type: "pkcs1" | "pkcs8"; - }; - } - interface RSAPSSKeyPairOptions { - /** - * Key size in bits - */ - modulusLength: number; - /** - * Public exponent - * @default 0x10001 - */ - publicExponent?: number | undefined; - /** - * Name of the message digest - */ - hashAlgorithm?: string; - /** - * Name of the message digest used by MGF1 - */ - mgf1HashAlgorithm?: string; - /** - * Minimal salt length in bytes - */ - saltLength?: string; - publicKeyEncoding: { - type: "spki"; - format: PubF; - }; - privateKeyEncoding: BasePrivateKeyEncodingOptions & { - type: "pkcs8"; - }; - } - interface DSAKeyPairOptions { - /** - * Key size in bits - */ - modulusLength: number; - /** - * Size of q in bits - */ - divisorLength: number; - publicKeyEncoding: { - type: "spki"; - format: PubF; - }; - privateKeyEncoding: BasePrivateKeyEncodingOptions & { - type: "pkcs8"; - }; - } - interface ECKeyPairOptions extends ECKeyPairKeyObjectOptions { - publicKeyEncoding: { - type: "pkcs1" | "spki"; - format: PubF; - }; - privateKeyEncoding: BasePrivateKeyEncodingOptions & { - type: "sec1" | "pkcs8"; - }; - } - interface ED25519KeyPairOptions { - publicKeyEncoding: { - type: "spki"; - format: PubF; - }; - privateKeyEncoding: BasePrivateKeyEncodingOptions & { - type: "pkcs8"; - }; - } - interface ED448KeyPairOptions { - publicKeyEncoding: { - type: "spki"; - format: PubF; - }; - privateKeyEncoding: BasePrivateKeyEncodingOptions & { - type: "pkcs8"; - }; - } - interface X25519KeyPairOptions { - publicKeyEncoding: { - type: "spki"; - format: PubF; - }; - privateKeyEncoding: BasePrivateKeyEncodingOptions & { - type: "pkcs8"; - }; - } - interface X448KeyPairOptions { - publicKeyEncoding: { - type: "spki"; - format: PubF; - }; - privateKeyEncoding: BasePrivateKeyEncodingOptions & { - type: "pkcs8"; - }; - } - interface KeyPairSyncResult { - publicKey: T1; - privateKey: T2; - } - /** - * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, - * Ed25519, Ed448, X25519, X448, and DH are currently supported. - * - * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function - * behaves as if `keyObject.export()` had been called on its result. Otherwise, - * the respective part of the key is returned as a `KeyObject`. - * - * When encoding public keys, it is recommended to use `'spki'`. When encoding - * private keys, it is recommended to use `'pkcs8'` with a strong passphrase, - * and to keep the passphrase confidential. - * - * ```js - * const { - * generateKeyPairSync, - * } = await import('node:crypto'); - * - * const { - * publicKey, - * privateKey, - * } = generateKeyPairSync('rsa', { - * modulusLength: 4096, - * publicKeyEncoding: { - * type: 'spki', - * format: 'pem', - * }, - * privateKeyEncoding: { - * type: 'pkcs8', - * format: 'pem', - * cipher: 'aes-256-cbc', - * passphrase: 'top secret', - * }, - * }); - * ``` - * - * The return value `{ publicKey, privateKey }` represents the generated key pair. - * When PEM encoding was selected, the respective key will be a string, otherwise - * it will be a buffer containing the data encoded as DER. - * @since v10.12.0 - * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. - */ - function generateKeyPairSync( - type: "rsa", - options: RSAKeyPairOptions<"pem", "pem">, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: "rsa", - options: RSAKeyPairOptions<"pem", "der">, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: "rsa", - options: RSAKeyPairOptions<"der", "pem">, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: "rsa", - options: RSAKeyPairOptions<"der", "der">, - ): KeyPairSyncResult; - function generateKeyPairSync(type: "rsa", options: RSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; - function generateKeyPairSync( - type: "rsa-pss", - options: RSAPSSKeyPairOptions<"pem", "pem">, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: "rsa-pss", - options: RSAPSSKeyPairOptions<"pem", "der">, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: "rsa-pss", - options: RSAPSSKeyPairOptions<"der", "pem">, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: "rsa-pss", - options: RSAPSSKeyPairOptions<"der", "der">, - ): KeyPairSyncResult; - function generateKeyPairSync(type: "rsa-pss", options: RSAPSSKeyPairKeyObjectOptions): KeyPairKeyObjectResult; - function generateKeyPairSync( - type: "dsa", - options: DSAKeyPairOptions<"pem", "pem">, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: "dsa", - options: DSAKeyPairOptions<"pem", "der">, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: "dsa", - options: DSAKeyPairOptions<"der", "pem">, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: "dsa", - options: DSAKeyPairOptions<"der", "der">, - ): KeyPairSyncResult; - function generateKeyPairSync(type: "dsa", options: DSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; - function generateKeyPairSync( - type: "ec", - options: ECKeyPairOptions<"pem", "pem">, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: "ec", - options: ECKeyPairOptions<"pem", "der">, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: "ec", - options: ECKeyPairOptions<"der", "pem">, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: "ec", - options: ECKeyPairOptions<"der", "der">, - ): KeyPairSyncResult; - function generateKeyPairSync(type: "ec", options: ECKeyPairKeyObjectOptions): KeyPairKeyObjectResult; - function generateKeyPairSync( - type: "ed25519", - options: ED25519KeyPairOptions<"pem", "pem">, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: "ed25519", - options: ED25519KeyPairOptions<"pem", "der">, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: "ed25519", - options: ED25519KeyPairOptions<"der", "pem">, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: "ed25519", - options: ED25519KeyPairOptions<"der", "der">, - ): KeyPairSyncResult; - function generateKeyPairSync(type: "ed25519", options?: ED25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; - function generateKeyPairSync( - type: "ed448", - options: ED448KeyPairOptions<"pem", "pem">, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: "ed448", - options: ED448KeyPairOptions<"pem", "der">, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: "ed448", - options: ED448KeyPairOptions<"der", "pem">, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: "ed448", - options: ED448KeyPairOptions<"der", "der">, - ): KeyPairSyncResult; - function generateKeyPairSync(type: "ed448", options?: ED448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; - function generateKeyPairSync( - type: "x25519", - options: X25519KeyPairOptions<"pem", "pem">, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: "x25519", - options: X25519KeyPairOptions<"pem", "der">, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: "x25519", - options: X25519KeyPairOptions<"der", "pem">, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: "x25519", - options: X25519KeyPairOptions<"der", "der">, - ): KeyPairSyncResult; - function generateKeyPairSync(type: "x25519", options?: X25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; - function generateKeyPairSync( - type: "x448", - options: X448KeyPairOptions<"pem", "pem">, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: "x448", - options: X448KeyPairOptions<"pem", "der">, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: "x448", - options: X448KeyPairOptions<"der", "pem">, - ): KeyPairSyncResult; - function generateKeyPairSync( - type: "x448", - options: X448KeyPairOptions<"der", "der">, - ): KeyPairSyncResult; - function generateKeyPairSync(type: "x448", options?: X448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; - /** - * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, - * Ed25519, Ed448, X25519, X448, and DH are currently supported. - * - * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function - * behaves as if `keyObject.export()` had been called on its result. Otherwise, - * the respective part of the key is returned as a `KeyObject`. - * - * It is recommended to encode public keys as `'spki'` and private keys as`'pkcs8'` with encryption for long-term storage: - * - * ```js - * const { - * generateKeyPair, - * } = await import('node:crypto'); - * - * generateKeyPair('rsa', { - * modulusLength: 4096, - * publicKeyEncoding: { - * type: 'spki', - * format: 'pem', - * }, - * privateKeyEncoding: { - * type: 'pkcs8', - * format: 'pem', - * cipher: 'aes-256-cbc', - * passphrase: 'top secret', - * }, - * }, (err, publicKey, privateKey) => { - * // Handle errors and use the generated key pair. - * }); - * ``` - * - * On completion, `callback` will be called with `err` set to `undefined` and`publicKey` / `privateKey` representing the generated key pair. - * - * If this method is invoked as its `util.promisify()` ed version, it returns - * a `Promise` for an `Object` with `publicKey` and `privateKey` properties. - * @since v10.12.0 - * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. - */ - function generateKeyPair( - type: "rsa", - options: RSAKeyPairOptions<"pem", "pem">, - callback: (err: Error | null, publicKey: string, privateKey: string) => void, - ): void; - function generateKeyPair( - type: "rsa", - options: RSAKeyPairOptions<"pem", "der">, - callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, - ): void; - function generateKeyPair( - type: "rsa", - options: RSAKeyPairOptions<"der", "pem">, - callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, - ): void; - function generateKeyPair( - type: "rsa", - options: RSAKeyPairOptions<"der", "der">, - callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, - ): void; - function generateKeyPair( - type: "rsa", - options: RSAKeyPairKeyObjectOptions, - callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, - ): void; - function generateKeyPair( - type: "rsa-pss", - options: RSAPSSKeyPairOptions<"pem", "pem">, - callback: (err: Error | null, publicKey: string, privateKey: string) => void, - ): void; - function generateKeyPair( - type: "rsa-pss", - options: RSAPSSKeyPairOptions<"pem", "der">, - callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, - ): void; - function generateKeyPair( - type: "rsa-pss", - options: RSAPSSKeyPairOptions<"der", "pem">, - callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, - ): void; - function generateKeyPair( - type: "rsa-pss", - options: RSAPSSKeyPairOptions<"der", "der">, - callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, - ): void; - function generateKeyPair( - type: "rsa-pss", - options: RSAPSSKeyPairKeyObjectOptions, - callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, - ): void; - function generateKeyPair( - type: "dsa", - options: DSAKeyPairOptions<"pem", "pem">, - callback: (err: Error | null, publicKey: string, privateKey: string) => void, - ): void; - function generateKeyPair( - type: "dsa", - options: DSAKeyPairOptions<"pem", "der">, - callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, - ): void; - function generateKeyPair( - type: "dsa", - options: DSAKeyPairOptions<"der", "pem">, - callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, - ): void; - function generateKeyPair( - type: "dsa", - options: DSAKeyPairOptions<"der", "der">, - callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, - ): void; - function generateKeyPair( - type: "dsa", - options: DSAKeyPairKeyObjectOptions, - callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, - ): void; - function generateKeyPair( - type: "ec", - options: ECKeyPairOptions<"pem", "pem">, - callback: (err: Error | null, publicKey: string, privateKey: string) => void, - ): void; - function generateKeyPair( - type: "ec", - options: ECKeyPairOptions<"pem", "der">, - callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, - ): void; - function generateKeyPair( - type: "ec", - options: ECKeyPairOptions<"der", "pem">, - callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, - ): void; - function generateKeyPair( - type: "ec", - options: ECKeyPairOptions<"der", "der">, - callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, - ): void; - function generateKeyPair( - type: "ec", - options: ECKeyPairKeyObjectOptions, - callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, - ): void; - function generateKeyPair( - type: "ed25519", - options: ED25519KeyPairOptions<"pem", "pem">, - callback: (err: Error | null, publicKey: string, privateKey: string) => void, - ): void; - function generateKeyPair( - type: "ed25519", - options: ED25519KeyPairOptions<"pem", "der">, - callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, - ): void; - function generateKeyPair( - type: "ed25519", - options: ED25519KeyPairOptions<"der", "pem">, - callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, - ): void; - function generateKeyPair( - type: "ed25519", - options: ED25519KeyPairOptions<"der", "der">, - callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, - ): void; - function generateKeyPair( - type: "ed25519", - options: ED25519KeyPairKeyObjectOptions | undefined, - callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, - ): void; - function generateKeyPair( - type: "ed448", - options: ED448KeyPairOptions<"pem", "pem">, - callback: (err: Error | null, publicKey: string, privateKey: string) => void, - ): void; - function generateKeyPair( - type: "ed448", - options: ED448KeyPairOptions<"pem", "der">, - callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, - ): void; - function generateKeyPair( - type: "ed448", - options: ED448KeyPairOptions<"der", "pem">, - callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, - ): void; - function generateKeyPair( - type: "ed448", - options: ED448KeyPairOptions<"der", "der">, - callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, - ): void; - function generateKeyPair( - type: "ed448", - options: ED448KeyPairKeyObjectOptions | undefined, - callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, - ): void; - function generateKeyPair( - type: "x25519", - options: X25519KeyPairOptions<"pem", "pem">, - callback: (err: Error | null, publicKey: string, privateKey: string) => void, - ): void; - function generateKeyPair( - type: "x25519", - options: X25519KeyPairOptions<"pem", "der">, - callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, - ): void; - function generateKeyPair( - type: "x25519", - options: X25519KeyPairOptions<"der", "pem">, - callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, - ): void; - function generateKeyPair( - type: "x25519", - options: X25519KeyPairOptions<"der", "der">, - callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, - ): void; - function generateKeyPair( - type: "x25519", - options: X25519KeyPairKeyObjectOptions | undefined, - callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, - ): void; - function generateKeyPair( - type: "x448", - options: X448KeyPairOptions<"pem", "pem">, - callback: (err: Error | null, publicKey: string, privateKey: string) => void, - ): void; - function generateKeyPair( - type: "x448", - options: X448KeyPairOptions<"pem", "der">, - callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, - ): void; - function generateKeyPair( - type: "x448", - options: X448KeyPairOptions<"der", "pem">, - callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, - ): void; - function generateKeyPair( - type: "x448", - options: X448KeyPairOptions<"der", "der">, - callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, - ): void; - function generateKeyPair( - type: "x448", - options: X448KeyPairKeyObjectOptions | undefined, - callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, - ): void; - namespace generateKeyPair { - function __promisify__( - type: "rsa", - options: RSAKeyPairOptions<"pem", "pem">, - ): Promise<{ - publicKey: string; - privateKey: string; - }>; - function __promisify__( - type: "rsa", - options: RSAKeyPairOptions<"pem", "der">, - ): Promise<{ - publicKey: string; - privateKey: Buffer; - }>; - function __promisify__( - type: "rsa", - options: RSAKeyPairOptions<"der", "pem">, - ): Promise<{ - publicKey: Buffer; - privateKey: string; - }>; - function __promisify__( - type: "rsa", - options: RSAKeyPairOptions<"der", "der">, - ): Promise<{ - publicKey: Buffer; - privateKey: Buffer; - }>; - function __promisify__(type: "rsa", options: RSAKeyPairKeyObjectOptions): Promise; - function __promisify__( - type: "rsa-pss", - options: RSAPSSKeyPairOptions<"pem", "pem">, - ): Promise<{ - publicKey: string; - privateKey: string; - }>; - function __promisify__( - type: "rsa-pss", - options: RSAPSSKeyPairOptions<"pem", "der">, - ): Promise<{ - publicKey: string; - privateKey: Buffer; - }>; - function __promisify__( - type: "rsa-pss", - options: RSAPSSKeyPairOptions<"der", "pem">, - ): Promise<{ - publicKey: Buffer; - privateKey: string; - }>; - function __promisify__( - type: "rsa-pss", - options: RSAPSSKeyPairOptions<"der", "der">, - ): Promise<{ - publicKey: Buffer; - privateKey: Buffer; - }>; - function __promisify__( - type: "rsa-pss", - options: RSAPSSKeyPairKeyObjectOptions, - ): Promise; - function __promisify__( - type: "dsa", - options: DSAKeyPairOptions<"pem", "pem">, - ): Promise<{ - publicKey: string; - privateKey: string; - }>; - function __promisify__( - type: "dsa", - options: DSAKeyPairOptions<"pem", "der">, - ): Promise<{ - publicKey: string; - privateKey: Buffer; - }>; - function __promisify__( - type: "dsa", - options: DSAKeyPairOptions<"der", "pem">, - ): Promise<{ - publicKey: Buffer; - privateKey: string; - }>; - function __promisify__( - type: "dsa", - options: DSAKeyPairOptions<"der", "der">, - ): Promise<{ - publicKey: Buffer; - privateKey: Buffer; - }>; - function __promisify__(type: "dsa", options: DSAKeyPairKeyObjectOptions): Promise; - function __promisify__( - type: "ec", - options: ECKeyPairOptions<"pem", "pem">, - ): Promise<{ - publicKey: string; - privateKey: string; - }>; - function __promisify__( - type: "ec", - options: ECKeyPairOptions<"pem", "der">, - ): Promise<{ - publicKey: string; - privateKey: Buffer; - }>; - function __promisify__( - type: "ec", - options: ECKeyPairOptions<"der", "pem">, - ): Promise<{ - publicKey: Buffer; - privateKey: string; - }>; - function __promisify__( - type: "ec", - options: ECKeyPairOptions<"der", "der">, - ): Promise<{ - publicKey: Buffer; - privateKey: Buffer; - }>; - function __promisify__(type: "ec", options: ECKeyPairKeyObjectOptions): Promise; - function __promisify__( - type: "ed25519", - options: ED25519KeyPairOptions<"pem", "pem">, - ): Promise<{ - publicKey: string; - privateKey: string; - }>; - function __promisify__( - type: "ed25519", - options: ED25519KeyPairOptions<"pem", "der">, - ): Promise<{ - publicKey: string; - privateKey: Buffer; - }>; - function __promisify__( - type: "ed25519", - options: ED25519KeyPairOptions<"der", "pem">, - ): Promise<{ - publicKey: Buffer; - privateKey: string; - }>; - function __promisify__( - type: "ed25519", - options: ED25519KeyPairOptions<"der", "der">, - ): Promise<{ - publicKey: Buffer; - privateKey: Buffer; - }>; - function __promisify__( - type: "ed25519", - options?: ED25519KeyPairKeyObjectOptions, - ): Promise; - function __promisify__( - type: "ed448", - options: ED448KeyPairOptions<"pem", "pem">, - ): Promise<{ - publicKey: string; - privateKey: string; - }>; - function __promisify__( - type: "ed448", - options: ED448KeyPairOptions<"pem", "der">, - ): Promise<{ - publicKey: string; - privateKey: Buffer; - }>; - function __promisify__( - type: "ed448", - options: ED448KeyPairOptions<"der", "pem">, - ): Promise<{ - publicKey: Buffer; - privateKey: string; - }>; - function __promisify__( - type: "ed448", - options: ED448KeyPairOptions<"der", "der">, - ): Promise<{ - publicKey: Buffer; - privateKey: Buffer; - }>; - function __promisify__(type: "ed448", options?: ED448KeyPairKeyObjectOptions): Promise; - function __promisify__( - type: "x25519", - options: X25519KeyPairOptions<"pem", "pem">, - ): Promise<{ - publicKey: string; - privateKey: string; - }>; - function __promisify__( - type: "x25519", - options: X25519KeyPairOptions<"pem", "der">, - ): Promise<{ - publicKey: string; - privateKey: Buffer; - }>; - function __promisify__( - type: "x25519", - options: X25519KeyPairOptions<"der", "pem">, - ): Promise<{ - publicKey: Buffer; - privateKey: string; - }>; - function __promisify__( - type: "x25519", - options: X25519KeyPairOptions<"der", "der">, - ): Promise<{ - publicKey: Buffer; - privateKey: Buffer; - }>; - function __promisify__( - type: "x25519", - options?: X25519KeyPairKeyObjectOptions, - ): Promise; - function __promisify__( - type: "x448", - options: X448KeyPairOptions<"pem", "pem">, - ): Promise<{ - publicKey: string; - privateKey: string; - }>; - function __promisify__( - type: "x448", - options: X448KeyPairOptions<"pem", "der">, - ): Promise<{ - publicKey: string; - privateKey: Buffer; - }>; - function __promisify__( - type: "x448", - options: X448KeyPairOptions<"der", "pem">, - ): Promise<{ - publicKey: Buffer; - privateKey: string; - }>; - function __promisify__( - type: "x448", - options: X448KeyPairOptions<"der", "der">, - ): Promise<{ - publicKey: Buffer; - privateKey: Buffer; - }>; - function __promisify__(type: "x448", options?: X448KeyPairKeyObjectOptions): Promise; - } - /** - * Calculates and returns the signature for `data` using the given private key and - * algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is - * dependent upon the key type (especially Ed25519 and Ed448). - * - * If `key` is not a `KeyObject`, this function behaves as if `key` had been - * passed to {@link createPrivateKey}. If it is an object, the following - * additional properties can be passed: - * - * If the `callback` function is provided this function uses libuv's threadpool. - * @since v12.0.0 - */ - function sign( - algorithm: string | null | undefined, - data: NodeJS.ArrayBufferView, - key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, - ): Buffer; - function sign( - algorithm: string | null | undefined, - data: NodeJS.ArrayBufferView, - key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, - callback: (error: Error | null, data: Buffer) => void, - ): void; - /** - * Verifies the given signature for `data` using the given key and algorithm. If`algorithm` is `null` or `undefined`, then the algorithm is dependent upon the - * key type (especially Ed25519 and Ed448). - * - * If `key` is not a `KeyObject`, this function behaves as if `key` had been - * passed to {@link createPublicKey}. If it is an object, the following - * additional properties can be passed: - * - * The `signature` argument is the previously calculated signature for the `data`. - * - * Because public keys can be derived from private keys, a private key or a public - * key may be passed for `key`. - * - * If the `callback` function is provided this function uses libuv's threadpool. - * @since v12.0.0 - */ - function verify( - algorithm: string | null | undefined, - data: NodeJS.ArrayBufferView, - key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, - signature: NodeJS.ArrayBufferView, - ): boolean; - function verify( - algorithm: string | null | undefined, - data: NodeJS.ArrayBufferView, - key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, - signature: NodeJS.ArrayBufferView, - callback: (error: Error | null, result: boolean) => void, - ): void; - /** - * Computes the Diffie-Hellman secret based on a `privateKey` and a `publicKey`. - * Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'`(for Diffie-Hellman), `'ec'` (for ECDH), `'x448'`, or `'x25519'` (for ECDH-ES). - * @since v13.9.0, v12.17.0 - */ - function diffieHellman(options: { privateKey: KeyObject; publicKey: KeyObject }): Buffer; - type CipherMode = "cbc" | "ccm" | "cfb" | "ctr" | "ecb" | "gcm" | "ocb" | "ofb" | "stream" | "wrap" | "xts"; - interface CipherInfoOptions { - /** - * A test key length. - */ - keyLength?: number | undefined; - /** - * A test IV length. - */ - ivLength?: number | undefined; - } - interface CipherInfo { - /** - * The name of the cipher. - */ - name: string; - /** - * The nid of the cipher. - */ - nid: number; - /** - * The block size of the cipher in bytes. - * This property is omitted when mode is 'stream'. - */ - blockSize?: number | undefined; - /** - * The expected or default initialization vector length in bytes. - * This property is omitted if the cipher does not use an initialization vector. - */ - ivLength?: number | undefined; - /** - * The expected or default key length in bytes. - */ - keyLength: number; - /** - * The cipher mode. - */ - mode: CipherMode; - } - /** - * Returns information about a given cipher. - * - * Some ciphers accept variable length keys and initialization vectors. By default, - * the `crypto.getCipherInfo()` method will return the default values for these - * ciphers. To test if a given key length or iv length is acceptable for given - * cipher, use the `keyLength` and `ivLength` options. If the given values are - * unacceptable, `undefined` will be returned. - * @since v15.0.0 - * @param nameOrNid The name or nid of the cipher to query. - */ - function getCipherInfo(nameOrNid: string | number, options?: CipherInfoOptions): CipherInfo | undefined; - /** - * HKDF is a simple key derivation function defined in RFC 5869\. The given `ikm`,`salt` and `info` are used with the `digest` to derive a key of `keylen` bytes. - * - * The supplied `callback` function is called with two arguments: `err` and`derivedKey`. If an errors occurs while deriving the key, `err` will be set; - * otherwise `err` will be `null`. The successfully generated `derivedKey` will - * be passed to the callback as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). An error will be thrown if any - * of the input arguments specify invalid values or types. - * - * ```js - * import { Buffer } from 'node:buffer'; - * const { - * hkdf, - * } = await import('node:crypto'); - * - * hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { - * if (err) throw err; - * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' - * }); - * ``` - * @since v15.0.0 - * @param digest The digest algorithm to use. - * @param ikm The input keying material. Must be provided but can be zero-length. - * @param salt The salt value. Must be provided but can be zero-length. - * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. - * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` - * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). - */ - function hkdf( - digest: string, - irm: BinaryLike | KeyObject, - salt: BinaryLike, - info: BinaryLike, - keylen: number, - callback: (err: Error | null, derivedKey: ArrayBuffer) => void, - ): void; - /** - * Provides a synchronous HKDF key derivation function as defined in RFC 5869\. The - * given `ikm`, `salt` and `info` are used with the `digest` to derive a key of`keylen` bytes. - * - * The successfully generated `derivedKey` will be returned as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). - * - * An error will be thrown if any of the input arguments specify invalid values or - * types, or if the derived key cannot be generated. - * - * ```js - * import { Buffer } from 'node:buffer'; - * const { - * hkdfSync, - * } = await import('node:crypto'); - * - * const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64); - * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' - * ``` - * @since v15.0.0 - * @param digest The digest algorithm to use. - * @param ikm The input keying material. Must be provided but can be zero-length. - * @param salt The salt value. Must be provided but can be zero-length. - * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. - * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` - * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). - */ - function hkdfSync( - digest: string, - ikm: BinaryLike | KeyObject, - salt: BinaryLike, - info: BinaryLike, - keylen: number, - ): ArrayBuffer; - interface SecureHeapUsage { - /** - * The total allocated secure heap size as specified using the `--secure-heap=n` command-line flag. - */ - total: number; - /** - * The minimum allocation from the secure heap as specified using the `--secure-heap-min` command-line flag. - */ - min: number; - /** - * The total number of bytes currently allocated from the secure heap. - */ - used: number; - /** - * The calculated ratio of `used` to `total` allocated bytes. - */ - utilization: number; - } - /** - * @since v15.6.0 - */ - function secureHeapUsed(): SecureHeapUsage; - interface RandomUUIDOptions { - /** - * By default, to improve performance, - * Node.js will pre-emptively generate and persistently cache enough - * random data to generate up to 128 random UUIDs. To generate a UUID - * without using the cache, set `disableEntropyCache` to `true`. - * - * @default `false` - */ - disableEntropyCache?: boolean | undefined; - } - /** - * Generates a random [RFC 4122](https://www.rfc-editor.org/rfc/rfc4122.txt) version 4 UUID. The UUID is generated using a - * cryptographic pseudorandom number generator. - * @since v15.6.0, v14.17.0 - */ - function randomUUID(options?: RandomUUIDOptions): string; - interface X509CheckOptions { - /** - * @default 'always' - */ - subject?: "always" | "default" | "never"; - /** - * @default true - */ - wildcards?: boolean; - /** - * @default true - */ - partialWildcards?: boolean; - /** - * @default false - */ - multiLabelWildcards?: boolean; - /** - * @default false - */ - singleLabelSubdomains?: boolean; - } - /** - * Encapsulates an X509 certificate and provides read-only access to - * its information. - * - * ```js - * const { X509Certificate } = await import('node:crypto'); - * - * const x509 = new X509Certificate('{... pem encoded cert ...}'); - * - * console.log(x509.subject); - * ``` - * @since v15.6.0 - */ - class X509Certificate { - /** - * Will be \`true\` if this is a Certificate Authority (CA) certificate. - * @since v15.6.0 - */ - readonly ca: boolean; - /** - * The SHA-1 fingerprint of this certificate. - * - * Because SHA-1 is cryptographically broken and because the security of SHA-1 is - * significantly worse than that of algorithms that are commonly used to sign - * certificates, consider using `x509.fingerprint256` instead. - * @since v15.6.0 - */ - readonly fingerprint: string; - /** - * The SHA-256 fingerprint of this certificate. - * @since v15.6.0 - */ - readonly fingerprint256: string; - /** - * The SHA-512 fingerprint of this certificate. - * - * Because computing the SHA-256 fingerprint is usually faster and because it is - * only half the size of the SHA-512 fingerprint, `x509.fingerprint256` may be - * a better choice. While SHA-512 presumably provides a higher level of security in - * general, the security of SHA-256 matches that of most algorithms that are - * commonly used to sign certificates. - * @since v17.2.0, v16.14.0 - */ - readonly fingerprint512: string; - /** - * The complete subject of this certificate. - * @since v15.6.0 - */ - readonly subject: string; - /** - * The subject alternative name specified for this certificate. - * - * This is a comma-separated list of subject alternative names. Each entry begins - * with a string identifying the kind of the subject alternative name followed by - * a colon and the value associated with the entry. - * - * Earlier versions of Node.js incorrectly assumed that it is safe to split this - * property at the two-character sequence `', '` (see [CVE-2021-44532](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44532)). However, - * both malicious and legitimate certificates can contain subject alternative names - * that include this sequence when represented as a string. - * - * After the prefix denoting the type of the entry, the remainder of each entry - * might be enclosed in quotes to indicate that the value is a JSON string literal. - * For backward compatibility, Node.js only uses JSON string literals within this - * property when necessary to avoid ambiguity. Third-party code should be prepared - * to handle both possible entry formats. - * @since v15.6.0 - */ - readonly subjectAltName: string | undefined; - /** - * A textual representation of the certificate's authority information access - * extension. - * - * This is a line feed separated list of access descriptions. Each line begins with - * the access method and the kind of the access location, followed by a colon and - * the value associated with the access location. - * - * After the prefix denoting the access method and the kind of the access location, - * the remainder of each line might be enclosed in quotes to indicate that the - * value is a JSON string literal. For backward compatibility, Node.js only uses - * JSON string literals within this property when necessary to avoid ambiguity. - * Third-party code should be prepared to handle both possible entry formats. - * @since v15.6.0 - */ - readonly infoAccess: string | undefined; - /** - * An array detailing the key usages for this certificate. - * @since v15.6.0 - */ - readonly keyUsage: string[]; - /** - * The issuer identification included in this certificate. - * @since v15.6.0 - */ - readonly issuer: string; - /** - * The issuer certificate or `undefined` if the issuer certificate is not - * available. - * @since v15.9.0 - */ - readonly issuerCertificate?: X509Certificate | undefined; - /** - * The public key `KeyObject` for this certificate. - * @since v15.6.0 - */ - readonly publicKey: KeyObject; - /** - * A `Buffer` containing the DER encoding of this certificate. - * @since v15.6.0 - */ - readonly raw: Buffer; - /** - * The serial number of this certificate. - * - * Serial numbers are assigned by certificate authorities and do not uniquely - * identify certificates. Consider using `x509.fingerprint256` as a unique - * identifier instead. - * @since v15.6.0 - */ - readonly serialNumber: string; - /** - * The date/time from which this certificate is considered valid. - * @since v15.6.0 - */ - readonly validFrom: string; - /** - * The date/time until which this certificate is considered valid. - * @since v15.6.0 - */ - readonly validTo: string; - constructor(buffer: BinaryLike); - /** - * Checks whether the certificate matches the given email address. - * - * If the `'subject'` option is undefined or set to `'default'`, the certificate - * subject is only considered if the subject alternative name extension either does - * not exist or does not contain any email addresses. - * - * If the `'subject'` option is set to `'always'` and if the subject alternative - * name extension either does not exist or does not contain a matching email - * address, the certificate subject is considered. - * - * If the `'subject'` option is set to `'never'`, the certificate subject is never - * considered, even if the certificate contains no subject alternative names. - * @since v15.6.0 - * @return Returns `email` if the certificate matches, `undefined` if it does not. - */ - checkEmail(email: string, options?: Pick): string | undefined; - /** - * Checks whether the certificate matches the given host name. - * - * If the certificate matches the given host name, the matching subject name is - * returned. The returned name might be an exact match (e.g., `foo.example.com`) - * or it might contain wildcards (e.g., `*.example.com`). Because host name - * comparisons are case-insensitive, the returned subject name might also differ - * from the given `name` in capitalization. - * - * If the `'subject'` option is undefined or set to `'default'`, the certificate - * subject is only considered if the subject alternative name extension either does - * not exist or does not contain any DNS names. This behavior is consistent with [RFC 2818](https://www.rfc-editor.org/rfc/rfc2818.txt) ("HTTP Over TLS"). - * - * If the `'subject'` option is set to `'always'` and if the subject alternative - * name extension either does not exist or does not contain a matching DNS name, - * the certificate subject is considered. - * - * If the `'subject'` option is set to `'never'`, the certificate subject is never - * considered, even if the certificate contains no subject alternative names. - * @since v15.6.0 - * @return Returns a subject name that matches `name`, or `undefined` if no subject name matches `name`. - */ - checkHost(name: string, options?: X509CheckOptions): string | undefined; - /** - * Checks whether the certificate matches the given IP address (IPv4 or IPv6). - * - * Only [RFC 5280](https://www.rfc-editor.org/rfc/rfc5280.txt) `iPAddress` subject alternative names are considered, and they - * must match the given `ip` address exactly. Other subject alternative names as - * well as the subject field of the certificate are ignored. - * @since v15.6.0 - * @return Returns `ip` if the certificate matches, `undefined` if it does not. - */ - checkIP(ip: string): string | undefined; - /** - * Checks whether this certificate was issued by the given `otherCert`. - * @since v15.6.0 - */ - checkIssued(otherCert: X509Certificate): boolean; - /** - * Checks whether the public key for this certificate is consistent with - * the given private key. - * @since v15.6.0 - * @param privateKey A private key. - */ - checkPrivateKey(privateKey: KeyObject): boolean; - /** - * There is no standard JSON encoding for X509 certificates. The`toJSON()` method returns a string containing the PEM encoded - * certificate. - * @since v15.6.0 - */ - toJSON(): string; - /** - * Returns information about this certificate using the legacy `certificate object` encoding. - * @since v15.6.0 - */ - toLegacyObject(): PeerCertificate; - /** - * Returns the PEM-encoded certificate. - * @since v15.6.0 - */ - toString(): string; - /** - * Verifies that this certificate was signed by the given public key. - * Does not perform any other validation checks on the certificate. - * @since v15.6.0 - * @param publicKey A public key. - */ - verify(publicKey: KeyObject): boolean; - } - type LargeNumberLike = NodeJS.ArrayBufferView | SharedArrayBuffer | ArrayBuffer | bigint; - interface GeneratePrimeOptions { - add?: LargeNumberLike | undefined; - rem?: LargeNumberLike | undefined; - /** - * @default false - */ - safe?: boolean | undefined; - bigint?: boolean | undefined; - } - interface GeneratePrimeOptionsBigInt extends GeneratePrimeOptions { - bigint: true; - } - interface GeneratePrimeOptionsArrayBuffer extends GeneratePrimeOptions { - bigint?: false | undefined; - } - /** - * Generates a pseudorandom prime of `size` bits. - * - * If `options.safe` is `true`, the prime will be a safe prime -- that is,`(prime - 1) / 2` will also be a prime. - * - * The `options.add` and `options.rem` parameters can be used to enforce additional - * requirements, e.g., for Diffie-Hellman: - * - * * If `options.add` and `options.rem` are both set, the prime will satisfy the - * condition that `prime % add = rem`. - * * If only `options.add` is set and `options.safe` is not `true`, the prime will - * satisfy the condition that `prime % add = 1`. - * * If only `options.add` is set and `options.safe` is set to `true`, the prime - * will instead satisfy the condition that `prime % add = 3`. This is necessary - * because `prime % add = 1` for `options.add > 2` would contradict the condition - * enforced by `options.safe`. - * * `options.rem` is ignored if `options.add` is not given. - * - * Both `options.add` and `options.rem` must be encoded as big-endian sequences - * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or`DataView`. - * - * By default, the prime is encoded as a big-endian sequence of octets - * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a - * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. - * @since v15.8.0 - * @param size The size (in bits) of the prime to generate. - */ - function generatePrime(size: number, callback: (err: Error | null, prime: ArrayBuffer) => void): void; - function generatePrime( - size: number, - options: GeneratePrimeOptionsBigInt, - callback: (err: Error | null, prime: bigint) => void, - ): void; - function generatePrime( - size: number, - options: GeneratePrimeOptionsArrayBuffer, - callback: (err: Error | null, prime: ArrayBuffer) => void, - ): void; - function generatePrime( - size: number, - options: GeneratePrimeOptions, - callback: (err: Error | null, prime: ArrayBuffer | bigint) => void, - ): void; - /** - * Generates a pseudorandom prime of `size` bits. - * - * If `options.safe` is `true`, the prime will be a safe prime -- that is,`(prime - 1) / 2` will also be a prime. - * - * The `options.add` and `options.rem` parameters can be used to enforce additional - * requirements, e.g., for Diffie-Hellman: - * - * * If `options.add` and `options.rem` are both set, the prime will satisfy the - * condition that `prime % add = rem`. - * * If only `options.add` is set and `options.safe` is not `true`, the prime will - * satisfy the condition that `prime % add = 1`. - * * If only `options.add` is set and `options.safe` is set to `true`, the prime - * will instead satisfy the condition that `prime % add = 3`. This is necessary - * because `prime % add = 1` for `options.add > 2` would contradict the condition - * enforced by `options.safe`. - * * `options.rem` is ignored if `options.add` is not given. - * - * Both `options.add` and `options.rem` must be encoded as big-endian sequences - * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or`DataView`. - * - * By default, the prime is encoded as a big-endian sequence of octets - * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a - * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. - * @since v15.8.0 - * @param size The size (in bits) of the prime to generate. - */ - function generatePrimeSync(size: number): ArrayBuffer; - function generatePrimeSync(size: number, options: GeneratePrimeOptionsBigInt): bigint; - function generatePrimeSync(size: number, options: GeneratePrimeOptionsArrayBuffer): ArrayBuffer; - function generatePrimeSync(size: number, options: GeneratePrimeOptions): ArrayBuffer | bigint; - interface CheckPrimeOptions { - /** - * The number of Miller-Rabin probabilistic primality iterations to perform. - * When the value is 0 (zero), a number of checks is used that yields a false positive rate of at most `2**-64` for random input. - * Care must be used when selecting a number of checks. - * Refer to the OpenSSL documentation for the BN_is_prime_ex function nchecks options for more details. - * - * @default 0 - */ - checks?: number | undefined; - } - /** - * Checks the primality of the `candidate`. - * @since v15.8.0 - * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. - */ - function checkPrime(value: LargeNumberLike, callback: (err: Error | null, result: boolean) => void): void; - function checkPrime( - value: LargeNumberLike, - options: CheckPrimeOptions, - callback: (err: Error | null, result: boolean) => void, - ): void; - /** - * Checks the primality of the `candidate`. - * @since v15.8.0 - * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. - * @return `true` if the candidate is a prime with an error probability less than `0.25 ** options.checks`. - */ - function checkPrimeSync(candidate: LargeNumberLike, options?: CheckPrimeOptions): boolean; - /** - * Load and set the `engine` for some or all OpenSSL functions (selected by flags). - * - * `engine` could be either an id or a path to the engine's shared library. - * - * The optional `flags` argument uses `ENGINE_METHOD_ALL` by default. The `flags`is a bit field taking one of or a mix of the following flags (defined in`crypto.constants`): - * - * * `crypto.constants.ENGINE_METHOD_RSA` - * * `crypto.constants.ENGINE_METHOD_DSA` - * * `crypto.constants.ENGINE_METHOD_DH` - * * `crypto.constants.ENGINE_METHOD_RAND` - * * `crypto.constants.ENGINE_METHOD_EC` - * * `crypto.constants.ENGINE_METHOD_CIPHERS` - * * `crypto.constants.ENGINE_METHOD_DIGESTS` - * * `crypto.constants.ENGINE_METHOD_PKEY_METHS` - * * `crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS` - * * `crypto.constants.ENGINE_METHOD_ALL` - * * `crypto.constants.ENGINE_METHOD_NONE` - * @since v0.11.11 - * @param flags - */ - function setEngine(engine: string, flags?: number): void; - /** - * A convenient alias for {@link webcrypto.getRandomValues}. This - * implementation is not compliant with the Web Crypto spec, to write - * web-compatible code use {@link webcrypto.getRandomValues} instead. - * @since v17.4.0 - * @return Returns `typedArray`. - */ - function getRandomValues(typedArray: T): T; - /** - * A convenient alias for `crypto.webcrypto.subtle`. - * @since v17.4.0 - */ - const subtle: webcrypto.SubtleCrypto; - /** - * An implementation of the Web Crypto API standard. - * - * See the {@link https://nodejs.org/docs/latest/api/webcrypto.html Web Crypto API documentation} for details. - * @since v15.0.0 - */ - const webcrypto: webcrypto.Crypto; - namespace webcrypto { - type BufferSource = ArrayBufferView | ArrayBuffer; - type KeyFormat = "jwk" | "pkcs8" | "raw" | "spki"; - type KeyType = "private" | "public" | "secret"; - type KeyUsage = - | "decrypt" - | "deriveBits" - | "deriveKey" - | "encrypt" - | "sign" - | "unwrapKey" - | "verify" - | "wrapKey"; - type AlgorithmIdentifier = Algorithm | string; - type HashAlgorithmIdentifier = AlgorithmIdentifier; - type NamedCurve = string; - type BigInteger = Uint8Array; - interface AesCbcParams extends Algorithm { - iv: BufferSource; - } - interface AesCtrParams extends Algorithm { - counter: BufferSource; - length: number; - } - interface AesDerivedKeyParams extends Algorithm { - length: number; - } - interface AesGcmParams extends Algorithm { - additionalData?: BufferSource; - iv: BufferSource; - tagLength?: number; - } - interface AesKeyAlgorithm extends KeyAlgorithm { - length: number; - } - interface AesKeyGenParams extends Algorithm { - length: number; - } - interface Algorithm { - name: string; - } - interface EcKeyAlgorithm extends KeyAlgorithm { - namedCurve: NamedCurve; - } - interface EcKeyGenParams extends Algorithm { - namedCurve: NamedCurve; - } - interface EcKeyImportParams extends Algorithm { - namedCurve: NamedCurve; - } - interface EcdhKeyDeriveParams extends Algorithm { - public: CryptoKey; - } - interface EcdsaParams extends Algorithm { - hash: HashAlgorithmIdentifier; - } - interface Ed448Params extends Algorithm { - context?: BufferSource; - } - interface HkdfParams extends Algorithm { - hash: HashAlgorithmIdentifier; - info: BufferSource; - salt: BufferSource; - } - interface HmacImportParams extends Algorithm { - hash: HashAlgorithmIdentifier; - length?: number; - } - interface HmacKeyAlgorithm extends KeyAlgorithm { - hash: KeyAlgorithm; - length: number; - } - interface HmacKeyGenParams extends Algorithm { - hash: HashAlgorithmIdentifier; - length?: number; - } - interface JsonWebKey { - alg?: string; - crv?: string; - d?: string; - dp?: string; - dq?: string; - e?: string; - ext?: boolean; - k?: string; - key_ops?: string[]; - kty?: string; - n?: string; - oth?: RsaOtherPrimesInfo[]; - p?: string; - q?: string; - qi?: string; - use?: string; - x?: string; - y?: string; - } - interface KeyAlgorithm { - name: string; - } - interface Pbkdf2Params extends Algorithm { - hash: HashAlgorithmIdentifier; - iterations: number; - salt: BufferSource; - } - interface RsaHashedImportParams extends Algorithm { - hash: HashAlgorithmIdentifier; - } - interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { - hash: KeyAlgorithm; - } - interface RsaHashedKeyGenParams extends RsaKeyGenParams { - hash: HashAlgorithmIdentifier; - } - interface RsaKeyAlgorithm extends KeyAlgorithm { - modulusLength: number; - publicExponent: BigInteger; - } - interface RsaKeyGenParams extends Algorithm { - modulusLength: number; - publicExponent: BigInteger; - } - interface RsaOaepParams extends Algorithm { - label?: BufferSource; - } - interface RsaOtherPrimesInfo { - d?: string; - r?: string; - t?: string; - } - interface RsaPssParams extends Algorithm { - saltLength: number; - } - /** - * Calling `require('node:crypto').webcrypto` returns an instance of the `Crypto` class. - * `Crypto` is a singleton that provides access to the remainder of the crypto API. - * @since v15.0.0 - */ - interface Crypto { - /** - * Provides access to the `SubtleCrypto` API. - * @since v15.0.0 - */ - readonly subtle: SubtleCrypto; - /** - * Generates cryptographically strong random values. - * The given `typedArray` is filled with random values, and a reference to `typedArray` is returned. - * - * The given `typedArray` must be an integer-based instance of {@link NodeJS.TypedArray}, i.e. `Float32Array` and `Float64Array` are not accepted. - * - * An error will be thrown if the given `typedArray` is larger than 65,536 bytes. - * @since v15.0.0 - */ - getRandomValues>(typedArray: T): T; - /** - * Generates a random {@link https://www.rfc-editor.org/rfc/rfc4122.txt RFC 4122} version 4 UUID. - * The UUID is generated using a cryptographic pseudorandom number generator. - * @since v16.7.0 - */ - randomUUID(): string; - CryptoKey: CryptoKeyConstructor; - } - // This constructor throws ILLEGAL_CONSTRUCTOR so it should not be newable. - interface CryptoKeyConstructor { - /** Illegal constructor */ - (_: { readonly _: unique symbol }): never; // Allows instanceof to work but not be callable by the user. - readonly length: 0; - readonly name: "CryptoKey"; - readonly prototype: CryptoKey; - } - /** - * @since v15.0.0 - */ - interface CryptoKey { - /** - * An object detailing the algorithm for which the key can be used along with additional algorithm-specific parameters. - * @since v15.0.0 - */ - readonly algorithm: KeyAlgorithm; - /** - * When `true`, the {@link CryptoKey} can be extracted using either `subtleCrypto.exportKey()` or `subtleCrypto.wrapKey()`. - * @since v15.0.0 - */ - readonly extractable: boolean; - /** - * A string identifying whether the key is a symmetric (`'secret'`) or asymmetric (`'private'` or `'public'`) key. - * @since v15.0.0 - */ - readonly type: KeyType; - /** - * An array of strings identifying the operations for which the key may be used. - * - * The possible usages are: - * - `'encrypt'` - The key may be used to encrypt data. - * - `'decrypt'` - The key may be used to decrypt data. - * - `'sign'` - The key may be used to generate digital signatures. - * - `'verify'` - The key may be used to verify digital signatures. - * - `'deriveKey'` - The key may be used to derive a new key. - * - `'deriveBits'` - The key may be used to derive bits. - * - `'wrapKey'` - The key may be used to wrap another key. - * - `'unwrapKey'` - The key may be used to unwrap another key. - * - * Valid key usages depend on the key algorithm (identified by `cryptokey.algorithm.name`). - * @since v15.0.0 - */ - readonly usages: KeyUsage[]; - } - /** - * The `CryptoKeyPair` is a simple dictionary object with `publicKey` and `privateKey` properties, representing an asymmetric key pair. - * @since v15.0.0 - */ - interface CryptoKeyPair { - /** - * A {@link CryptoKey} whose type will be `'private'`. - * @since v15.0.0 - */ - privateKey: CryptoKey; - /** - * A {@link CryptoKey} whose type will be `'public'`. - * @since v15.0.0 - */ - publicKey: CryptoKey; - } - /** - * @since v15.0.0 - */ - interface SubtleCrypto { - /** - * Using the method and parameters specified in `algorithm` and the keying material provided by `key`, - * `subtle.decrypt()` attempts to decipher the provided `data`. If successful, - * the returned promise will be resolved with an `` containing the plaintext result. - * - * The algorithms currently supported include: - * - * - `'RSA-OAEP'` - * - `'AES-CTR'` - * - `'AES-CBC'` - * - `'AES-GCM'` - * @since v15.0.0 - */ - decrypt( - algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, - key: CryptoKey, - data: BufferSource, - ): Promise; - /** - * Using the method and parameters specified in `algorithm` and the keying material provided by `baseKey`, - * `subtle.deriveBits()` attempts to generate `length` bits. - * The Node.js implementation requires that when `length` is a number it must be multiple of `8`. - * When `length` is `null` the maximum number of bits for a given algorithm is generated. This is allowed - * for the `'ECDH'`, `'X25519'`, and `'X448'` algorithms. - * If successful, the returned promise will be resolved with an `` containing the generated data. - * - * The algorithms currently supported include: - * - * - `'ECDH'` - * - `'X25519'` - * - `'X448'` - * - `'HKDF'` - * - `'PBKDF2'` - * @since v15.0.0 - */ - deriveBits(algorithm: EcdhKeyDeriveParams, baseKey: CryptoKey, length: number | null): Promise; - deriveBits( - algorithm: AlgorithmIdentifier | HkdfParams | Pbkdf2Params, - baseKey: CryptoKey, - length: number, - ): Promise; - /** - * Using the method and parameters specified in `algorithm`, and the keying material provided by `baseKey`, - * `subtle.deriveKey()` attempts to generate a new ` based on the method and parameters in `derivedKeyAlgorithm`. - * - * Calling `subtle.deriveKey()` is equivalent to calling `subtle.deriveBits()` to generate raw keying material, - * then passing the result into the `subtle.importKey()` method using the `deriveKeyAlgorithm`, `extractable`, and `keyUsages` parameters as input. - * - * The algorithms currently supported include: - * - * - `'ECDH'` - * - `'X25519'` - * - `'X448'` - * - `'HKDF'` - * - `'PBKDF2'` - * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. - * @since v15.0.0 - */ - deriveKey( - algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, - baseKey: CryptoKey, - derivedKeyAlgorithm: - | AlgorithmIdentifier - | AesDerivedKeyParams - | HmacImportParams - | HkdfParams - | Pbkdf2Params, - extractable: boolean, - keyUsages: readonly KeyUsage[], - ): Promise; - /** - * Using the method identified by `algorithm`, `subtle.digest()` attempts to generate a digest of `data`. - * If successful, the returned promise is resolved with an `` containing the computed digest. - * - * If `algorithm` is provided as a ``, it must be one of: - * - * - `'SHA-1'` - * - `'SHA-256'` - * - `'SHA-384'` - * - `'SHA-512'` - * - * If `algorithm` is provided as an ``, it must have a `name` property whose value is one of the above. - * @since v15.0.0 - */ - digest(algorithm: AlgorithmIdentifier, data: BufferSource): Promise; - /** - * Using the method and parameters specified by `algorithm` and the keying material provided by `key`, - * `subtle.encrypt()` attempts to encipher `data`. If successful, - * the returned promise is resolved with an `` containing the encrypted result. - * - * The algorithms currently supported include: - * - * - `'RSA-OAEP'` - * - `'AES-CTR'` - * - `'AES-CBC'` - * - `'AES-GCM'` - * @since v15.0.0 - */ - encrypt( - algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, - key: CryptoKey, - data: BufferSource, - ): Promise; - /** - * Exports the given key into the specified format, if supported. - * - * If the `` is not extractable, the returned promise will reject. - * - * When `format` is either `'pkcs8'` or `'spki'` and the export is successful, - * the returned promise will be resolved with an `` containing the exported key data. - * - * When `format` is `'jwk'` and the export is successful, the returned promise will be resolved with a - * JavaScript object conforming to the {@link https://tools.ietf.org/html/rfc7517 JSON Web Key} specification. - * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. - * @returns `` containing ``. - * @since v15.0.0 - */ - exportKey(format: "jwk", key: CryptoKey): Promise; - exportKey(format: Exclude, key: CryptoKey): Promise; - /** - * Using the method and parameters provided in `algorithm`, - * `subtle.generateKey()` attempts to generate new keying material. - * Depending the method used, the method may generate either a single `` or a ``. - * - * The `` (public and private key) generating algorithms supported include: - * - * - `'RSASSA-PKCS1-v1_5'` - * - `'RSA-PSS'` - * - `'RSA-OAEP'` - * - `'ECDSA'` - * - `'Ed25519'` - * - `'Ed448'` - * - `'ECDH'` - * - `'X25519'` - * - `'X448'` - * The `` (secret key) generating algorithms supported include: - * - * - `'HMAC'` - * - `'AES-CTR'` - * - `'AES-CBC'` - * - `'AES-GCM'` - * - `'AES-KW'` - * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. - * @since v15.0.0 - */ - generateKey( - algorithm: RsaHashedKeyGenParams | EcKeyGenParams, - extractable: boolean, - keyUsages: readonly KeyUsage[], - ): Promise; - generateKey( - algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, - extractable: boolean, - keyUsages: readonly KeyUsage[], - ): Promise; - generateKey( - algorithm: AlgorithmIdentifier, - extractable: boolean, - keyUsages: KeyUsage[], - ): Promise; - /** - * The `subtle.importKey()` method attempts to interpret the provided `keyData` as the given `format` - * to create a `` instance using the provided `algorithm`, `extractable`, and `keyUsages` arguments. - * If the import is successful, the returned promise will be resolved with the created ``. - * - * If importing a `'PBKDF2'` key, `extractable` must be `false`. - * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. - * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. - * @since v15.0.0 - */ - importKey( - format: "jwk", - keyData: JsonWebKey, - algorithm: - | AlgorithmIdentifier - | RsaHashedImportParams - | EcKeyImportParams - | HmacImportParams - | AesKeyAlgorithm, - extractable: boolean, - keyUsages: readonly KeyUsage[], - ): Promise; - importKey( - format: Exclude, - keyData: BufferSource, - algorithm: - | AlgorithmIdentifier - | RsaHashedImportParams - | EcKeyImportParams - | HmacImportParams - | AesKeyAlgorithm, - extractable: boolean, - keyUsages: KeyUsage[], - ): Promise; - /** - * Using the method and parameters given by `algorithm` and the keying material provided by `key`, - * `subtle.sign()` attempts to generate a cryptographic signature of `data`. If successful, - * the returned promise is resolved with an `` containing the generated signature. - * - * The algorithms currently supported include: - * - * - `'RSASSA-PKCS1-v1_5'` - * - `'RSA-PSS'` - * - `'ECDSA'` - * - `'Ed25519'` - * - `'Ed448'` - * - `'HMAC'` - * @since v15.0.0 - */ - sign( - algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | Ed448Params, - key: CryptoKey, - data: BufferSource, - ): Promise; - /** - * In cryptography, "wrapping a key" refers to exporting and then encrypting the keying material. - * The `subtle.unwrapKey()` method attempts to decrypt a wrapped key and create a `` instance. - * It is equivalent to calling `subtle.decrypt()` first on the encrypted key data (using the `wrappedKey`, `unwrapAlgo`, and `unwrappingKey` arguments as input) - * then passing the results in to the `subtle.importKey()` method using the `unwrappedKeyAlgo`, `extractable`, and `keyUsages` arguments as inputs. - * If successful, the returned promise is resolved with a `` object. - * - * The wrapping algorithms currently supported include: - * - * - `'RSA-OAEP'` - * - `'AES-CTR'` - * - `'AES-CBC'` - * - `'AES-GCM'` - * - `'AES-KW'` - * - * The unwrapped key algorithms supported include: - * - * - `'RSASSA-PKCS1-v1_5'` - * - `'RSA-PSS'` - * - `'RSA-OAEP'` - * - `'ECDSA'` - * - `'Ed25519'` - * - `'Ed448'` - * - `'ECDH'` - * - `'X25519'` - * - `'X448'` - * - `'HMAC'` - * - `'AES-CTR'` - * - `'AES-CBC'` - * - `'AES-GCM'` - * - `'AES-KW'` - * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. - * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. - * @since v15.0.0 - */ - unwrapKey( - format: KeyFormat, - wrappedKey: BufferSource, - unwrappingKey: CryptoKey, - unwrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, - unwrappedKeyAlgorithm: - | AlgorithmIdentifier - | RsaHashedImportParams - | EcKeyImportParams - | HmacImportParams - | AesKeyAlgorithm, - extractable: boolean, - keyUsages: KeyUsage[], - ): Promise; - /** - * Using the method and parameters given in `algorithm` and the keying material provided by `key`, - * `subtle.verify()` attempts to verify that `signature` is a valid cryptographic signature of `data`. - * The returned promise is resolved with either `true` or `false`. - * - * The algorithms currently supported include: - * - * - `'RSASSA-PKCS1-v1_5'` - * - `'RSA-PSS'` - * - `'ECDSA'` - * - `'Ed25519'` - * - `'Ed448'` - * - `'HMAC'` - * @since v15.0.0 - */ - verify( - algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | Ed448Params, - key: CryptoKey, - signature: BufferSource, - data: BufferSource, - ): Promise; - /** - * In cryptography, "wrapping a key" refers to exporting and then encrypting the keying material. - * The `subtle.wrapKey()` method exports the keying material into the format identified by `format`, - * then encrypts it using the method and parameters specified by `wrapAlgo` and the keying material provided by `wrappingKey`. - * It is the equivalent to calling `subtle.exportKey()` using `format` and `key` as the arguments, - * then passing the result to the `subtle.encrypt()` method using `wrappingKey` and `wrapAlgo` as inputs. - * If successful, the returned promise will be resolved with an `` containing the encrypted key data. - * - * The wrapping algorithms currently supported include: - * - * - `'RSA-OAEP'` - * - `'AES-CTR'` - * - `'AES-CBC'` - * - `'AES-GCM'` - * - `'AES-KW'` - * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. - * @since v15.0.0 - */ - wrapKey( - format: KeyFormat, - key: CryptoKey, - wrappingKey: CryptoKey, - wrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, - ): Promise; - } - } -} -declare module "node:crypto" { - export * from "crypto"; -} diff --git a/node_modules/@types/node/ts4.8/dgram.d.ts b/node_modules/@types/node/ts4.8/dgram.d.ts deleted file mode 100644 index 0b86ae735a285305d46132651ad38c7cdea67d09..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/dgram.d.ts +++ /dev/null @@ -1,596 +0,0 @@ -/** - * The `node:dgram` module provides an implementation of UDP datagram sockets. - * - * ```js - * import dgram from 'node:dgram'; - * - * const server = dgram.createSocket('udp4'); - * - * server.on('error', (err) => { - * console.error(`server error:\n${err.stack}`); - * server.close(); - * }); - * - * server.on('message', (msg, rinfo) => { - * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); - * }); - * - * server.on('listening', () => { - * const address = server.address(); - * console.log(`server listening ${address.address}:${address.port}`); - * }); - * - * server.bind(41234); - * // Prints: server listening 0.0.0.0:41234 - * ``` - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/dgram.js) - */ -declare module "dgram" { - import { AddressInfo } from "node:net"; - import * as dns from "node:dns"; - import { Abortable, EventEmitter } from "node:events"; - interface RemoteInfo { - address: string; - family: "IPv4" | "IPv6"; - port: number; - size: number; - } - interface BindOptions { - port?: number | undefined; - address?: string | undefined; - exclusive?: boolean | undefined; - fd?: number | undefined; - } - type SocketType = "udp4" | "udp6"; - interface SocketOptions extends Abortable { - type: SocketType; - reuseAddr?: boolean | undefined; - /** - * @default false - */ - ipv6Only?: boolean | undefined; - recvBufferSize?: number | undefined; - sendBufferSize?: number | undefined; - lookup?: - | (( - hostname: string, - options: dns.LookupOneOptions, - callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, - ) => void) - | undefined; - } - /** - * Creates a `dgram.Socket` object. Once the socket is created, calling `socket.bind()` will instruct the socket to begin listening for datagram - * messages. When `address` and `port` are not passed to `socket.bind()` the - * method will bind the socket to the "all interfaces" address on a random port - * (it does the right thing for both `udp4` and `udp6` sockets). The bound address - * and port can be retrieved using `socket.address().address` and `socket.address().port`. - * - * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.close()` on the socket: - * - * ```js - * const controller = new AbortController(); - * const { signal } = controller; - * const server = dgram.createSocket({ type: 'udp4', signal }); - * server.on('message', (msg, rinfo) => { - * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); - * }); - * // Later, when you want to close the server. - * controller.abort(); - * ``` - * @since v0.11.13 - * @param options Available options are: - * @param callback Attached as a listener for `'message'` events. Optional. - */ - function createSocket(type: SocketType, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; - function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; - /** - * Encapsulates the datagram functionality. - * - * New instances of `dgram.Socket` are created using {@link createSocket}. - * The `new` keyword is not to be used to create `dgram.Socket` instances. - * @since v0.1.99 - */ - class Socket extends EventEmitter { - /** - * Tells the kernel to join a multicast group at the given `multicastAddress` and`multicastInterface` using the `IP_ADD_MEMBERSHIP` socket option. If the`multicastInterface` argument is not - * specified, the operating system will choose - * one interface and will add membership to it. To add membership to every - * available interface, call `addMembership` multiple times, once per interface. - * - * When called on an unbound socket, this method will implicitly bind to a random - * port, listening on all interfaces. - * - * When sharing a UDP socket across multiple `cluster` workers, the`socket.addMembership()` function must be called only once or an`EADDRINUSE` error will occur: - * - * ```js - * import cluster from 'node:cluster'; - * import dgram from 'node:dgram'; - * - * if (cluster.isPrimary) { - * cluster.fork(); // Works ok. - * cluster.fork(); // Fails with EADDRINUSE. - * } else { - * const s = dgram.createSocket('udp4'); - * s.bind(1234, () => { - * s.addMembership('224.0.0.114'); - * }); - * } - * ``` - * @since v0.6.9 - */ - addMembership(multicastAddress: string, multicastInterface?: string): void; - /** - * Returns an object containing the address information for a socket. - * For UDP sockets, this object will contain `address`, `family`, and `port`properties. - * - * This method throws `EBADF` if called on an unbound socket. - * @since v0.1.99 - */ - address(): AddressInfo; - /** - * For UDP sockets, causes the `dgram.Socket` to listen for datagram - * messages on a named `port` and optional `address`. If `port` is not - * specified or is `0`, the operating system will attempt to bind to a - * random port. If `address` is not specified, the operating system will - * attempt to listen on all addresses. Once binding is complete, a`'listening'` event is emitted and the optional `callback` function is - * called. - * - * Specifying both a `'listening'` event listener and passing a`callback` to the `socket.bind()` method is not harmful but not very - * useful. - * - * A bound datagram socket keeps the Node.js process running to receive - * datagram messages. - * - * If binding fails, an `'error'` event is generated. In rare case (e.g. - * attempting to bind with a closed socket), an `Error` may be thrown. - * - * Example of a UDP server listening on port 41234: - * - * ```js - * import dgram from 'node:dgram'; - * - * const server = dgram.createSocket('udp4'); - * - * server.on('error', (err) => { - * console.error(`server error:\n${err.stack}`); - * server.close(); - * }); - * - * server.on('message', (msg, rinfo) => { - * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); - * }); - * - * server.on('listening', () => { - * const address = server.address(); - * console.log(`server listening ${address.address}:${address.port}`); - * }); - * - * server.bind(41234); - * // Prints: server listening 0.0.0.0:41234 - * ``` - * @since v0.1.99 - * @param callback with no parameters. Called when binding is complete. - */ - bind(port?: number, address?: string, callback?: () => void): this; - bind(port?: number, callback?: () => void): this; - bind(callback?: () => void): this; - bind(options: BindOptions, callback?: () => void): this; - /** - * Close the underlying socket and stop listening for data on it. If a callback is - * provided, it is added as a listener for the `'close'` event. - * @since v0.1.99 - * @param callback Called when the socket has been closed. - */ - close(callback?: () => void): this; - /** - * Associates the `dgram.Socket` to a remote address and port. Every - * message sent by this handle is automatically sent to that destination. Also, - * the socket will only receive messages from that remote peer. - * Trying to call `connect()` on an already connected socket will result - * in an `ERR_SOCKET_DGRAM_IS_CONNECTED` exception. If `address` is not - * provided, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets) - * will be used by default. Once the connection is complete, a `'connect'` event - * is emitted and the optional `callback` function is called. In case of failure, - * the `callback` is called or, failing this, an `'error'` event is emitted. - * @since v12.0.0 - * @param callback Called when the connection is completed or on error. - */ - connect(port: number, address?: string, callback?: () => void): void; - connect(port: number, callback: () => void): void; - /** - * A synchronous function that disassociates a connected `dgram.Socket` from - * its remote address. Trying to call `disconnect()` on an unbound or already - * disconnected socket will result in an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception. - * @since v12.0.0 - */ - disconnect(): void; - /** - * Instructs the kernel to leave a multicast group at `multicastAddress` using the`IP_DROP_MEMBERSHIP` socket option. This method is automatically called by the - * kernel when the socket is closed or the process terminates, so most apps will - * never have reason to call this. - * - * If `multicastInterface` is not specified, the operating system will attempt to - * drop membership on all valid interfaces. - * @since v0.6.9 - */ - dropMembership(multicastAddress: string, multicastInterface?: string): void; - /** - * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. - * @since v8.7.0 - * @return the `SO_RCVBUF` socket receive buffer size in bytes. - */ - getRecvBufferSize(): number; - /** - * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. - * @since v8.7.0 - * @return the `SO_SNDBUF` socket send buffer size in bytes. - */ - getSendBufferSize(): number; - /** - * @since v18.8.0, v16.19.0 - * @return Number of bytes queued for sending. - */ - getSendQueueSize(): number; - /** - * @since v18.8.0, v16.19.0 - * @return Number of send requests currently in the queue awaiting to be processed. - */ - getSendQueueCount(): number; - /** - * By default, binding a socket will cause it to block the Node.js process from - * exiting as long as the socket is open. The `socket.unref()` method can be used - * to exclude the socket from the reference counting that keeps the Node.js - * process active. The `socket.ref()` method adds the socket back to the reference - * counting and restores the default behavior. - * - * Calling `socket.ref()` multiples times will have no additional effect. - * - * The `socket.ref()` method returns a reference to the socket so calls can be - * chained. - * @since v0.9.1 - */ - ref(): this; - /** - * Returns an object containing the `address`, `family`, and `port` of the remote - * endpoint. This method throws an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception - * if the socket is not connected. - * @since v12.0.0 - */ - remoteAddress(): AddressInfo; - /** - * Broadcasts a datagram on the socket. - * For connectionless sockets, the destination `port` and `address` must be - * specified. Connected sockets, on the other hand, will use their associated - * remote endpoint, so the `port` and `address` arguments must not be set. - * - * The `msg` argument contains the message to be sent. - * Depending on its type, different behavior can apply. If `msg` is a `Buffer`, - * any `TypedArray` or a `DataView`, - * the `offset` and `length` specify the offset within the `Buffer` where the - * message begins and the number of bytes in the message, respectively. - * If `msg` is a `String`, then it is automatically converted to a `Buffer`with `'utf8'` encoding. With messages that - * contain multi-byte characters, `offset` and `length` will be calculated with - * respect to `byte length` and not the character position. - * If `msg` is an array, `offset` and `length` must not be specified. - * - * The `address` argument is a string. If the value of `address` is a host name, - * DNS will be used to resolve the address of the host. If `address` is not - * provided or otherwise nullish, `'127.0.0.1'` (for `udp4` sockets) or `'::1'`(for `udp6` sockets) will be used by default. - * - * If the socket has not been previously bound with a call to `bind`, the socket - * is assigned a random port number and is bound to the "all interfaces" address - * (`'0.0.0.0'` for `udp4` sockets, `'::0'` for `udp6` sockets.) - * - * An optional `callback` function may be specified to as a way of reporting - * DNS errors or for determining when it is safe to reuse the `buf` object. - * DNS lookups delay the time to send for at least one tick of the - * Node.js event loop. - * - * The only way to know for sure that the datagram has been sent is by using a`callback`. If an error occurs and a `callback` is given, the error will be - * passed as the first argument to the `callback`. If a `callback` is not given, - * the error is emitted as an `'error'` event on the `socket` object. - * - * Offset and length are optional but both _must_ be set if either are used. - * They are supported only when the first argument is a `Buffer`, a `TypedArray`, - * or a `DataView`. - * - * This method throws `ERR_SOCKET_BAD_PORT` if called on an unbound socket. - * - * Example of sending a UDP packet to a port on `localhost`; - * - * ```js - * import dgram from 'node:dgram'; - * import { Buffer } from 'node:buffer'; - * - * const message = Buffer.from('Some bytes'); - * const client = dgram.createSocket('udp4'); - * client.send(message, 41234, 'localhost', (err) => { - * client.close(); - * }); - * ``` - * - * Example of sending a UDP packet composed of multiple buffers to a port on`127.0.0.1`; - * - * ```js - * import dgram from 'node:dgram'; - * import { Buffer } from 'node:buffer'; - * - * const buf1 = Buffer.from('Some '); - * const buf2 = Buffer.from('bytes'); - * const client = dgram.createSocket('udp4'); - * client.send([buf1, buf2], 41234, (err) => { - * client.close(); - * }); - * ``` - * - * Sending multiple buffers might be faster or slower depending on the - * application and operating system. Run benchmarks to - * determine the optimal strategy on a case-by-case basis. Generally speaking, - * however, sending multiple buffers is faster. - * - * Example of sending a UDP packet using a socket connected to a port on`localhost`: - * - * ```js - * import dgram from 'node:dgram'; - * import { Buffer } from 'node:buffer'; - * - * const message = Buffer.from('Some bytes'); - * const client = dgram.createSocket('udp4'); - * client.connect(41234, 'localhost', (err) => { - * client.send(message, (err) => { - * client.close(); - * }); - * }); - * ``` - * @since v0.1.99 - * @param msg Message to be sent. - * @param offset Offset in the buffer where the message starts. - * @param length Number of bytes in the message. - * @param port Destination port. - * @param address Destination host name or IP address. - * @param callback Called when the message has been sent. - */ - send( - msg: string | Uint8Array | readonly any[], - port?: number, - address?: string, - callback?: (error: Error | null, bytes: number) => void, - ): void; - send( - msg: string | Uint8Array | readonly any[], - port?: number, - callback?: (error: Error | null, bytes: number) => void, - ): void; - send( - msg: string | Uint8Array | readonly any[], - callback?: (error: Error | null, bytes: number) => void, - ): void; - send( - msg: string | Uint8Array, - offset: number, - length: number, - port?: number, - address?: string, - callback?: (error: Error | null, bytes: number) => void, - ): void; - send( - msg: string | Uint8Array, - offset: number, - length: number, - port?: number, - callback?: (error: Error | null, bytes: number) => void, - ): void; - send( - msg: string | Uint8Array, - offset: number, - length: number, - callback?: (error: Error | null, bytes: number) => void, - ): void; - /** - * Sets or clears the `SO_BROADCAST` socket option. When set to `true`, UDP - * packets may be sent to a local interface's broadcast address. - * - * This method throws `EBADF` if called on an unbound socket. - * @since v0.6.9 - */ - setBroadcast(flag: boolean): void; - /** - * _All references to scope in this section are referring to [IPv6 Zone Indices](https://en.wikipedia.org/wiki/IPv6_address#Scoped_literal_IPv6_addresses), which are defined by [RFC - * 4007](https://tools.ietf.org/html/rfc4007). In string form, an IP_ - * _with a scope index is written as `'IP%scope'` where scope is an interface name_ - * _or interface number._ - * - * Sets the default outgoing multicast interface of the socket to a chosen - * interface or back to system interface selection. The `multicastInterface` must - * be a valid string representation of an IP from the socket's family. - * - * For IPv4 sockets, this should be the IP configured for the desired physical - * interface. All packets sent to multicast on the socket will be sent on the - * interface determined by the most recent successful use of this call. - * - * For IPv6 sockets, `multicastInterface` should include a scope to indicate the - * interface as in the examples that follow. In IPv6, individual `send` calls can - * also use explicit scope in addresses, so only packets sent to a multicast - * address without specifying an explicit scope are affected by the most recent - * successful use of this call. - * - * This method throws `EBADF` if called on an unbound socket. - * - * #### Example: IPv6 outgoing multicast interface - * - * On most systems, where scope format uses the interface name: - * - * ```js - * const socket = dgram.createSocket('udp6'); - * - * socket.bind(1234, () => { - * socket.setMulticastInterface('::%eth1'); - * }); - * ``` - * - * On Windows, where scope format uses an interface number: - * - * ```js - * const socket = dgram.createSocket('udp6'); - * - * socket.bind(1234, () => { - * socket.setMulticastInterface('::%2'); - * }); - * ``` - * - * #### Example: IPv4 outgoing multicast interface - * - * All systems use an IP of the host on the desired physical interface: - * - * ```js - * const socket = dgram.createSocket('udp4'); - * - * socket.bind(1234, () => { - * socket.setMulticastInterface('10.0.0.2'); - * }); - * ``` - * @since v8.6.0 - */ - setMulticastInterface(multicastInterface: string): void; - /** - * Sets or clears the `IP_MULTICAST_LOOP` socket option. When set to `true`, - * multicast packets will also be received on the local interface. - * - * This method throws `EBADF` if called on an unbound socket. - * @since v0.3.8 - */ - setMulticastLoopback(flag: boolean): boolean; - /** - * Sets the `IP_MULTICAST_TTL` socket option. While TTL generally stands for - * "Time to Live", in this context it specifies the number of IP hops that a - * packet is allowed to travel through, specifically for multicast traffic. Each - * router or gateway that forwards a packet decrements the TTL. If the TTL is - * decremented to 0 by a router, it will not be forwarded. - * - * The `ttl` argument may be between 0 and 255\. The default on most systems is `1`. - * - * This method throws `EBADF` if called on an unbound socket. - * @since v0.3.8 - */ - setMulticastTTL(ttl: number): number; - /** - * Sets the `SO_RCVBUF` socket option. Sets the maximum socket receive buffer - * in bytes. - * - * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. - * @since v8.7.0 - */ - setRecvBufferSize(size: number): void; - /** - * Sets the `SO_SNDBUF` socket option. Sets the maximum socket send buffer - * in bytes. - * - * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. - * @since v8.7.0 - */ - setSendBufferSize(size: number): void; - /** - * Sets the `IP_TTL` socket option. While TTL generally stands for "Time to Live", - * in this context it specifies the number of IP hops that a packet is allowed to - * travel through. Each router or gateway that forwards a packet decrements the - * TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. - * Changing TTL values is typically done for network probes or when multicasting. - * - * The `ttl` argument may be between 1 and 255\. The default on most systems - * is 64. - * - * This method throws `EBADF` if called on an unbound socket. - * @since v0.1.101 - */ - setTTL(ttl: number): number; - /** - * By default, binding a socket will cause it to block the Node.js process from - * exiting as long as the socket is open. The `socket.unref()` method can be used - * to exclude the socket from the reference counting that keeps the Node.js - * process active, allowing the process to exit even if the socket is still - * listening. - * - * Calling `socket.unref()` multiple times will have no additional effect. - * - * The `socket.unref()` method returns a reference to the socket so calls can be - * chained. - * @since v0.9.1 - */ - unref(): this; - /** - * Tells the kernel to join a source-specific multicast channel at the given`sourceAddress` and `groupAddress`, using the `multicastInterface` with the`IP_ADD_SOURCE_MEMBERSHIP` socket - * option. If the `multicastInterface` argument - * is not specified, the operating system will choose one interface and will add - * membership to it. To add membership to every available interface, call`socket.addSourceSpecificMembership()` multiple times, once per interface. - * - * When called on an unbound socket, this method will implicitly bind to a random - * port, listening on all interfaces. - * @since v13.1.0, v12.16.0 - */ - addSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; - /** - * Instructs the kernel to leave a source-specific multicast channel at the given`sourceAddress` and `groupAddress` using the `IP_DROP_SOURCE_MEMBERSHIP`socket option. This method is - * automatically called by the kernel when the - * socket is closed or the process terminates, so most apps will never have - * reason to call this. - * - * If `multicastInterface` is not specified, the operating system will attempt to - * drop membership on all valid interfaces. - * @since v13.1.0, v12.16.0 - */ - dropSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; - /** - * events.EventEmitter - * 1. close - * 2. connect - * 3. error - * 4. listening - * 5. message - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "connect", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "listening", listener: () => void): this; - addListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "connect"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "listening"): boolean; - emit(event: "message", msg: Buffer, rinfo: RemoteInfo): boolean; - on(event: string, listener: (...args: any[]) => void): this; - on(event: "close", listener: () => void): this; - on(event: "connect", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "listening", listener: () => void): this; - on(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; - once(event: string, listener: (...args: any[]) => void): this; - once(event: "close", listener: () => void): this; - once(event: "connect", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "listening", listener: () => void): this; - once(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "connect", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "listening", listener: () => void): this; - prependListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "connect", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "listening", listener: () => void): this; - prependOnceListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; - /** - * Calls `socket.close()` and returns a promise that fulfills when the socket has closed. - * @since v20.5.0 - */ - [Symbol.asyncDispose](): Promise; - } -} -declare module "node:dgram" { - export * from "dgram"; -} diff --git a/node_modules/@types/node/ts4.8/diagnostics_channel.d.ts b/node_modules/@types/node/ts4.8/diagnostics_channel.d.ts deleted file mode 100644 index cd4bd71b365a1f4ed4c3f851eb3624a7eb3843b9..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/diagnostics_channel.d.ts +++ /dev/null @@ -1,545 +0,0 @@ -/** - * The `node:diagnostics_channel` module provides an API to create named channels - * to report arbitrary message data for diagnostics purposes. - * - * It can be accessed using: - * - * ```js - * import diagnostics_channel from 'node:diagnostics_channel'; - * ``` - * - * It is intended that a module writer wanting to report diagnostics messages - * will create one or many top-level channels to report messages through. - * Channels may also be acquired at runtime but it is not encouraged - * due to the additional overhead of doing so. Channels may be exported for - * convenience, but as long as the name is known it can be acquired anywhere. - * - * If you intend for your module to produce diagnostics data for others to - * consume it is recommended that you include documentation of what named - * channels are used along with the shape of the message data. Channel names - * should generally include the module name to avoid collisions with data from - * other modules. - * @since v15.1.0, v14.17.0 - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/diagnostics_channel.js) - */ -declare module "diagnostics_channel" { - import { AsyncLocalStorage } from "node:async_hooks"; - /** - * Check if there are active subscribers to the named channel. This is helpful if - * the message you want to send might be expensive to prepare. - * - * This API is optional but helpful when trying to publish messages from very - * performance-sensitive code. - * - * ```js - * import diagnostics_channel from 'node:diagnostics_channel'; - * - * if (diagnostics_channel.hasSubscribers('my-channel')) { - * // There are subscribers, prepare and publish message - * } - * ``` - * @since v15.1.0, v14.17.0 - * @param name The channel name - * @return If there are active subscribers - */ - function hasSubscribers(name: string | symbol): boolean; - /** - * This is the primary entry-point for anyone wanting to publish to a named - * channel. It produces a channel object which is optimized to reduce overhead at - * publish time as much as possible. - * - * ```js - * import diagnostics_channel from 'node:diagnostics_channel'; - * - * const channel = diagnostics_channel.channel('my-channel'); - * ``` - * @since v15.1.0, v14.17.0 - * @param name The channel name - * @return The named channel object - */ - function channel(name: string | symbol): Channel; - type ChannelListener = (message: unknown, name: string | symbol) => void; - /** - * Register a message handler to subscribe to this channel. This message handler - * will be run synchronously whenever a message is published to the channel. Any - * errors thrown in the message handler will trigger an `'uncaughtException'`. - * - * ```js - * import diagnostics_channel from 'node:diagnostics_channel'; - * - * diagnostics_channel.subscribe('my-channel', (message, name) => { - * // Received data - * }); - * ``` - * @since v18.7.0, v16.17.0 - * @param name The channel name - * @param onMessage The handler to receive channel messages - */ - function subscribe(name: string | symbol, onMessage: ChannelListener): void; - /** - * Remove a message handler previously registered to this channel with {@link subscribe}. - * - * ```js - * import diagnostics_channel from 'node:diagnostics_channel'; - * - * function onMessage(message, name) { - * // Received data - * } - * - * diagnostics_channel.subscribe('my-channel', onMessage); - * - * diagnostics_channel.unsubscribe('my-channel', onMessage); - * ``` - * @since v18.7.0, v16.17.0 - * @param name The channel name - * @param onMessage The previous subscribed handler to remove - * @return `true` if the handler was found, `false` otherwise. - */ - function unsubscribe(name: string | symbol, onMessage: ChannelListener): boolean; - /** - * Creates a `TracingChannel` wrapper for the given `TracingChannel Channels`. If a name is given, the corresponding tracing - * channels will be created in the form of `tracing:${name}:${eventType}` where`eventType` corresponds to the types of `TracingChannel Channels`. - * - * ```js - * import diagnostics_channel from 'node:diagnostics_channel'; - * - * const channelsByName = diagnostics_channel.tracingChannel('my-channel'); - * - * // or... - * - * const channelsByCollection = diagnostics_channel.tracingChannel({ - * start: diagnostics_channel.channel('tracing:my-channel:start'), - * end: diagnostics_channel.channel('tracing:my-channel:end'), - * asyncStart: diagnostics_channel.channel('tracing:my-channel:asyncStart'), - * asyncEnd: diagnostics_channel.channel('tracing:my-channel:asyncEnd'), - * error: diagnostics_channel.channel('tracing:my-channel:error'), - * }); - * ``` - * @since v19.9.0 - * @experimental - * @param nameOrChannels Channel name or object containing all the `TracingChannel Channels` - * @return Collection of channels to trace with - */ - function tracingChannel< - StoreType = unknown, - ContextType extends object = StoreType extends object ? StoreType : object, - >( - nameOrChannels: string | TracingChannelCollection, - ): TracingChannel; - /** - * The class `Channel` represents an individual named channel within the data - * pipeline. It is used to track subscribers and to publish messages when there - * are subscribers present. It exists as a separate object to avoid channel - * lookups at publish time, enabling very fast publish speeds and allowing - * for heavy use while incurring very minimal cost. Channels are created with {@link channel}, constructing a channel directly - * with `new Channel(name)` is not supported. - * @since v15.1.0, v14.17.0 - */ - class Channel { - readonly name: string | symbol; - /** - * Check if there are active subscribers to this channel. This is helpful if - * the message you want to send might be expensive to prepare. - * - * This API is optional but helpful when trying to publish messages from very - * performance-sensitive code. - * - * ```js - * import diagnostics_channel from 'node:diagnostics_channel'; - * - * const channel = diagnostics_channel.channel('my-channel'); - * - * if (channel.hasSubscribers) { - * // There are subscribers, prepare and publish message - * } - * ``` - * @since v15.1.0, v14.17.0 - */ - readonly hasSubscribers: boolean; - private constructor(name: string | symbol); - /** - * Publish a message to any subscribers to the channel. This will trigger - * message handlers synchronously so they will execute within the same context. - * - * ```js - * import diagnostics_channel from 'node:diagnostics_channel'; - * - * const channel = diagnostics_channel.channel('my-channel'); - * - * channel.publish({ - * some: 'message', - * }); - * ``` - * @since v15.1.0, v14.17.0 - * @param message The message to send to the channel subscribers - */ - publish(message: unknown): void; - /** - * Register a message handler to subscribe to this channel. This message handler - * will be run synchronously whenever a message is published to the channel. Any - * errors thrown in the message handler will trigger an `'uncaughtException'`. - * - * ```js - * import diagnostics_channel from 'node:diagnostics_channel'; - * - * const channel = diagnostics_channel.channel('my-channel'); - * - * channel.subscribe((message, name) => { - * // Received data - * }); - * ``` - * @since v15.1.0, v14.17.0 - * @deprecated Since v18.7.0,v16.17.0 - Use {@link subscribe(name, onMessage)} - * @param onMessage The handler to receive channel messages - */ - subscribe(onMessage: ChannelListener): void; - /** - * Remove a message handler previously registered to this channel with `channel.subscribe(onMessage)`. - * - * ```js - * import diagnostics_channel from 'node:diagnostics_channel'; - * - * const channel = diagnostics_channel.channel('my-channel'); - * - * function onMessage(message, name) { - * // Received data - * } - * - * channel.subscribe(onMessage); - * - * channel.unsubscribe(onMessage); - * ``` - * @since v15.1.0, v14.17.0 - * @deprecated Since v18.7.0,v16.17.0 - Use {@link unsubscribe(name, onMessage)} - * @param onMessage The previous subscribed handler to remove - * @return `true` if the handler was found, `false` otherwise. - */ - unsubscribe(onMessage: ChannelListener): void; - /** - * When `channel.runStores(context, ...)` is called, the given context data - * will be applied to any store bound to the channel. If the store has already been - * bound the previous `transform` function will be replaced with the new one. - * The `transform` function may be omitted to set the given context data as the - * context directly. - * - * ```js - * import diagnostics_channel from 'node:diagnostics_channel'; - * import { AsyncLocalStorage } from 'node:async_hooks'; - * - * const store = new AsyncLocalStorage(); - * - * const channel = diagnostics_channel.channel('my-channel'); - * - * channel.bindStore(store, (data) => { - * return { data }; - * }); - * ``` - * @since v19.9.0 - * @experimental - * @param store The store to which to bind the context data - * @param transform Transform context data before setting the store context - */ - bindStore(store: AsyncLocalStorage, transform?: (context: ContextType) => StoreType): void; - /** - * Remove a message handler previously registered to this channel with `channel.bindStore(store)`. - * - * ```js - * import diagnostics_channel from 'node:diagnostics_channel'; - * import { AsyncLocalStorage } from 'node:async_hooks'; - * - * const store = new AsyncLocalStorage(); - * - * const channel = diagnostics_channel.channel('my-channel'); - * - * channel.bindStore(store); - * channel.unbindStore(store); - * ``` - * @since v19.9.0 - * @experimental - * @param store The store to unbind from the channel. - * @return `true` if the store was found, `false` otherwise. - */ - unbindStore(store: any): void; - /** - * Applies the given data to any AsyncLocalStorage instances bound to the channel - * for the duration of the given function, then publishes to the channel within - * the scope of that data is applied to the stores. - * - * If a transform function was given to `channel.bindStore(store)` it will be - * applied to transform the message data before it becomes the context value for - * the store. The prior storage context is accessible from within the transform - * function in cases where context linking is required. - * - * The context applied to the store should be accessible in any async code which - * continues from execution which began during the given function, however - * there are some situations in which `context loss` may occur. - * - * ```js - * import diagnostics_channel from 'node:diagnostics_channel'; - * import { AsyncLocalStorage } from 'node:async_hooks'; - * - * const store = new AsyncLocalStorage(); - * - * const channel = diagnostics_channel.channel('my-channel'); - * - * channel.bindStore(store, (message) => { - * const parent = store.getStore(); - * return new Span(message, parent); - * }); - * channel.runStores({ some: 'message' }, () => { - * store.getStore(); // Span({ some: 'message' }) - * }); - * ``` - * @since v19.9.0 - * @experimental - * @param context Message to send to subscribers and bind to stores - * @param fn Handler to run within the entered storage context - * @param thisArg The receiver to be used for the function call. - * @param args Optional arguments to pass to the function. - */ - runStores(): void; - } - interface TracingChannelSubscribers { - start: (message: ContextType) => void; - end: ( - message: ContextType & { - error?: unknown; - result?: unknown; - }, - ) => void; - asyncStart: ( - message: ContextType & { - error?: unknown; - result?: unknown; - }, - ) => void; - asyncEnd: ( - message: ContextType & { - error?: unknown; - result?: unknown; - }, - ) => void; - error: ( - message: ContextType & { - error: unknown; - }, - ) => void; - } - interface TracingChannelCollection { - start: Channel; - end: Channel; - asyncStart: Channel; - asyncEnd: Channel; - error: Channel; - } - /** - * The class `TracingChannel` is a collection of `TracingChannel Channels` which - * together express a single traceable action. It is used to formalize and - * simplify the process of producing events for tracing application flow.{@link tracingChannel} is used to construct a`TracingChannel`. As with `Channel` it is recommended to create and reuse a - * single `TracingChannel` at the top-level of the file rather than creating them - * dynamically. - * @since v19.9.0 - * @experimental - */ - class TracingChannel implements TracingChannelCollection { - start: Channel; - end: Channel; - asyncStart: Channel; - asyncEnd: Channel; - error: Channel; - /** - * Helper to subscribe a collection of functions to the corresponding channels. - * This is the same as calling `channel.subscribe(onMessage)` on each channel - * individually. - * - * ```js - * import diagnostics_channel from 'node:diagnostics_channel'; - * - * const channels = diagnostics_channel.tracingChannel('my-channel'); - * - * channels.subscribe({ - * start(message) { - * // Handle start message - * }, - * end(message) { - * // Handle end message - * }, - * asyncStart(message) { - * // Handle asyncStart message - * }, - * asyncEnd(message) { - * // Handle asyncEnd message - * }, - * error(message) { - * // Handle error message - * }, - * }); - * ``` - * @since v19.9.0 - * @experimental - * @param subscribers Set of `TracingChannel Channels` subscribers - */ - subscribe(subscribers: TracingChannelSubscribers): void; - /** - * Helper to unsubscribe a collection of functions from the corresponding channels. - * This is the same as calling `channel.unsubscribe(onMessage)` on each channel - * individually. - * - * ```js - * import diagnostics_channel from 'node:diagnostics_channel'; - * - * const channels = diagnostics_channel.tracingChannel('my-channel'); - * - * channels.unsubscribe({ - * start(message) { - * // Handle start message - * }, - * end(message) { - * // Handle end message - * }, - * asyncStart(message) { - * // Handle asyncStart message - * }, - * asyncEnd(message) { - * // Handle asyncEnd message - * }, - * error(message) { - * // Handle error message - * }, - * }); - * ``` - * @since v19.9.0 - * @experimental - * @param subscribers Set of `TracingChannel Channels` subscribers - * @return `true` if all handlers were successfully unsubscribed, and `false` otherwise. - */ - unsubscribe(subscribers: TracingChannelSubscribers): void; - /** - * Trace a synchronous function call. This will always produce a `start event` and `end event` around the execution and may produce an `error event` if the given function throws an error. - * This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all - * events should have any bound stores set to match this trace context. - * - * ```js - * import diagnostics_channel from 'node:diagnostics_channel'; - * - * const channels = diagnostics_channel.tracingChannel('my-channel'); - * - * channels.traceSync(() => { - * // Do something - * }, { - * some: 'thing', - * }); - * ``` - * @since v19.9.0 - * @experimental - * @param fn Function to wrap a trace around - * @param context Shared object to correlate events through - * @param thisArg The receiver to be used for the function call - * @param args Optional arguments to pass to the function - * @return The return value of the given function - */ - traceSync( - fn: (this: ThisArg, ...args: Args) => any, - context?: ContextType, - thisArg?: ThisArg, - ...args: Args - ): void; - /** - * Trace a promise-returning function call. This will always produce a `start event` and `end event` around the synchronous portion of the - * function execution, and will produce an `asyncStart event` and `asyncEnd event` when a promise continuation is reached. It may also - * produce an `error event` if the given function throws an error or the - * returned promise rejects. This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all - * events should have any bound stores set to match this trace context. - * - * ```js - * import diagnostics_channel from 'node:diagnostics_channel'; - * - * const channels = diagnostics_channel.tracingChannel('my-channel'); - * - * channels.tracePromise(async () => { - * // Do something - * }, { - * some: 'thing', - * }); - * ``` - * @since v19.9.0 - * @experimental - * @param fn Promise-returning function to wrap a trace around - * @param context Shared object to correlate trace events through - * @param thisArg The receiver to be used for the function call - * @param args Optional arguments to pass to the function - * @return Chained from promise returned by the given function - */ - tracePromise( - fn: (this: ThisArg, ...args: Args) => Promise, - context?: ContextType, - thisArg?: ThisArg, - ...args: Args - ): void; - /** - * Trace a callback-receiving function call. This will always produce a `start event` and `end event` around the synchronous portion of the - * function execution, and will produce a `asyncStart event` and `asyncEnd event` around the callback execution. It may also produce an `error event` if the given function throws an error or - * the returned - * promise rejects. This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all - * events should have any bound stores set to match this trace context. - * - * The `position` will be -1 by default to indicate the final argument should - * be used as the callback. - * - * ```js - * import diagnostics_channel from 'node:diagnostics_channel'; - * - * const channels = diagnostics_channel.tracingChannel('my-channel'); - * - * channels.traceCallback((arg1, callback) => { - * // Do something - * callback(null, 'result'); - * }, 1, { - * some: 'thing', - * }, thisArg, arg1, callback); - * ``` - * - * The callback will also be run with `channel.runStores(context, ...)` which - * enables context loss recovery in some cases. - * - * ```js - * import diagnostics_channel from 'node:diagnostics_channel'; - * import { AsyncLocalStorage } from 'node:async_hooks'; - * - * const channels = diagnostics_channel.tracingChannel('my-channel'); - * const myStore = new AsyncLocalStorage(); - * - * // The start channel sets the initial store data to something - * // and stores that store data value on the trace context object - * channels.start.bindStore(myStore, (data) => { - * const span = new Span(data); - * data.span = span; - * return span; - * }); - * - * // Then asyncStart can restore from that data it stored previously - * channels.asyncStart.bindStore(myStore, (data) => { - * return data.span; - * }); - * ``` - * @since v19.9.0 - * @experimental - * @param fn callback using function to wrap a trace around - * @param position Zero-indexed argument position of expected callback - * @param context Shared object to correlate trace events through - * @param thisArg The receiver to be used for the function call - * @param args Optional arguments to pass to the function - * @return The return value of the given function - */ - traceCallback any>( - fn: Fn, - position: number | undefined, - context: ContextType | undefined, - thisArg: any, - ...args: Parameters - ): void; - } -} -declare module "node:diagnostics_channel" { - export * from "diagnostics_channel"; -} diff --git a/node_modules/@types/node/ts4.8/dns.d.ts b/node_modules/@types/node/ts4.8/dns.d.ts deleted file mode 100644 index 380cf7d7015e33c3fd5d2d1ff8c3f43c5f35a92d..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/dns.d.ts +++ /dev/null @@ -1,809 +0,0 @@ -/** - * The `node:dns` module enables name resolution. For example, use it to look up IP - * addresses of host names. - * - * Although named for the [Domain Name System (DNS)](https://en.wikipedia.org/wiki/Domain_Name_System), it does not always use the - * DNS protocol for lookups. {@link lookup} uses the operating system - * facilities to perform name resolution. It may not need to perform any network - * communication. To perform name resolution the way other applications on the same - * system do, use {@link lookup}. - * - * ```js - * const dns = require('node:dns'); - * - * dns.lookup('example.org', (err, address, family) => { - * console.log('address: %j family: IPv%s', address, family); - * }); - * // address: "93.184.216.34" family: IPv4 - * ``` - * - * All other functions in the `node:dns` module connect to an actual DNS server to - * perform name resolution. They will always use the network to perform DNS - * queries. These functions do not use the same set of configuration files used by {@link lookup} (e.g. `/etc/hosts`). Use these functions to always perform - * DNS queries, bypassing other name-resolution facilities. - * - * ```js - * const dns = require('node:dns'); - * - * dns.resolve4('archive.org', (err, addresses) => { - * if (err) throw err; - * - * console.log(`addresses: ${JSON.stringify(addresses)}`); - * - * addresses.forEach((a) => { - * dns.reverse(a, (err, hostnames) => { - * if (err) { - * throw err; - * } - * console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`); - * }); - * }); - * }); - * ``` - * - * See the `Implementation considerations section` for more information. - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/dns.js) - */ -declare module "dns" { - import * as dnsPromises from "node:dns/promises"; - // Supported getaddrinfo flags. - export const ADDRCONFIG: number; - export const V4MAPPED: number; - /** - * If `dns.V4MAPPED` is specified, return resolved IPv6 addresses as - * well as IPv4 mapped IPv6 addresses. - */ - export const ALL: number; - export interface LookupOptions { - family?: number | undefined; - hints?: number | undefined; - all?: boolean | undefined; - /** - * @default true - */ - verbatim?: boolean | undefined; - } - export interface LookupOneOptions extends LookupOptions { - all?: false | undefined; - } - export interface LookupAllOptions extends LookupOptions { - all: true; - } - export interface LookupAddress { - address: string; - family: number; - } - /** - * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or - * AAAA (IPv6) record. All `option` properties are optional. If `options` is an - * integer, then it must be `4` or `6` – if `options` is `0` or not provided, then - * IPv4 and IPv6 addresses are both returned if found. - * - * With the `all` option set to `true`, the arguments for `callback` change to`(err, addresses)`, with `addresses` being an array of objects with the - * properties `address` and `family`. - * - * On error, `err` is an `Error` object, where `err.code` is the error code. - * Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when - * the host name does not exist but also when the lookup fails in other ways - * such as no available file descriptors. - * - * `dns.lookup()` does not necessarily have anything to do with the DNS protocol. - * The implementation uses an operating system facility that can associate names - * with addresses and vice versa. This implementation can have subtle but - * important consequences on the behavior of any Node.js program. Please take some - * time to consult the `Implementation considerations section` before using`dns.lookup()`. - * - * Example usage: - * - * ```js - * const dns = require('node:dns'); - * const options = { - * family: 6, - * hints: dns.ADDRCONFIG | dns.V4MAPPED, - * }; - * dns.lookup('example.com', options, (err, address, family) => - * console.log('address: %j family: IPv%s', address, family)); - * // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 - * - * // When options.all is true, the result will be an Array. - * options.all = true; - * dns.lookup('example.com', options, (err, addresses) => - * console.log('addresses: %j', addresses)); - * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] - * ``` - * - * If this method is invoked as its `util.promisify()` ed version, and `all`is not set to `true`, it returns a `Promise` for an `Object` with `address` and`family` properties. - * @since v0.1.90 - */ - export function lookup( - hostname: string, - family: number, - callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, - ): void; - export function lookup( - hostname: string, - options: LookupOneOptions, - callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, - ): void; - export function lookup( - hostname: string, - options: LookupAllOptions, - callback: (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void, - ): void; - export function lookup( - hostname: string, - options: LookupOptions, - callback: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family: number) => void, - ): void; - export function lookup( - hostname: string, - callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, - ): void; - export namespace lookup { - function __promisify__(hostname: string, options: LookupAllOptions): Promise; - function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise; - function __promisify__(hostname: string, options: LookupOptions): Promise; - } - /** - * Resolves the given `address` and `port` into a host name and service using - * the operating system's underlying `getnameinfo` implementation. - * - * If `address` is not a valid IP address, a `TypeError` will be thrown. - * The `port` will be coerced to a number. If it is not a legal port, a `TypeError`will be thrown. - * - * On an error, `err` is an `Error` object, where `err.code` is the error code. - * - * ```js - * const dns = require('node:dns'); - * dns.lookupService('127.0.0.1', 22, (err, hostname, service) => { - * console.log(hostname, service); - * // Prints: localhost ssh - * }); - * ``` - * - * If this method is invoked as its `util.promisify()` ed version, it returns a`Promise` for an `Object` with `hostname` and `service` properties. - * @since v0.11.14 - */ - export function lookupService( - address: string, - port: number, - callback: (err: NodeJS.ErrnoException | null, hostname: string, service: string) => void, - ): void; - export namespace lookupService { - function __promisify__( - address: string, - port: number, - ): Promise<{ - hostname: string; - service: string; - }>; - } - export interface ResolveOptions { - ttl: boolean; - } - export interface ResolveWithTtlOptions extends ResolveOptions { - ttl: true; - } - export interface RecordWithTtl { - address: string; - ttl: number; - } - /** @deprecated Use `AnyARecord` or `AnyAaaaRecord` instead. */ - export type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord; - export interface AnyARecord extends RecordWithTtl { - type: "A"; - } - export interface AnyAaaaRecord extends RecordWithTtl { - type: "AAAA"; - } - export interface CaaRecord { - critical: number; - issue?: string | undefined; - issuewild?: string | undefined; - iodef?: string | undefined; - contactemail?: string | undefined; - contactphone?: string | undefined; - } - export interface MxRecord { - priority: number; - exchange: string; - } - export interface AnyMxRecord extends MxRecord { - type: "MX"; - } - export interface NaptrRecord { - flags: string; - service: string; - regexp: string; - replacement: string; - order: number; - preference: number; - } - export interface AnyNaptrRecord extends NaptrRecord { - type: "NAPTR"; - } - export interface SoaRecord { - nsname: string; - hostmaster: string; - serial: number; - refresh: number; - retry: number; - expire: number; - minttl: number; - } - export interface AnySoaRecord extends SoaRecord { - type: "SOA"; - } - export interface SrvRecord { - priority: number; - weight: number; - port: number; - name: string; - } - export interface AnySrvRecord extends SrvRecord { - type: "SRV"; - } - export interface AnyTxtRecord { - type: "TXT"; - entries: string[]; - } - export interface AnyNsRecord { - type: "NS"; - value: string; - } - export interface AnyPtrRecord { - type: "PTR"; - value: string; - } - export interface AnyCnameRecord { - type: "CNAME"; - value: string; - } - export type AnyRecord = - | AnyARecord - | AnyAaaaRecord - | AnyCnameRecord - | AnyMxRecord - | AnyNaptrRecord - | AnyNsRecord - | AnyPtrRecord - | AnySoaRecord - | AnySrvRecord - | AnyTxtRecord; - /** - * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array - * of the resource records. The `callback` function has arguments`(err, records)`. When successful, `records` will be an array of resource - * records. The type and structure of individual results varies based on `rrtype`: - * - * - * - * On error, `err` is an `Error` object, where `err.code` is one of the `DNS error codes`. - * @since v0.1.27 - * @param hostname Host name to resolve. - * @param [rrtype='A'] Resource record type. - */ - export function resolve( - hostname: string, - callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, - ): void; - export function resolve( - hostname: string, - rrtype: "A", - callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, - ): void; - export function resolve( - hostname: string, - rrtype: "AAAA", - callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, - ): void; - export function resolve( - hostname: string, - rrtype: "ANY", - callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void, - ): void; - export function resolve( - hostname: string, - rrtype: "CNAME", - callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, - ): void; - export function resolve( - hostname: string, - rrtype: "MX", - callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void, - ): void; - export function resolve( - hostname: string, - rrtype: "NAPTR", - callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void, - ): void; - export function resolve( - hostname: string, - rrtype: "NS", - callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, - ): void; - export function resolve( - hostname: string, - rrtype: "PTR", - callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, - ): void; - export function resolve( - hostname: string, - rrtype: "SOA", - callback: (err: NodeJS.ErrnoException | null, addresses: SoaRecord) => void, - ): void; - export function resolve( - hostname: string, - rrtype: "SRV", - callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void, - ): void; - export function resolve( - hostname: string, - rrtype: "TXT", - callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void, - ): void; - export function resolve( - hostname: string, - rrtype: string, - callback: ( - err: NodeJS.ErrnoException | null, - addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[], - ) => void, - ): void; - export namespace resolve { - function __promisify__(hostname: string, rrtype?: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise; - function __promisify__(hostname: string, rrtype: "ANY"): Promise; - function __promisify__(hostname: string, rrtype: "MX"): Promise; - function __promisify__(hostname: string, rrtype: "NAPTR"): Promise; - function __promisify__(hostname: string, rrtype: "SOA"): Promise; - function __promisify__(hostname: string, rrtype: "SRV"): Promise; - function __promisify__(hostname: string, rrtype: "TXT"): Promise; - function __promisify__( - hostname: string, - rrtype: string, - ): Promise; - } - /** - * Uses the DNS protocol to resolve a IPv4 addresses (`A` records) for the`hostname`. The `addresses` argument passed to the `callback` function - * will contain an array of IPv4 addresses (e.g.`['74.125.79.104', '74.125.79.105', '74.125.79.106']`). - * @since v0.1.16 - * @param hostname Host name to resolve. - */ - export function resolve4( - hostname: string, - callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, - ): void; - export function resolve4( - hostname: string, - options: ResolveWithTtlOptions, - callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void, - ): void; - export function resolve4( - hostname: string, - options: ResolveOptions, - callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void, - ): void; - export namespace resolve4 { - function __promisify__(hostname: string): Promise; - function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; - function __promisify__(hostname: string, options?: ResolveOptions): Promise; - } - /** - * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the`hostname`. The `addresses` argument passed to the `callback` function - * will contain an array of IPv6 addresses. - * @since v0.1.16 - * @param hostname Host name to resolve. - */ - export function resolve6( - hostname: string, - callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, - ): void; - export function resolve6( - hostname: string, - options: ResolveWithTtlOptions, - callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void, - ): void; - export function resolve6( - hostname: string, - options: ResolveOptions, - callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void, - ): void; - export namespace resolve6 { - function __promisify__(hostname: string): Promise; - function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; - function __promisify__(hostname: string, options?: ResolveOptions): Promise; - } - /** - * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. The`addresses` argument passed to the `callback` function - * will contain an array of canonical name records available for the `hostname`(e.g. `['bar.example.com']`). - * @since v0.3.2 - */ - export function resolveCname( - hostname: string, - callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, - ): void; - export namespace resolveCname { - function __promisify__(hostname: string): Promise; - } - /** - * Uses the DNS protocol to resolve `CAA` records for the `hostname`. The`addresses` argument passed to the `callback` function - * will contain an array of certification authority authorization records - * available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]`). - * @since v15.0.0, v14.17.0 - */ - export function resolveCaa( - hostname: string, - callback: (err: NodeJS.ErrnoException | null, records: CaaRecord[]) => void, - ): void; - export namespace resolveCaa { - function __promisify__(hostname: string): Promise; - } - /** - * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the`hostname`. The `addresses` argument passed to the `callback` function will - * contain an array of objects containing both a `priority` and `exchange`property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`). - * @since v0.1.27 - */ - export function resolveMx( - hostname: string, - callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void, - ): void; - export namespace resolveMx { - function __promisify__(hostname: string): Promise; - } - /** - * Uses the DNS protocol to resolve regular expression-based records (`NAPTR`records) for the `hostname`. The `addresses` argument passed to the `callback`function will contain an array of - * objects with the following properties: - * - * * `flags` - * * `service` - * * `regexp` - * * `replacement` - * * `order` - * * `preference` - * - * ```js - * { - * flags: 's', - * service: 'SIP+D2U', - * regexp: '', - * replacement: '_sip._udp.example.com', - * order: 30, - * preference: 100 - * } - * ``` - * @since v0.9.12 - */ - export function resolveNaptr( - hostname: string, - callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void, - ): void; - export namespace resolveNaptr { - function __promisify__(hostname: string): Promise; - } - /** - * Uses the DNS protocol to resolve name server records (`NS` records) for the`hostname`. The `addresses` argument passed to the `callback` function will - * contain an array of name server records available for `hostname`(e.g. `['ns1.example.com', 'ns2.example.com']`). - * @since v0.1.90 - */ - export function resolveNs( - hostname: string, - callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, - ): void; - export namespace resolveNs { - function __promisify__(hostname: string): Promise; - } - /** - * Uses the DNS protocol to resolve pointer records (`PTR` records) for the`hostname`. The `addresses` argument passed to the `callback` function will - * be an array of strings containing the reply records. - * @since v6.0.0 - */ - export function resolvePtr( - hostname: string, - callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, - ): void; - export namespace resolvePtr { - function __promisify__(hostname: string): Promise; - } - /** - * Uses the DNS protocol to resolve a start of authority record (`SOA` record) for - * the `hostname`. The `address` argument passed to the `callback` function will - * be an object with the following properties: - * - * * `nsname` - * * `hostmaster` - * * `serial` - * * `refresh` - * * `retry` - * * `expire` - * * `minttl` - * - * ```js - * { - * nsname: 'ns.example.com', - * hostmaster: 'root.example.com', - * serial: 2013101809, - * refresh: 10000, - * retry: 2400, - * expire: 604800, - * minttl: 3600 - * } - * ``` - * @since v0.11.10 - */ - export function resolveSoa( - hostname: string, - callback: (err: NodeJS.ErrnoException | null, address: SoaRecord) => void, - ): void; - export namespace resolveSoa { - function __promisify__(hostname: string): Promise; - } - /** - * Uses the DNS protocol to resolve service records (`SRV` records) for the`hostname`. The `addresses` argument passed to the `callback` function will - * be an array of objects with the following properties: - * - * * `priority` - * * `weight` - * * `port` - * * `name` - * - * ```js - * { - * priority: 10, - * weight: 5, - * port: 21223, - * name: 'service.example.com' - * } - * ``` - * @since v0.1.27 - */ - export function resolveSrv( - hostname: string, - callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void, - ): void; - export namespace resolveSrv { - function __promisify__(hostname: string): Promise; - } - /** - * Uses the DNS protocol to resolve text queries (`TXT` records) for the`hostname`. The `records` argument passed to the `callback` function is a - * two-dimensional array of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of - * one record. Depending on the use case, these could be either joined together or - * treated separately. - * @since v0.1.27 - */ - export function resolveTxt( - hostname: string, - callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void, - ): void; - export namespace resolveTxt { - function __promisify__(hostname: string): Promise; - } - /** - * Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). - * The `ret` argument passed to the `callback` function will be an array containing - * various types of records. Each object has a property `type` that indicates the - * type of the current record. And depending on the `type`, additional properties - * will be present on the object: - * - * - * - * Here is an example of the `ret` object passed to the callback: - * - * ```js - * [ { type: 'A', address: '127.0.0.1', ttl: 299 }, - * { type: 'CNAME', value: 'example.com' }, - * { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, - * { type: 'NS', value: 'ns1.example.com' }, - * { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, - * { type: 'SOA', - * nsname: 'ns1.example.com', - * hostmaster: 'admin.example.com', - * serial: 156696742, - * refresh: 900, - * retry: 900, - * expire: 1800, - * minttl: 60 } ] - * ``` - * - * DNS server operators may choose not to respond to `ANY`queries. It may be better to call individual methods like {@link resolve4},{@link resolveMx}, and so on. For more details, see [RFC - * 8482](https://tools.ietf.org/html/rfc8482). - */ - export function resolveAny( - hostname: string, - callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void, - ): void; - export namespace resolveAny { - function __promisify__(hostname: string): Promise; - } - /** - * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an - * array of host names. - * - * On error, `err` is an `Error` object, where `err.code` is - * one of the `DNS error codes`. - * @since v0.1.16 - */ - export function reverse( - ip: string, - callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void, - ): void; - /** - * Get the default value for `verbatim` in {@link lookup} and `dnsPromises.lookup()`. The value could be: - * - * * `ipv4first`: for `verbatim` defaulting to `false`. - * * `verbatim`: for `verbatim` defaulting to `true`. - * @since v20.1.0 - */ - export function getDefaultResultOrder(): "ipv4first" | "verbatim"; - /** - * Sets the IP address and port of servers to be used when performing DNS - * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted - * addresses. If the port is the IANA default DNS port (53) it can be omitted. - * - * ```js - * dns.setServers([ - * '4.4.4.4', - * '[2001:4860:4860::8888]', - * '4.4.4.4:1053', - * '[2001:4860:4860::8888]:1053', - * ]); - * ``` - * - * An error will be thrown if an invalid address is provided. - * - * The `dns.setServers()` method must not be called while a DNS query is in - * progress. - * - * The {@link setServers} method affects only {@link resolve},`dns.resolve*()` and {@link reverse} (and specifically _not_ {@link lookup}). - * - * This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). - * That is, if attempting to resolve with the first server provided results in a`NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with - * subsequent servers provided. Fallback DNS servers will only be used if the - * earlier ones time out or result in some other error. - * @since v0.11.3 - * @param servers array of `RFC 5952` formatted addresses - */ - export function setServers(servers: readonly string[]): void; - /** - * Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), - * that are currently configured for DNS resolution. A string will include a port - * section if a custom port is used. - * - * ```js - * [ - * '4.4.4.4', - * '2001:4860:4860::8888', - * '4.4.4.4:1053', - * '[2001:4860:4860::8888]:1053', - * ] - * ``` - * @since v0.11.3 - */ - export function getServers(): string[]; - /** - * Set the default value of `verbatim` in {@link lookup} and `dnsPromises.lookup()`. The value could be: - * - * * `ipv4first`: sets default `verbatim` `false`. - * * `verbatim`: sets default `verbatim` `true`. - * - * The default is `verbatim` and {@link setDefaultResultOrder} have higher - * priority than `--dns-result-order`. When using `worker threads`,{@link setDefaultResultOrder} from the main thread won't affect the default - * dns orders in workers. - * @since v16.4.0, v14.18.0 - * @param order must be `'ipv4first'` or `'verbatim'`. - */ - export function setDefaultResultOrder(order: "ipv4first" | "verbatim"): void; - // Error codes - export const NODATA: string; - export const FORMERR: string; - export const SERVFAIL: string; - export const NOTFOUND: string; - export const NOTIMP: string; - export const REFUSED: string; - export const BADQUERY: string; - export const BADNAME: string; - export const BADFAMILY: string; - export const BADRESP: string; - export const CONNREFUSED: string; - export const TIMEOUT: string; - export const EOF: string; - export const FILE: string; - export const NOMEM: string; - export const DESTRUCTION: string; - export const BADSTR: string; - export const BADFLAGS: string; - export const NONAME: string; - export const BADHINTS: string; - export const NOTINITIALIZED: string; - export const LOADIPHLPAPI: string; - export const ADDRGETNETWORKPARAMS: string; - export const CANCELLED: string; - export interface ResolverOptions { - timeout?: number | undefined; - /** - * @default 4 - */ - tries?: number; - } - /** - * An independent resolver for DNS requests. - * - * Creating a new resolver uses the default server settings. Setting - * the servers used for a resolver using `resolver.setServers()` does not affect - * other resolvers: - * - * ```js - * const { Resolver } = require('node:dns'); - * const resolver = new Resolver(); - * resolver.setServers(['4.4.4.4']); - * - * // This request will use the server at 4.4.4.4, independent of global settings. - * resolver.resolve4('example.org', (err, addresses) => { - * // ... - * }); - * ``` - * - * The following methods from the `node:dns` module are available: - * - * * `resolver.getServers()` - * * `resolver.resolve()` - * * `resolver.resolve4()` - * * `resolver.resolve6()` - * * `resolver.resolveAny()` - * * `resolver.resolveCaa()` - * * `resolver.resolveCname()` - * * `resolver.resolveMx()` - * * `resolver.resolveNaptr()` - * * `resolver.resolveNs()` - * * `resolver.resolvePtr()` - * * `resolver.resolveSoa()` - * * `resolver.resolveSrv()` - * * `resolver.resolveTxt()` - * * `resolver.reverse()` - * * `resolver.setServers()` - * @since v8.3.0 - */ - export class Resolver { - constructor(options?: ResolverOptions); - /** - * Cancel all outstanding DNS queries made by this resolver. The corresponding - * callbacks will be called with an error with code `ECANCELLED`. - * @since v8.3.0 - */ - cancel(): void; - getServers: typeof getServers; - resolve: typeof resolve; - resolve4: typeof resolve4; - resolve6: typeof resolve6; - resolveAny: typeof resolveAny; - resolveCaa: typeof resolveCaa; - resolveCname: typeof resolveCname; - resolveMx: typeof resolveMx; - resolveNaptr: typeof resolveNaptr; - resolveNs: typeof resolveNs; - resolvePtr: typeof resolvePtr; - resolveSoa: typeof resolveSoa; - resolveSrv: typeof resolveSrv; - resolveTxt: typeof resolveTxt; - reverse: typeof reverse; - /** - * The resolver instance will send its requests from the specified IP address. - * This allows programs to specify outbound interfaces when used on multi-homed - * systems. - * - * If a v4 or v6 address is not specified, it is set to the default and the - * operating system will choose a local address automatically. - * - * The resolver will use the v4 local address when making requests to IPv4 DNS - * servers, and the v6 local address when making requests to IPv6 DNS servers. - * The `rrtype` of resolution requests has no impact on the local address used. - * @since v15.1.0, v14.17.0 - * @param [ipv4='0.0.0.0'] A string representation of an IPv4 address. - * @param [ipv6='::0'] A string representation of an IPv6 address. - */ - setLocalAddress(ipv4?: string, ipv6?: string): void; - setServers: typeof setServers; - } - export { dnsPromises as promises }; -} -declare module "node:dns" { - export * from "dns"; -} diff --git a/node_modules/@types/node/ts4.8/dns/promises.d.ts b/node_modules/@types/node/ts4.8/dns/promises.d.ts deleted file mode 100644 index ef9b2228123c3a483363e3c102ab8c30ec9be2dd..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/dns/promises.d.ts +++ /dev/null @@ -1,425 +0,0 @@ -/** - * The `dns.promises` API provides an alternative set of asynchronous DNS methods - * that return `Promise` objects rather than using callbacks. The API is accessible - * via `require('node:dns').promises` or `require('node:dns/promises')`. - * @since v10.6.0 - */ -declare module "dns/promises" { - import { - AnyRecord, - CaaRecord, - LookupAddress, - LookupAllOptions, - LookupOneOptions, - LookupOptions, - MxRecord, - NaptrRecord, - RecordWithTtl, - ResolveOptions, - ResolverOptions, - ResolveWithTtlOptions, - SoaRecord, - SrvRecord, - } from "node:dns"; - /** - * Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), - * that are currently configured for DNS resolution. A string will include a port - * section if a custom port is used. - * - * ```js - * [ - * '4.4.4.4', - * '2001:4860:4860::8888', - * '4.4.4.4:1053', - * '[2001:4860:4860::8888]:1053', - * ] - * ``` - * @since v10.6.0 - */ - function getServers(): string[]; - /** - * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or - * AAAA (IPv6) record. All `option` properties are optional. If `options` is an - * integer, then it must be `4` or `6` – if `options` is not provided, then IPv4 - * and IPv6 addresses are both returned if found. - * - * With the `all` option set to `true`, the `Promise` is resolved with `addresses`being an array of objects with the properties `address` and `family`. - * - * On error, the `Promise` is rejected with an `Error` object, where `err.code`is the error code. - * Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when - * the host name does not exist but also when the lookup fails in other ways - * such as no available file descriptors. - * - * `dnsPromises.lookup()` does not necessarily have anything to do with the DNS - * protocol. The implementation uses an operating system facility that can - * associate names with addresses and vice versa. This implementation can have - * subtle but important consequences on the behavior of any Node.js program. Please - * take some time to consult the `Implementation considerations section` before - * using `dnsPromises.lookup()`. - * - * Example usage: - * - * ```js - * const dns = require('node:dns'); - * const dnsPromises = dns.promises; - * const options = { - * family: 6, - * hints: dns.ADDRCONFIG | dns.V4MAPPED, - * }; - * - * dnsPromises.lookup('example.com', options).then((result) => { - * console.log('address: %j family: IPv%s', result.address, result.family); - * // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 - * }); - * - * // When options.all is true, the result will be an Array. - * options.all = true; - * dnsPromises.lookup('example.com', options).then((result) => { - * console.log('addresses: %j', result); - * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] - * }); - * ``` - * @since v10.6.0 - */ - function lookup(hostname: string, family: number): Promise; - function lookup(hostname: string, options: LookupOneOptions): Promise; - function lookup(hostname: string, options: LookupAllOptions): Promise; - function lookup(hostname: string, options: LookupOptions): Promise; - function lookup(hostname: string): Promise; - /** - * Resolves the given `address` and `port` into a host name and service using - * the operating system's underlying `getnameinfo` implementation. - * - * If `address` is not a valid IP address, a `TypeError` will be thrown. - * The `port` will be coerced to a number. If it is not a legal port, a `TypeError`will be thrown. - * - * On error, the `Promise` is rejected with an `Error` object, where `err.code`is the error code. - * - * ```js - * const dnsPromises = require('node:dns').promises; - * dnsPromises.lookupService('127.0.0.1', 22).then((result) => { - * console.log(result.hostname, result.service); - * // Prints: localhost ssh - * }); - * ``` - * @since v10.6.0 - */ - function lookupService( - address: string, - port: number, - ): Promise<{ - hostname: string; - service: string; - }>; - /** - * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array - * of the resource records. When successful, the `Promise` is resolved with an - * array of resource records. The type and structure of individual results vary - * based on `rrtype`: - * - * - * - * On error, the `Promise` is rejected with an `Error` object, where `err.code`is one of the `DNS error codes`. - * @since v10.6.0 - * @param hostname Host name to resolve. - * @param [rrtype='A'] Resource record type. - */ - function resolve(hostname: string): Promise; - function resolve(hostname: string, rrtype: "A"): Promise; - function resolve(hostname: string, rrtype: "AAAA"): Promise; - function resolve(hostname: string, rrtype: "ANY"): Promise; - function resolve(hostname: string, rrtype: "CAA"): Promise; - function resolve(hostname: string, rrtype: "CNAME"): Promise; - function resolve(hostname: string, rrtype: "MX"): Promise; - function resolve(hostname: string, rrtype: "NAPTR"): Promise; - function resolve(hostname: string, rrtype: "NS"): Promise; - function resolve(hostname: string, rrtype: "PTR"): Promise; - function resolve(hostname: string, rrtype: "SOA"): Promise; - function resolve(hostname: string, rrtype: "SRV"): Promise; - function resolve(hostname: string, rrtype: "TXT"): Promise; - function resolve( - hostname: string, - rrtype: string, - ): Promise; - /** - * Uses the DNS protocol to resolve IPv4 addresses (`A` records) for the`hostname`. On success, the `Promise` is resolved with an array of IPv4 - * addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`). - * @since v10.6.0 - * @param hostname Host name to resolve. - */ - function resolve4(hostname: string): Promise; - function resolve4(hostname: string, options: ResolveWithTtlOptions): Promise; - function resolve4(hostname: string, options: ResolveOptions): Promise; - /** - * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the`hostname`. On success, the `Promise` is resolved with an array of IPv6 - * addresses. - * @since v10.6.0 - * @param hostname Host name to resolve. - */ - function resolve6(hostname: string): Promise; - function resolve6(hostname: string, options: ResolveWithTtlOptions): Promise; - function resolve6(hostname: string, options: ResolveOptions): Promise; - /** - * Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). - * On success, the `Promise` is resolved with an array containing various types of - * records. Each object has a property `type` that indicates the type of the - * current record. And depending on the `type`, additional properties will be - * present on the object: - * - * - * - * Here is an example of the result object: - * - * ```js - * [ { type: 'A', address: '127.0.0.1', ttl: 299 }, - * { type: 'CNAME', value: 'example.com' }, - * { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, - * { type: 'NS', value: 'ns1.example.com' }, - * { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, - * { type: 'SOA', - * nsname: 'ns1.example.com', - * hostmaster: 'admin.example.com', - * serial: 156696742, - * refresh: 900, - * retry: 900, - * expire: 1800, - * minttl: 60 } ] - * ``` - * @since v10.6.0 - */ - function resolveAny(hostname: string): Promise; - /** - * Uses the DNS protocol to resolve `CAA` records for the `hostname`. On success, - * the `Promise` is resolved with an array of objects containing available - * certification authority authorization records available for the `hostname`(e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'},{critical: 128, issue: 'pki.example.com'}]`). - * @since v15.0.0, v14.17.0 - */ - function resolveCaa(hostname: string): Promise; - /** - * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. On success, - * the `Promise` is resolved with an array of canonical name records available for - * the `hostname` (e.g. `['bar.example.com']`). - * @since v10.6.0 - */ - function resolveCname(hostname: string): Promise; - /** - * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the`hostname`. On success, the `Promise` is resolved with an array of objects - * containing both a `priority` and `exchange` property (e.g.`[{priority: 10, exchange: 'mx.example.com'}, ...]`). - * @since v10.6.0 - */ - function resolveMx(hostname: string): Promise; - /** - * Uses the DNS protocol to resolve regular expression-based records (`NAPTR`records) for the `hostname`. On success, the `Promise` is resolved with an array - * of objects with the following properties: - * - * * `flags` - * * `service` - * * `regexp` - * * `replacement` - * * `order` - * * `preference` - * - * ```js - * { - * flags: 's', - * service: 'SIP+D2U', - * regexp: '', - * replacement: '_sip._udp.example.com', - * order: 30, - * preference: 100 - * } - * ``` - * @since v10.6.0 - */ - function resolveNaptr(hostname: string): Promise; - /** - * Uses the DNS protocol to resolve name server records (`NS` records) for the`hostname`. On success, the `Promise` is resolved with an array of name server - * records available for `hostname` (e.g.`['ns1.example.com', 'ns2.example.com']`). - * @since v10.6.0 - */ - function resolveNs(hostname: string): Promise; - /** - * Uses the DNS protocol to resolve pointer records (`PTR` records) for the`hostname`. On success, the `Promise` is resolved with an array of strings - * containing the reply records. - * @since v10.6.0 - */ - function resolvePtr(hostname: string): Promise; - /** - * Uses the DNS protocol to resolve a start of authority record (`SOA` record) for - * the `hostname`. On success, the `Promise` is resolved with an object with the - * following properties: - * - * * `nsname` - * * `hostmaster` - * * `serial` - * * `refresh` - * * `retry` - * * `expire` - * * `minttl` - * - * ```js - * { - * nsname: 'ns.example.com', - * hostmaster: 'root.example.com', - * serial: 2013101809, - * refresh: 10000, - * retry: 2400, - * expire: 604800, - * minttl: 3600 - * } - * ``` - * @since v10.6.0 - */ - function resolveSoa(hostname: string): Promise; - /** - * Uses the DNS protocol to resolve service records (`SRV` records) for the`hostname`. On success, the `Promise` is resolved with an array of objects with - * the following properties: - * - * * `priority` - * * `weight` - * * `port` - * * `name` - * - * ```js - * { - * priority: 10, - * weight: 5, - * port: 21223, - * name: 'service.example.com' - * } - * ``` - * @since v10.6.0 - */ - function resolveSrv(hostname: string): Promise; - /** - * Uses the DNS protocol to resolve text queries (`TXT` records) for the`hostname`. On success, the `Promise` is resolved with a two-dimensional array - * of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of - * one record. Depending on the use case, these could be either joined together or - * treated separately. - * @since v10.6.0 - */ - function resolveTxt(hostname: string): Promise; - /** - * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an - * array of host names. - * - * On error, the `Promise` is rejected with an `Error` object, where `err.code`is one of the `DNS error codes`. - * @since v10.6.0 - */ - function reverse(ip: string): Promise; - /** - * Get the default value for `verbatim` in {@link lookup} and `dnsPromises.lookup()`. The value could be: - * - * * `ipv4first`: for `verbatim` defaulting to `false`. - * * `verbatim`: for `verbatim` defaulting to `true`. - * @since v20.1.0 - */ - function getDefaultResultOrder(): "ipv4first" | "verbatim"; - /** - * Sets the IP address and port of servers to be used when performing DNS - * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted - * addresses. If the port is the IANA default DNS port (53) it can be omitted. - * - * ```js - * dnsPromises.setServers([ - * '4.4.4.4', - * '[2001:4860:4860::8888]', - * '4.4.4.4:1053', - * '[2001:4860:4860::8888]:1053', - * ]); - * ``` - * - * An error will be thrown if an invalid address is provided. - * - * The `dnsPromises.setServers()` method must not be called while a DNS query is in - * progress. - * - * This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). - * That is, if attempting to resolve with the first server provided results in a`NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with - * subsequent servers provided. Fallback DNS servers will only be used if the - * earlier ones time out or result in some other error. - * @since v10.6.0 - * @param servers array of `RFC 5952` formatted addresses - */ - function setServers(servers: readonly string[]): void; - /** - * Set the default value of `verbatim` in `dns.lookup()` and `dnsPromises.lookup()`. The value could be: - * - * * `ipv4first`: sets default `verbatim` `false`. - * * `verbatim`: sets default `verbatim` `true`. - * - * The default is `verbatim` and `dnsPromises.setDefaultResultOrder()` have - * higher priority than `--dns-result-order`. When using `worker threads`,`dnsPromises.setDefaultResultOrder()` from the main thread won't affect the - * default dns orders in workers. - * @since v16.4.0, v14.18.0 - * @param order must be `'ipv4first'` or `'verbatim'`. - */ - function setDefaultResultOrder(order: "ipv4first" | "verbatim"): void; - /** - * An independent resolver for DNS requests. - * - * Creating a new resolver uses the default server settings. Setting - * the servers used for a resolver using `resolver.setServers()` does not affect - * other resolvers: - * - * ```js - * const { Resolver } = require('node:dns').promises; - * const resolver = new Resolver(); - * resolver.setServers(['4.4.4.4']); - * - * // This request will use the server at 4.4.4.4, independent of global settings. - * resolver.resolve4('example.org').then((addresses) => { - * // ... - * }); - * - * // Alternatively, the same code can be written using async-await style. - * (async function() { - * const addresses = await resolver.resolve4('example.org'); - * })(); - * ``` - * - * The following methods from the `dnsPromises` API are available: - * - * * `resolver.getServers()` - * * `resolver.resolve()` - * * `resolver.resolve4()` - * * `resolver.resolve6()` - * * `resolver.resolveAny()` - * * `resolver.resolveCaa()` - * * `resolver.resolveCname()` - * * `resolver.resolveMx()` - * * `resolver.resolveNaptr()` - * * `resolver.resolveNs()` - * * `resolver.resolvePtr()` - * * `resolver.resolveSoa()` - * * `resolver.resolveSrv()` - * * `resolver.resolveTxt()` - * * `resolver.reverse()` - * * `resolver.setServers()` - * @since v10.6.0 - */ - class Resolver { - constructor(options?: ResolverOptions); - cancel(): void; - getServers: typeof getServers; - resolve: typeof resolve; - resolve4: typeof resolve4; - resolve6: typeof resolve6; - resolveAny: typeof resolveAny; - resolveCaa: typeof resolveCaa; - resolveCname: typeof resolveCname; - resolveMx: typeof resolveMx; - resolveNaptr: typeof resolveNaptr; - resolveNs: typeof resolveNs; - resolvePtr: typeof resolvePtr; - resolveSoa: typeof resolveSoa; - resolveSrv: typeof resolveSrv; - resolveTxt: typeof resolveTxt; - reverse: typeof reverse; - setLocalAddress(ipv4?: string, ipv6?: string): void; - setServers: typeof setServers; - } -} -declare module "node:dns/promises" { - export * from "dns/promises"; -} diff --git a/node_modules/@types/node/ts4.8/dom-events.d.ts b/node_modules/@types/node/ts4.8/dom-events.d.ts deleted file mode 100644 index 147a7b657dfa93431b2724b9e31c05f75cfe230c..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/dom-events.d.ts +++ /dev/null @@ -1,122 +0,0 @@ -export {}; // Don't export anything! - -//// DOM-like Events -// NB: The Event / EventTarget / EventListener implementations below were copied -// from lib.dom.d.ts, then edited to reflect Node's documentation at -// https://nodejs.org/api/events.html#class-eventtarget. -// Please read that link to understand important implementation differences. - -// This conditional type will be the existing global Event in a browser, or -// the copy below in a Node environment. -type __Event = typeof globalThis extends { onmessage: any; Event: any } ? {} - : { - /** This is not used in Node.js and is provided purely for completeness. */ - readonly bubbles: boolean; - /** Alias for event.stopPropagation(). This is not used in Node.js and is provided purely for completeness. */ - cancelBubble: () => void; - /** True if the event was created with the cancelable option */ - readonly cancelable: boolean; - /** This is not used in Node.js and is provided purely for completeness. */ - readonly composed: boolean; - /** Returns an array containing the current EventTarget as the only entry or empty if the event is not being dispatched. This is not used in Node.js and is provided purely for completeness. */ - composedPath(): [EventTarget?]; - /** Alias for event.target. */ - readonly currentTarget: EventTarget | null; - /** Is true if cancelable is true and event.preventDefault() has been called. */ - readonly defaultPrevented: boolean; - /** This is not used in Node.js and is provided purely for completeness. */ - readonly eventPhase: 0 | 2; - /** The `AbortSignal` "abort" event is emitted with `isTrusted` set to `true`. The value is `false` in all other cases. */ - readonly isTrusted: boolean; - /** Sets the `defaultPrevented` property to `true` if `cancelable` is `true`. */ - preventDefault(): void; - /** This is not used in Node.js and is provided purely for completeness. */ - returnValue: boolean; - /** Alias for event.target. */ - readonly srcElement: EventTarget | null; - /** Stops the invocation of event listeners after the current one completes. */ - stopImmediatePropagation(): void; - /** This is not used in Node.js and is provided purely for completeness. */ - stopPropagation(): void; - /** The `EventTarget` dispatching the event */ - readonly target: EventTarget | null; - /** The millisecond timestamp when the Event object was created. */ - readonly timeStamp: number; - /** Returns the type of event, e.g. "click", "hashchange", or "submit". */ - readonly type: string; - }; - -// See comment above explaining conditional type -type __EventTarget = typeof globalThis extends { onmessage: any; EventTarget: any } ? {} - : { - /** - * Adds a new handler for the `type` event. Any given `listener` is added only once per `type` and per `capture` option value. - * - * If the `once` option is true, the `listener` is removed after the next time a `type` event is dispatched. - * - * The `capture` option is not used by Node.js in any functional way other than tracking registered event listeners per the `EventTarget` specification. - * Specifically, the `capture` option is used as part of the key when registering a `listener`. - * Any individual `listener` may be added once with `capture = false`, and once with `capture = true`. - */ - addEventListener( - type: string, - listener: EventListener | EventListenerObject, - options?: AddEventListenerOptions | boolean, - ): void; - /** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ - dispatchEvent(event: Event): boolean; - /** Removes the event listener in target's event listener list with the same type, callback, and options. */ - removeEventListener( - type: string, - listener: EventListener | EventListenerObject, - options?: EventListenerOptions | boolean, - ): void; - }; - -interface EventInit { - bubbles?: boolean; - cancelable?: boolean; - composed?: boolean; -} - -interface EventListenerOptions { - /** Not directly used by Node.js. Added for API completeness. Default: `false`. */ - capture?: boolean; -} - -interface AddEventListenerOptions extends EventListenerOptions { - /** When `true`, the listener is automatically removed when it is first invoked. Default: `false`. */ - once?: boolean; - /** When `true`, serves as a hint that the listener will not call the `Event` object's `preventDefault()` method. Default: false. */ - passive?: boolean; -} - -interface EventListener { - (evt: Event): void; -} - -interface EventListenerObject { - handleEvent(object: Event): void; -} - -import {} from "events"; // Make this an ambient declaration -declare global { - /** An event which takes place in the DOM. */ - interface Event extends __Event {} - var Event: typeof globalThis extends { onmessage: any; Event: infer T } ? T - : { - prototype: __Event; - new(type: string, eventInitDict?: EventInit): __Event; - }; - - /** - * EventTarget is a DOM interface implemented by objects that can - * receive events and may have listeners for them. - */ - interface EventTarget extends __EventTarget {} - var EventTarget: typeof globalThis extends { onmessage: any; EventTarget: infer T } ? T - : { - prototype: __EventTarget; - new(): __EventTarget; - }; -} diff --git a/node_modules/@types/node/ts4.8/domain.d.ts b/node_modules/@types/node/ts4.8/domain.d.ts deleted file mode 100644 index 72f17bd801e745a3697e684826345fee0d998fcb..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/domain.d.ts +++ /dev/null @@ -1,170 +0,0 @@ -/** - * **This module is pending deprecation.** Once a replacement API has been - * finalized, this module will be fully deprecated. Most developers should - * **not** have cause to use this module. Users who absolutely must have - * the functionality that domains provide may rely on it for the time being - * but should expect to have to migrate to a different solution - * in the future. - * - * Domains provide a way to handle multiple different IO operations as a - * single group. If any of the event emitters or callbacks registered to a - * domain emit an `'error'` event, or throw an error, then the domain object - * will be notified, rather than losing the context of the error in the`process.on('uncaughtException')` handler, or causing the program to - * exit immediately with an error code. - * @deprecated Since v1.4.2 - Deprecated - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/domain.js) - */ -declare module "domain" { - import EventEmitter = require("node:events"); - /** - * The `Domain` class encapsulates the functionality of routing errors and - * uncaught exceptions to the active `Domain` object. - * - * To handle the errors that it catches, listen to its `'error'` event. - */ - class Domain extends EventEmitter { - /** - * An array of timers and event emitters that have been explicitly added - * to the domain. - */ - members: Array; - /** - * The `enter()` method is plumbing used by the `run()`, `bind()`, and`intercept()` methods to set the active domain. It sets `domain.active` and`process.domain` to the domain, and implicitly - * pushes the domain onto the domain - * stack managed by the domain module (see {@link exit} for details on the - * domain stack). The call to `enter()` delimits the beginning of a chain of - * asynchronous calls and I/O operations bound to a domain. - * - * Calling `enter()` changes only the active domain, and does not alter the domain - * itself. `enter()` and `exit()` can be called an arbitrary number of times on a - * single domain. - */ - enter(): void; - /** - * The `exit()` method exits the current domain, popping it off the domain stack. - * Any time execution is going to switch to the context of a different chain of - * asynchronous calls, it's important to ensure that the current domain is exited. - * The call to `exit()` delimits either the end of or an interruption to the chain - * of asynchronous calls and I/O operations bound to a domain. - * - * If there are multiple, nested domains bound to the current execution context,`exit()` will exit any domains nested within this domain. - * - * Calling `exit()` changes only the active domain, and does not alter the domain - * itself. `enter()` and `exit()` can be called an arbitrary number of times on a - * single domain. - */ - exit(): void; - /** - * Run the supplied function in the context of the domain, implicitly - * binding all event emitters, timers, and low-level requests that are - * created in that context. Optionally, arguments can be passed to - * the function. - * - * This is the most basic way to use a domain. - * - * ```js - * const domain = require('node:domain'); - * const fs = require('node:fs'); - * const d = domain.create(); - * d.on('error', (er) => { - * console.error('Caught error!', er); - * }); - * d.run(() => { - * process.nextTick(() => { - * setTimeout(() => { // Simulating some various async stuff - * fs.open('non-existent file', 'r', (er, fd) => { - * if (er) throw er; - * // proceed... - * }); - * }, 100); - * }); - * }); - * ``` - * - * In this example, the `d.on('error')` handler will be triggered, rather - * than crashing the program. - */ - run(fn: (...args: any[]) => T, ...args: any[]): T; - /** - * Explicitly adds an emitter to the domain. If any event handlers called by - * the emitter throw an error, or if the emitter emits an `'error'` event, it - * will be routed to the domain's `'error'` event, just like with implicit - * binding. - * - * This also works with timers that are returned from `setInterval()` and `setTimeout()`. If their callback function throws, it will be caught by - * the domain `'error'` handler. - * - * If the Timer or `EventEmitter` was already bound to a domain, it is removed - * from that one, and bound to this one instead. - * @param emitter emitter or timer to be added to the domain - */ - add(emitter: EventEmitter | NodeJS.Timer): void; - /** - * The opposite of {@link add}. Removes domain handling from the - * specified emitter. - * @param emitter emitter or timer to be removed from the domain - */ - remove(emitter: EventEmitter | NodeJS.Timer): void; - /** - * The returned function will be a wrapper around the supplied callback - * function. When the returned function is called, any errors that are - * thrown will be routed to the domain's `'error'` event. - * - * ```js - * const d = domain.create(); - * - * function readSomeFile(filename, cb) { - * fs.readFile(filename, 'utf8', d.bind((er, data) => { - * // If this throws, it will also be passed to the domain. - * return cb(er, data ? JSON.parse(data) : null); - * })); - * } - * - * d.on('error', (er) => { - * // An error occurred somewhere. If we throw it now, it will crash the program - * // with the normal line number and stack message. - * }); - * ``` - * @param callback The callback function - * @return The bound function - */ - bind(callback: T): T; - /** - * This method is almost identical to {@link bind}. However, in - * addition to catching thrown errors, it will also intercept `Error` objects sent as the first argument to the function. - * - * In this way, the common `if (err) return callback(err);` pattern can be replaced - * with a single error handler in a single place. - * - * ```js - * const d = domain.create(); - * - * function readSomeFile(filename, cb) { - * fs.readFile(filename, 'utf8', d.intercept((data) => { - * // Note, the first argument is never passed to the - * // callback since it is assumed to be the 'Error' argument - * // and thus intercepted by the domain. - * - * // If this throws, it will also be passed to the domain - * // so the error-handling logic can be moved to the 'error' - * // event on the domain instead of being repeated throughout - * // the program. - * return cb(null, JSON.parse(data)); - * })); - * } - * - * d.on('error', (er) => { - * // An error occurred somewhere. If we throw it now, it will crash the program - * // with the normal line number and stack message. - * }); - * ``` - * @param callback The callback function - * @return The intercepted function - */ - intercept(callback: T): T; - } - function create(): Domain; -} -declare module "node:domain" { - export * from "domain"; -} diff --git a/node_modules/@types/node/ts4.8/events.d.ts b/node_modules/@types/node/ts4.8/events.d.ts deleted file mode 100644 index 6ed47c53aa9c2a5d6d4d146aaff9855135036631..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/events.d.ts +++ /dev/null @@ -1,879 +0,0 @@ -/** - * Much of the Node.js core API is built around an idiomatic asynchronous - * event-driven architecture in which certain kinds of objects (called "emitters") - * emit named events that cause `Function` objects ("listeners") to be called. - * - * For instance: a `net.Server` object emits an event each time a peer - * connects to it; a `fs.ReadStream` emits an event when the file is opened; - * a `stream` emits an event whenever data is available to be read. - * - * All objects that emit events are instances of the `EventEmitter` class. These - * objects expose an `eventEmitter.on()` function that allows one or more - * functions to be attached to named events emitted by the object. Typically, - * event names are camel-cased strings but any valid JavaScript property key - * can be used. - * - * When the `EventEmitter` object emits an event, all of the functions attached - * to that specific event are called _synchronously_. Any values returned by the - * called listeners are _ignored_ and discarded. - * - * The following example shows a simple `EventEmitter` instance with a single - * listener. The `eventEmitter.on()` method is used to register listeners, while - * the `eventEmitter.emit()` method is used to trigger the event. - * - * ```js - * import { EventEmitter } from 'node:events'; - * - * class MyEmitter extends EventEmitter {} - * - * const myEmitter = new MyEmitter(); - * myEmitter.on('event', () => { - * console.log('an event occurred!'); - * }); - * myEmitter.emit('event'); - * ``` - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/events.js) - */ -declare module "events" { - import { AsyncResource, AsyncResourceOptions } from "node:async_hooks"; - // NOTE: This class is in the docs but is **not actually exported** by Node. - // If https://github.com/nodejs/node/issues/39903 gets resolved and Node - // actually starts exporting the class, uncomment below. - // import { EventListener, EventListenerObject } from '__dom-events'; - // /** The NodeEventTarget is a Node.js-specific extension to EventTarget that emulates a subset of the EventEmitter API. */ - // interface NodeEventTarget extends EventTarget { - // /** - // * Node.js-specific extension to the `EventTarget` class that emulates the equivalent `EventEmitter` API. - // * The only difference between `addListener()` and `addEventListener()` is that addListener() will return a reference to the EventTarget. - // */ - // addListener(type: string, listener: EventListener | EventListenerObject, options?: { once: boolean }): this; - // /** Node.js-specific extension to the `EventTarget` class that returns an array of event `type` names for which event listeners are registered. */ - // eventNames(): string[]; - // /** Node.js-specific extension to the `EventTarget` class that returns the number of event listeners registered for the `type`. */ - // listenerCount(type: string): number; - // /** Node.js-specific alias for `eventTarget.removeListener()`. */ - // off(type: string, listener: EventListener | EventListenerObject): this; - // /** Node.js-specific alias for `eventTarget.addListener()`. */ - // on(type: string, listener: EventListener | EventListenerObject, options?: { once: boolean }): this; - // /** Node.js-specific extension to the `EventTarget` class that adds a `once` listener for the given event `type`. This is equivalent to calling `on` with the `once` option set to `true`. */ - // once(type: string, listener: EventListener | EventListenerObject): this; - // /** - // * Node.js-specific extension to the `EventTarget` class. - // * If `type` is specified, removes all registered listeners for `type`, - // * otherwise removes all registered listeners. - // */ - // removeAllListeners(type: string): this; - // /** - // * Node.js-specific extension to the `EventTarget` class that removes the listener for the given `type`. - // * The only difference between `removeListener()` and `removeEventListener()` is that `removeListener()` will return a reference to the `EventTarget`. - // */ - // removeListener(type: string, listener: EventListener | EventListenerObject): this; - // } - interface EventEmitterOptions { - /** - * Enables automatic capturing of promise rejection. - */ - captureRejections?: boolean | undefined; - } - // Any EventTarget with a Node-style `once` function - interface _NodeEventTarget { - once(eventName: string | symbol, listener: (...args: any[]) => void): this; - } - // Any EventTarget with a DOM-style `addEventListener` - interface _DOMEventTarget { - addEventListener( - eventName: string, - listener: (...args: any[]) => void, - opts?: { - once: boolean; - }, - ): any; - } - interface StaticEventEmitterOptions { - signal?: AbortSignal | undefined; - } - interface EventEmitter extends NodeJS.EventEmitter {} - /** - * The `EventEmitter` class is defined and exposed by the `node:events` module: - * - * ```js - * import { EventEmitter } from 'node:events'; - * ``` - * - * All `EventEmitter`s emit the event `'newListener'` when new listeners are - * added and `'removeListener'` when existing listeners are removed. - * - * It supports the following option: - * @since v0.1.26 - */ - class EventEmitter { - constructor(options?: EventEmitterOptions); - - [EventEmitter.captureRejectionSymbol]?(error: Error, event: string, ...args: any[]): void; - - /** - * Creates a `Promise` that is fulfilled when the `EventEmitter` emits the given - * event or that is rejected if the `EventEmitter` emits `'error'` while waiting. - * The `Promise` will resolve with an array of all the arguments emitted to the - * given event. - * - * This method is intentionally generic and works with the web platform [EventTarget](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event - * semantics and does not listen to the `'error'` event. - * - * ```js - * import { once, EventEmitter } from 'node:events'; - * import process from 'node:process'; - * - * const ee = new EventEmitter(); - * - * process.nextTick(() => { - * ee.emit('myevent', 42); - * }); - * - * const [value] = await once(ee, 'myevent'); - * console.log(value); - * - * const err = new Error('kaboom'); - * process.nextTick(() => { - * ee.emit('error', err); - * }); - * - * try { - * await once(ee, 'myevent'); - * } catch (err) { - * console.error('error happened', err); - * } - * ``` - * - * The special handling of the `'error'` event is only used when `events.once()`is used to wait for another event. If `events.once()` is used to wait for the - * '`error'` event itself, then it is treated as any other kind of event without - * special handling: - * - * ```js - * import { EventEmitter, once } from 'node:events'; - * - * const ee = new EventEmitter(); - * - * once(ee, 'error') - * .then(([err]) => console.log('ok', err.message)) - * .catch((err) => console.error('error', err.message)); - * - * ee.emit('error', new Error('boom')); - * - * // Prints: ok boom - * ``` - * - * An `AbortSignal` can be used to cancel waiting for the event: - * - * ```js - * import { EventEmitter, once } from 'node:events'; - * - * const ee = new EventEmitter(); - * const ac = new AbortController(); - * - * async function foo(emitter, event, signal) { - * try { - * await once(emitter, event, { signal }); - * console.log('event emitted!'); - * } catch (error) { - * if (error.name === 'AbortError') { - * console.error('Waiting for the event was canceled!'); - * } else { - * console.error('There was an error', error.message); - * } - * } - * } - * - * foo(ee, 'foo', ac.signal); - * ac.abort(); // Abort waiting for the event - * ee.emit('foo'); // Prints: Waiting for the event was canceled! - * ``` - * @since v11.13.0, v10.16.0 - */ - static once( - emitter: _NodeEventTarget, - eventName: string | symbol, - options?: StaticEventEmitterOptions, - ): Promise; - static once(emitter: _DOMEventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise; - /** - * ```js - * import { on, EventEmitter } from 'node:events'; - * import process from 'node:process'; - * - * const ee = new EventEmitter(); - * - * // Emit later on - * process.nextTick(() => { - * ee.emit('foo', 'bar'); - * ee.emit('foo', 42); - * }); - * - * for await (const event of on(ee, 'foo')) { - * // The execution of this inner block is synchronous and it - * // processes one event at a time (even with await). Do not use - * // if concurrent execution is required. - * console.log(event); // prints ['bar'] [42] - * } - * // Unreachable here - * ``` - * - * Returns an `AsyncIterator` that iterates `eventName` events. It will throw - * if the `EventEmitter` emits `'error'`. It removes all listeners when - * exiting the loop. The `value` returned by each iteration is an array - * composed of the emitted event arguments. - * - * An `AbortSignal` can be used to cancel waiting on events: - * - * ```js - * import { on, EventEmitter } from 'node:events'; - * import process from 'node:process'; - * - * const ac = new AbortController(); - * - * (async () => { - * const ee = new EventEmitter(); - * - * // Emit later on - * process.nextTick(() => { - * ee.emit('foo', 'bar'); - * ee.emit('foo', 42); - * }); - * - * for await (const event of on(ee, 'foo', { signal: ac.signal })) { - * // The execution of this inner block is synchronous and it - * // processes one event at a time (even with await). Do not use - * // if concurrent execution is required. - * console.log(event); // prints ['bar'] [42] - * } - * // Unreachable here - * })(); - * - * process.nextTick(() => ac.abort()); - * ``` - * @since v13.6.0, v12.16.0 - * @param eventName The name of the event being listened for - * @return that iterates `eventName` events emitted by the `emitter` - */ - static on( - emitter: NodeJS.EventEmitter, - eventName: string, - options?: StaticEventEmitterOptions, - ): AsyncIterableIterator; - /** - * A class method that returns the number of listeners for the given `eventName`registered on the given `emitter`. - * - * ```js - * import { EventEmitter, listenerCount } from 'node:events'; - * - * const myEmitter = new EventEmitter(); - * myEmitter.on('event', () => {}); - * myEmitter.on('event', () => {}); - * console.log(listenerCount(myEmitter, 'event')); - * // Prints: 2 - * ``` - * @since v0.9.12 - * @deprecated Since v3.2.0 - Use `listenerCount` instead. - * @param emitter The emitter to query - * @param eventName The event name - */ - static listenerCount(emitter: NodeJS.EventEmitter, eventName: string | symbol): number; - /** - * Returns a copy of the array of listeners for the event named `eventName`. - * - * For `EventEmitter`s this behaves exactly the same as calling `.listeners` on - * the emitter. - * - * For `EventTarget`s this is the only way to get the event listeners for the - * event target. This is useful for debugging and diagnostic purposes. - * - * ```js - * import { getEventListeners, EventEmitter } from 'node:events'; - * - * { - * const ee = new EventEmitter(); - * const listener = () => console.log('Events are fun'); - * ee.on('foo', listener); - * console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ] - * } - * { - * const et = new EventTarget(); - * const listener = () => console.log('Events are fun'); - * et.addEventListener('foo', listener); - * console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ] - * } - * ``` - * @since v15.2.0, v14.17.0 - */ - static getEventListeners(emitter: _DOMEventTarget | NodeJS.EventEmitter, name: string | symbol): Function[]; - /** - * Returns the currently set max amount of listeners. - * - * For `EventEmitter`s this behaves exactly the same as calling `.getMaxListeners` on - * the emitter. - * - * For `EventTarget`s this is the only way to get the max event listeners for the - * event target. If the number of event handlers on a single EventTarget exceeds - * the max set, the EventTarget will print a warning. - * - * ```js - * import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events'; - * - * { - * const ee = new EventEmitter(); - * console.log(getMaxListeners(ee)); // 10 - * setMaxListeners(11, ee); - * console.log(getMaxListeners(ee)); // 11 - * } - * { - * const et = new EventTarget(); - * console.log(getMaxListeners(et)); // 10 - * setMaxListeners(11, et); - * console.log(getMaxListeners(et)); // 11 - * } - * ``` - * @since v19.9.0 - */ - static getMaxListeners(emitter: _DOMEventTarget | NodeJS.EventEmitter): number; - /** - * ```js - * import { setMaxListeners, EventEmitter } from 'node:events'; - * - * const target = new EventTarget(); - * const emitter = new EventEmitter(); - * - * setMaxListeners(5, target, emitter); - * ``` - * @since v15.4.0 - * @param n A non-negative number. The maximum number of listeners per `EventTarget` event. - * @param eventsTargets Zero or more {EventTarget} or {EventEmitter} instances. If none are specified, `n` is set as the default max for all newly created {EventTarget} and {EventEmitter} - * objects. - */ - static setMaxListeners(n?: number, ...eventTargets: Array<_DOMEventTarget | NodeJS.EventEmitter>): void; - /** - * Listens once to the `abort` event on the provided `signal`. - * - * Listening to the `abort` event on abort signals is unsafe and may - * lead to resource leaks since another third party with the signal can - * call `e.stopImmediatePropagation()`. Unfortunately Node.js cannot change - * this since it would violate the web standard. Additionally, the original - * API makes it easy to forget to remove listeners. - * - * This API allows safely using `AbortSignal`s in Node.js APIs by solving these - * two issues by listening to the event such that `stopImmediatePropagation` does - * not prevent the listener from running. - * - * Returns a disposable so that it may be unsubscribed from more easily. - * - * ```js - * import { addAbortListener } from 'node:events'; - * - * function example(signal) { - * let disposable; - * try { - * signal.addEventListener('abort', (e) => e.stopImmediatePropagation()); - * disposable = addAbortListener(signal, (e) => { - * // Do something when signal is aborted. - * }); - * } finally { - * disposable?.[Symbol.dispose](); - * } - * } - * ``` - * @since v20.5.0 - * @experimental - * @return Disposable that removes the `abort` listener. - */ - static addAbortListener(signal: AbortSignal, resource: (event: Event) => void): Disposable; - /** - * This symbol shall be used to install a listener for only monitoring `'error'`events. Listeners installed using this symbol are called before the regular`'error'` listeners are called. - * - * Installing a listener using this symbol does not change the behavior once an`'error'` event is emitted. Therefore, the process will still crash if no - * regular `'error'` listener is installed. - * @since v13.6.0, v12.17.0 - */ - static readonly errorMonitor: unique symbol; - /** - * Value: `Symbol.for('nodejs.rejection')` - * - * See how to write a custom `rejection handler`. - * @since v13.4.0, v12.16.0 - */ - static readonly captureRejectionSymbol: unique symbol; - /** - * Value: [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) - * - * Change the default `captureRejections` option on all new `EventEmitter` objects. - * @since v13.4.0, v12.16.0 - */ - static captureRejections: boolean; - /** - * By default, a maximum of `10` listeners can be registered for any single - * event. This limit can be changed for individual `EventEmitter` instances - * using the `emitter.setMaxListeners(n)` method. To change the default - * for _all_`EventEmitter` instances, the `events.defaultMaxListeners`property can be used. If this value is not a positive number, a `RangeError`is thrown. - * - * Take caution when setting the `events.defaultMaxListeners` because the - * change affects _all_`EventEmitter` instances, including those created before - * the change is made. However, calling `emitter.setMaxListeners(n)` still has - * precedence over `events.defaultMaxListeners`. - * - * This is not a hard limit. The `EventEmitter` instance will allow - * more listeners to be added but will output a trace warning to stderr indicating - * that a "possible EventEmitter memory leak" has been detected. For any single`EventEmitter`, the `emitter.getMaxListeners()` and `emitter.setMaxListeners()`methods can be used to - * temporarily avoid this warning: - * - * ```js - * import { EventEmitter } from 'node:events'; - * const emitter = new EventEmitter(); - * emitter.setMaxListeners(emitter.getMaxListeners() + 1); - * emitter.once('event', () => { - * // do stuff - * emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0)); - * }); - * ``` - * - * The `--trace-warnings` command-line flag can be used to display the - * stack trace for such warnings. - * - * The emitted warning can be inspected with `process.on('warning')` and will - * have the additional `emitter`, `type`, and `count` properties, referring to - * the event emitter instance, the event's name and the number of attached - * listeners, respectively. - * Its `name` property is set to `'MaxListenersExceededWarning'`. - * @since v0.11.2 - */ - static defaultMaxListeners: number; - } - import internal = require("node:events"); - namespace EventEmitter { - // Should just be `export { EventEmitter }`, but that doesn't work in TypeScript 3.4 - export { internal as EventEmitter }; - export interface Abortable { - /** - * When provided the corresponding `AbortController` can be used to cancel an asynchronous action. - */ - signal?: AbortSignal | undefined; - } - - export interface EventEmitterReferencingAsyncResource extends AsyncResource { - readonly eventEmitter: EventEmitterAsyncResource; - } - - export interface EventEmitterAsyncResourceOptions extends AsyncResourceOptions, EventEmitterOptions { - /** - * The type of async event, this is required when instantiating `EventEmitterAsyncResource` - * directly rather than as a child class. - * @default new.target.name if instantiated as a child class. - */ - name?: string; - } - - /** - * Integrates `EventEmitter` with `AsyncResource` for `EventEmitter`s that - * require manual async tracking. Specifically, all events emitted by instances - * of `events.EventEmitterAsyncResource` will run within its `async context`. - * - * ```js - * import { EventEmitterAsyncResource, EventEmitter } from 'node:events'; - * import { notStrictEqual, strictEqual } from 'node:assert'; - * import { executionAsyncId, triggerAsyncId } from 'node:async_hooks'; - * - * // Async tracking tooling will identify this as 'Q'. - * const ee1 = new EventEmitterAsyncResource({ name: 'Q' }); - * - * // 'foo' listeners will run in the EventEmitters async context. - * ee1.on('foo', () => { - * strictEqual(executionAsyncId(), ee1.asyncId); - * strictEqual(triggerAsyncId(), ee1.triggerAsyncId); - * }); - * - * const ee2 = new EventEmitter(); - * - * // 'foo' listeners on ordinary EventEmitters that do not track async - * // context, however, run in the same async context as the emit(). - * ee2.on('foo', () => { - * notStrictEqual(executionAsyncId(), ee2.asyncId); - * notStrictEqual(triggerAsyncId(), ee2.triggerAsyncId); - * }); - * - * Promise.resolve().then(() => { - * ee1.emit('foo'); - * ee2.emit('foo'); - * }); - * ``` - * - * The `EventEmitterAsyncResource` class has the same methods and takes the - * same options as `EventEmitter` and `AsyncResource` themselves. - * @since v17.4.0, v16.14.0 - */ - export class EventEmitterAsyncResource extends EventEmitter { - /** - * @param options Only optional in child class. - */ - constructor(options?: EventEmitterAsyncResourceOptions); - /** - * Call all `destroy` hooks. This should only ever be called once. An error will - * be thrown if it is called more than once. This **must** be manually called. If - * the resource is left to be collected by the GC then the `destroy` hooks will - * never be called. - */ - emitDestroy(): void; - /** - * The unique `asyncId` assigned to the resource. - */ - readonly asyncId: number; - /** - * The same triggerAsyncId that is passed to the AsyncResource constructor. - */ - readonly triggerAsyncId: number; - /** - * The returned `AsyncResource` object has an additional `eventEmitter` property - * that provides a reference to this `EventEmitterAsyncResource`. - */ - readonly asyncResource: EventEmitterReferencingAsyncResource; - } - } - global { - namespace NodeJS { - interface EventEmitter { - [EventEmitter.captureRejectionSymbol]?(error: Error, event: string, ...args: any[]): void; - /** - * Alias for `emitter.on(eventName, listener)`. - * @since v0.1.26 - */ - addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; - /** - * Adds the `listener` function to the end of the listeners array for the - * event named `eventName`. No checks are made to see if the `listener` has - * already been added. Multiple calls passing the same combination of `eventName`and `listener` will result in the `listener` being added, and called, multiple - * times. - * - * ```js - * server.on('connection', (stream) => { - * console.log('someone connected!'); - * }); - * ``` - * - * Returns a reference to the `EventEmitter`, so that calls can be chained. - * - * By default, event listeners are invoked in the order they are added. The`emitter.prependListener()` method can be used as an alternative to add the - * event listener to the beginning of the listeners array. - * - * ```js - * import { EventEmitter } from 'node:events'; - * const myEE = new EventEmitter(); - * myEE.on('foo', () => console.log('a')); - * myEE.prependListener('foo', () => console.log('b')); - * myEE.emit('foo'); - * // Prints: - * // b - * // a - * ``` - * @since v0.1.101 - * @param eventName The name of the event. - * @param listener The callback function - */ - on(eventName: string | symbol, listener: (...args: any[]) => void): this; - /** - * Adds a **one-time**`listener` function for the event named `eventName`. The - * next time `eventName` is triggered, this listener is removed and then invoked. - * - * ```js - * server.once('connection', (stream) => { - * console.log('Ah, we have our first user!'); - * }); - * ``` - * - * Returns a reference to the `EventEmitter`, so that calls can be chained. - * - * By default, event listeners are invoked in the order they are added. The`emitter.prependOnceListener()` method can be used as an alternative to add the - * event listener to the beginning of the listeners array. - * - * ```js - * import { EventEmitter } from 'node:events'; - * const myEE = new EventEmitter(); - * myEE.once('foo', () => console.log('a')); - * myEE.prependOnceListener('foo', () => console.log('b')); - * myEE.emit('foo'); - * // Prints: - * // b - * // a - * ``` - * @since v0.3.0 - * @param eventName The name of the event. - * @param listener The callback function - */ - once(eventName: string | symbol, listener: (...args: any[]) => void): this; - /** - * Removes the specified `listener` from the listener array for the event named`eventName`. - * - * ```js - * const callback = (stream) => { - * console.log('someone connected!'); - * }; - * server.on('connection', callback); - * // ... - * server.removeListener('connection', callback); - * ``` - * - * `removeListener()` will remove, at most, one instance of a listener from the - * listener array. If any single listener has been added multiple times to the - * listener array for the specified `eventName`, then `removeListener()` must be - * called multiple times to remove each instance. - * - * Once an event is emitted, all listeners attached to it at the - * time of emitting are called in order. This implies that any`removeListener()` or `removeAllListeners()` calls _after_ emitting and _before_ the last listener finishes execution - * will not remove them from`emit()` in progress. Subsequent events behave as expected. - * - * ```js - * import { EventEmitter } from 'node:events'; - * class MyEmitter extends EventEmitter {} - * const myEmitter = new MyEmitter(); - * - * const callbackA = () => { - * console.log('A'); - * myEmitter.removeListener('event', callbackB); - * }; - * - * const callbackB = () => { - * console.log('B'); - * }; - * - * myEmitter.on('event', callbackA); - * - * myEmitter.on('event', callbackB); - * - * // callbackA removes listener callbackB but it will still be called. - * // Internal listener array at time of emit [callbackA, callbackB] - * myEmitter.emit('event'); - * // Prints: - * // A - * // B - * - * // callbackB is now removed. - * // Internal listener array [callbackA] - * myEmitter.emit('event'); - * // Prints: - * // A - * ``` - * - * Because listeners are managed using an internal array, calling this will - * change the position indices of any listener registered _after_ the listener - * being removed. This will not impact the order in which listeners are called, - * but it means that any copies of the listener array as returned by - * the `emitter.listeners()` method will need to be recreated. - * - * When a single function has been added as a handler multiple times for a single - * event (as in the example below), `removeListener()` will remove the most - * recently added instance. In the example the `once('ping')`listener is removed: - * - * ```js - * import { EventEmitter } from 'node:events'; - * const ee = new EventEmitter(); - * - * function pong() { - * console.log('pong'); - * } - * - * ee.on('ping', pong); - * ee.once('ping', pong); - * ee.removeListener('ping', pong); - * - * ee.emit('ping'); - * ee.emit('ping'); - * ``` - * - * Returns a reference to the `EventEmitter`, so that calls can be chained. - * @since v0.1.26 - */ - removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; - /** - * Alias for `emitter.removeListener()`. - * @since v10.0.0 - */ - off(eventName: string | symbol, listener: (...args: any[]) => void): this; - /** - * Removes all listeners, or those of the specified `eventName`. - * - * It is bad practice to remove listeners added elsewhere in the code, - * particularly when the `EventEmitter` instance was created by some other - * component or module (e.g. sockets or file streams). - * - * Returns a reference to the `EventEmitter`, so that calls can be chained. - * @since v0.1.26 - */ - removeAllListeners(event?: string | symbol): this; - /** - * By default `EventEmitter`s will print a warning if more than `10` listeners are - * added for a particular event. This is a useful default that helps finding - * memory leaks. The `emitter.setMaxListeners()` method allows the limit to be - * modified for this specific `EventEmitter` instance. The value can be set to`Infinity` (or `0`) to indicate an unlimited number of listeners. - * - * Returns a reference to the `EventEmitter`, so that calls can be chained. - * @since v0.3.5 - */ - setMaxListeners(n: number): this; - /** - * Returns the current max listener value for the `EventEmitter` which is either - * set by `emitter.setMaxListeners(n)` or defaults to {@link defaultMaxListeners}. - * @since v1.0.0 - */ - getMaxListeners(): number; - /** - * Returns a copy of the array of listeners for the event named `eventName`. - * - * ```js - * server.on('connection', (stream) => { - * console.log('someone connected!'); - * }); - * console.log(util.inspect(server.listeners('connection'))); - * // Prints: [ [Function] ] - * ``` - * @since v0.1.26 - */ - listeners(eventName: string | symbol): Function[]; - /** - * Returns a copy of the array of listeners for the event named `eventName`, - * including any wrappers (such as those created by `.once()`). - * - * ```js - * import { EventEmitter } from 'node:events'; - * const emitter = new EventEmitter(); - * emitter.once('log', () => console.log('log once')); - * - * // Returns a new Array with a function `onceWrapper` which has a property - * // `listener` which contains the original listener bound above - * const listeners = emitter.rawListeners('log'); - * const logFnWrapper = listeners[0]; - * - * // Logs "log once" to the console and does not unbind the `once` event - * logFnWrapper.listener(); - * - * // Logs "log once" to the console and removes the listener - * logFnWrapper(); - * - * emitter.on('log', () => console.log('log persistently')); - * // Will return a new Array with a single function bound by `.on()` above - * const newListeners = emitter.rawListeners('log'); - * - * // Logs "log persistently" twice - * newListeners[0](); - * emitter.emit('log'); - * ``` - * @since v9.4.0 - */ - rawListeners(eventName: string | symbol): Function[]; - /** - * Synchronously calls each of the listeners registered for the event named`eventName`, in the order they were registered, passing the supplied arguments - * to each. - * - * Returns `true` if the event had listeners, `false` otherwise. - * - * ```js - * import { EventEmitter } from 'node:events'; - * const myEmitter = new EventEmitter(); - * - * // First listener - * myEmitter.on('event', function firstListener() { - * console.log('Helloooo! first listener'); - * }); - * // Second listener - * myEmitter.on('event', function secondListener(arg1, arg2) { - * console.log(`event with parameters ${arg1}, ${arg2} in second listener`); - * }); - * // Third listener - * myEmitter.on('event', function thirdListener(...args) { - * const parameters = args.join(', '); - * console.log(`event with parameters ${parameters} in third listener`); - * }); - * - * console.log(myEmitter.listeners('event')); - * - * myEmitter.emit('event', 1, 2, 3, 4, 5); - * - * // Prints: - * // [ - * // [Function: firstListener], - * // [Function: secondListener], - * // [Function: thirdListener] - * // ] - * // Helloooo! first listener - * // event with parameters 1, 2 in second listener - * // event with parameters 1, 2, 3, 4, 5 in third listener - * ``` - * @since v0.1.26 - */ - emit(eventName: string | symbol, ...args: any[]): boolean; - /** - * Returns the number of listeners listening for the event named `eventName`. - * If `listener` is provided, it will return how many times the listener is found - * in the list of the listeners of the event. - * @since v3.2.0 - * @param eventName The name of the event being listened for - * @param listener The event handler function - */ - listenerCount(eventName: string | symbol, listener?: Function): number; - /** - * Adds the `listener` function to the _beginning_ of the listeners array for the - * event named `eventName`. No checks are made to see if the `listener` has - * already been added. Multiple calls passing the same combination of `eventName`and `listener` will result in the `listener` being added, and called, multiple - * times. - * - * ```js - * server.prependListener('connection', (stream) => { - * console.log('someone connected!'); - * }); - * ``` - * - * Returns a reference to the `EventEmitter`, so that calls can be chained. - * @since v6.0.0 - * @param eventName The name of the event. - * @param listener The callback function - */ - prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; - /** - * Adds a **one-time**`listener` function for the event named `eventName` to the _beginning_ of the listeners array. The next time `eventName` is triggered, this - * listener is removed, and then invoked. - * - * ```js - * server.prependOnceListener('connection', (stream) => { - * console.log('Ah, we have our first user!'); - * }); - * ``` - * - * Returns a reference to the `EventEmitter`, so that calls can be chained. - * @since v6.0.0 - * @param eventName The name of the event. - * @param listener The callback function - */ - prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; - /** - * Returns an array listing the events for which the emitter has registered - * listeners. The values in the array are strings or `Symbol`s. - * - * ```js - * import { EventEmitter } from 'node:events'; - * - * const myEE = new EventEmitter(); - * myEE.on('foo', () => {}); - * myEE.on('bar', () => {}); - * - * const sym = Symbol('symbol'); - * myEE.on(sym, () => {}); - * - * console.log(myEE.eventNames()); - * // Prints: [ 'foo', 'bar', Symbol(symbol) ] - * ``` - * @since v6.0.0 - */ - eventNames(): Array; - } - } - } - export = EventEmitter; -} -declare module "node:events" { - import events = require("events"); - export = events; -} diff --git a/node_modules/@types/node/ts4.8/fs.d.ts b/node_modules/@types/node/ts4.8/fs.d.ts deleted file mode 100644 index 5cbca12fce3886269ec0648145cb6626be34fdc1..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/fs.d.ts +++ /dev/null @@ -1,4311 +0,0 @@ -/** - * The `node:fs` module enables interacting with the file system in a - * way modeled on standard POSIX functions. - * - * To use the promise-based APIs: - * - * ```js - * import * as fs from 'node:fs/promises'; - * ``` - * - * To use the callback and sync APIs: - * - * ```js - * import * as fs from 'node:fs'; - * ``` - * - * All file system operations have synchronous, callback, and promise-based - * forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM). - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/fs.js) - */ -declare module "fs" { - import * as stream from "node:stream"; - import { Abortable, EventEmitter } from "node:events"; - import { URL } from "node:url"; - import * as promises from "node:fs/promises"; - export { promises }; - /** - * Valid types for path values in "fs". - */ - export type PathLike = string | Buffer | URL; - export type PathOrFileDescriptor = PathLike | number; - export type TimeLike = string | number | Date; - export type NoParamCallback = (err: NodeJS.ErrnoException | null) => void; - export type BufferEncodingOption = - | "buffer" - | { - encoding: "buffer"; - }; - export interface ObjectEncodingOptions { - encoding?: BufferEncoding | null | undefined; - } - export type EncodingOption = ObjectEncodingOptions | BufferEncoding | undefined | null; - export type OpenMode = number | string; - export type Mode = number | string; - export interface StatsBase { - isFile(): boolean; - isDirectory(): boolean; - isBlockDevice(): boolean; - isCharacterDevice(): boolean; - isSymbolicLink(): boolean; - isFIFO(): boolean; - isSocket(): boolean; - dev: T; - ino: T; - mode: T; - nlink: T; - uid: T; - gid: T; - rdev: T; - size: T; - blksize: T; - blocks: T; - atimeMs: T; - mtimeMs: T; - ctimeMs: T; - birthtimeMs: T; - atime: Date; - mtime: Date; - ctime: Date; - birthtime: Date; - } - export interface Stats extends StatsBase {} - /** - * A `fs.Stats` object provides information about a file. - * - * Objects returned from {@link stat}, {@link lstat}, {@link fstat}, and - * their synchronous counterparts are of this type. - * If `bigint` in the `options` passed to those methods is true, the numeric values - * will be `bigint` instead of `number`, and the object will contain additional - * nanosecond-precision properties suffixed with `Ns`. - * - * ```console - * Stats { - * dev: 2114, - * ino: 48064969, - * mode: 33188, - * nlink: 1, - * uid: 85, - * gid: 100, - * rdev: 0, - * size: 527, - * blksize: 4096, - * blocks: 8, - * atimeMs: 1318289051000.1, - * mtimeMs: 1318289051000.1, - * ctimeMs: 1318289051000.1, - * birthtimeMs: 1318289051000.1, - * atime: Mon, 10 Oct 2011 23:24:11 GMT, - * mtime: Mon, 10 Oct 2011 23:24:11 GMT, - * ctime: Mon, 10 Oct 2011 23:24:11 GMT, - * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } - * ``` - * - * `bigint` version: - * - * ```console - * BigIntStats { - * dev: 2114n, - * ino: 48064969n, - * mode: 33188n, - * nlink: 1n, - * uid: 85n, - * gid: 100n, - * rdev: 0n, - * size: 527n, - * blksize: 4096n, - * blocks: 8n, - * atimeMs: 1318289051000n, - * mtimeMs: 1318289051000n, - * ctimeMs: 1318289051000n, - * birthtimeMs: 1318289051000n, - * atimeNs: 1318289051000000000n, - * mtimeNs: 1318289051000000000n, - * ctimeNs: 1318289051000000000n, - * birthtimeNs: 1318289051000000000n, - * atime: Mon, 10 Oct 2011 23:24:11 GMT, - * mtime: Mon, 10 Oct 2011 23:24:11 GMT, - * ctime: Mon, 10 Oct 2011 23:24:11 GMT, - * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } - * ``` - * @since v0.1.21 - */ - export class Stats {} - export interface StatsFsBase { - /** Type of file system. */ - type: T; - /** Optimal transfer block size. */ - bsize: T; - /** Total data blocks in file system. */ - blocks: T; - /** Free blocks in file system. */ - bfree: T; - /** Available blocks for unprivileged users */ - bavail: T; - /** Total file nodes in file system. */ - files: T; - /** Free file nodes in file system. */ - ffree: T; - } - export interface StatsFs extends StatsFsBase {} - /** - * Provides information about a mounted file system. - * - * Objects returned from {@link statfs} and its synchronous counterpart are of - * this type. If `bigint` in the `options` passed to those methods is `true`, the - * numeric values will be `bigint` instead of `number`. - * - * ```console - * StatFs { - * type: 1397114950, - * bsize: 4096, - * blocks: 121938943, - * bfree: 61058895, - * bavail: 61058895, - * files: 999, - * ffree: 1000000 - * } - * ``` - * - * `bigint` version: - * - * ```console - * StatFs { - * type: 1397114950n, - * bsize: 4096n, - * blocks: 121938943n, - * bfree: 61058895n, - * bavail: 61058895n, - * files: 999n, - * ffree: 1000000n - * } - * ``` - * @since v19.6.0, v18.15.0 - */ - export class StatsFs {} - export interface BigIntStatsFs extends StatsFsBase {} - export interface StatFsOptions { - bigint?: boolean | undefined; - } - /** - * A representation of a directory entry, which can be a file or a subdirectory - * within the directory, as returned by reading from an `fs.Dir`. The - * directory entry is a combination of the file name and file type pairs. - * - * Additionally, when {@link readdir} or {@link readdirSync} is called with - * the `withFileTypes` option set to `true`, the resulting array is filled with `fs.Dirent` objects, rather than strings or `Buffer` s. - * @since v10.10.0 - */ - export class Dirent { - /** - * Returns `true` if the `fs.Dirent` object describes a regular file. - * @since v10.10.0 - */ - isFile(): boolean; - /** - * Returns `true` if the `fs.Dirent` object describes a file system - * directory. - * @since v10.10.0 - */ - isDirectory(): boolean; - /** - * Returns `true` if the `fs.Dirent` object describes a block device. - * @since v10.10.0 - */ - isBlockDevice(): boolean; - /** - * Returns `true` if the `fs.Dirent` object describes a character device. - * @since v10.10.0 - */ - isCharacterDevice(): boolean; - /** - * Returns `true` if the `fs.Dirent` object describes a symbolic link. - * @since v10.10.0 - */ - isSymbolicLink(): boolean; - /** - * Returns `true` if the `fs.Dirent` object describes a first-in-first-out - * (FIFO) pipe. - * @since v10.10.0 - */ - isFIFO(): boolean; - /** - * Returns `true` if the `fs.Dirent` object describes a socket. - * @since v10.10.0 - */ - isSocket(): boolean; - /** - * The file name that this `fs.Dirent` object refers to. The type of this - * value is determined by the `options.encoding` passed to {@link readdir} or {@link readdirSync}. - * @since v10.10.0 - */ - name: string; - /** - * The base path that this `fs.Dirent` object refers to. - * @since v20.1.0 - */ - path: string; - } - /** - * A class representing a directory stream. - * - * Created by {@link opendir}, {@link opendirSync}, or `fsPromises.opendir()`. - * - * ```js - * import { opendir } from 'node:fs/promises'; - * - * try { - * const dir = await opendir('./'); - * for await (const dirent of dir) - * console.log(dirent.name); - * } catch (err) { - * console.error(err); - * } - * ``` - * - * When using the async iterator, the `fs.Dir` object will be automatically - * closed after the iterator exits. - * @since v12.12.0 - */ - export class Dir implements AsyncIterable { - /** - * The read-only path of this directory as was provided to {@link opendir},{@link opendirSync}, or `fsPromises.opendir()`. - * @since v12.12.0 - */ - readonly path: string; - /** - * Asynchronously iterates over the directory via `readdir(3)` until all entries have been read. - */ - [Symbol.asyncIterator](): AsyncIterableIterator; - /** - * Asynchronously close the directory's underlying resource handle. - * Subsequent reads will result in errors. - * - * A promise is returned that will be fulfilled after the resource has been - * closed. - * @since v12.12.0 - */ - close(): Promise; - close(cb: NoParamCallback): void; - /** - * Synchronously close the directory's underlying resource handle. - * Subsequent reads will result in errors. - * @since v12.12.0 - */ - closeSync(): void; - /** - * Asynchronously read the next directory entry via [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) as an `fs.Dirent`. - * - * A promise is returned that will be fulfilled with an `fs.Dirent`, or `null`if there are no more directory entries to read. - * - * Directory entries returned by this function are in no particular order as - * provided by the operating system's underlying directory mechanisms. - * Entries added or removed while iterating over the directory might not be - * included in the iteration results. - * @since v12.12.0 - * @return containing {fs.Dirent|null} - */ - read(): Promise; - read(cb: (err: NodeJS.ErrnoException | null, dirEnt: Dirent | null) => void): void; - /** - * Synchronously read the next directory entry as an `fs.Dirent`. See the - * POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more detail. - * - * If there are no more directory entries to read, `null` will be returned. - * - * Directory entries returned by this function are in no particular order as - * provided by the operating system's underlying directory mechanisms. - * Entries added or removed while iterating over the directory might not be - * included in the iteration results. - * @since v12.12.0 - */ - readSync(): Dirent | null; - } - /** - * Class: fs.StatWatcher - * @since v14.3.0, v12.20.0 - * Extends `EventEmitter` - * A successful call to {@link watchFile} method will return a new fs.StatWatcher object. - */ - export interface StatWatcher extends EventEmitter { - /** - * When called, requests that the Node.js event loop _not_ exit so long as the `fs.StatWatcher` is active. Calling `watcher.ref()` multiple times will have - * no effect. - * - * By default, all `fs.StatWatcher` objects are "ref'ed", making it normally - * unnecessary to call `watcher.ref()` unless `watcher.unref()` had been - * called previously. - * @since v14.3.0, v12.20.0 - */ - ref(): this; - /** - * When called, the active `fs.StatWatcher` object will not require the Node.js - * event loop to remain active. If there is no other activity keeping the - * event loop running, the process may exit before the `fs.StatWatcher` object's - * callback is invoked. Calling `watcher.unref()` multiple times will have - * no effect. - * @since v14.3.0, v12.20.0 - */ - unref(): this; - } - export interface FSWatcher extends EventEmitter { - /** - * Stop watching for changes on the given `fs.FSWatcher`. Once stopped, the `fs.FSWatcher` object is no longer usable. - * @since v0.5.8 - */ - close(): void; - /** - * When called, requests that the Node.js event loop _not_ exit so long as the `fs.FSWatcher` is active. Calling `watcher.ref()` multiple times will have - * no effect. - * - * By default, all `fs.FSWatcher` objects are "ref'ed", making it normally - * unnecessary to call `watcher.ref()` unless `watcher.unref()` had been - * called previously. - * @since v14.3.0, v12.20.0 - */ - ref(): this; - /** - * When called, the active `fs.FSWatcher` object will not require the Node.js - * event loop to remain active. If there is no other activity keeping the - * event loop running, the process may exit before the `fs.FSWatcher` object's - * callback is invoked. Calling `watcher.unref()` multiple times will have - * no effect. - * @since v14.3.0, v12.20.0 - */ - unref(): this; - /** - * events.EventEmitter - * 1. change - * 2. close - * 3. error - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "error", listener: (error: Error) => void): this; - on(event: string, listener: (...args: any[]) => void): this; - on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - on(event: "close", listener: () => void): this; - on(event: "error", listener: (error: Error) => void): this; - once(event: string, listener: (...args: any[]) => void): this; - once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - once(event: "close", listener: () => void): this; - once(event: "error", listener: (error: Error) => void): this; - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "error", listener: (error: Error) => void): this; - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "error", listener: (error: Error) => void): this; - } - /** - * Instances of `fs.ReadStream` are created and returned using the {@link createReadStream} function. - * @since v0.1.93 - */ - export class ReadStream extends stream.Readable { - close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; - /** - * The number of bytes that have been read so far. - * @since v6.4.0 - */ - bytesRead: number; - /** - * The path to the file the stream is reading from as specified in the first - * argument to `fs.createReadStream()`. If `path` is passed as a string, then`readStream.path` will be a string. If `path` is passed as a `Buffer`, then`readStream.path` will be a - * `Buffer`. If `fd` is specified, then`readStream.path` will be `undefined`. - * @since v0.1.93 - */ - path: string | Buffer; - /** - * This property is `true` if the underlying file has not been opened yet, - * i.e. before the `'ready'` event is emitted. - * @since v11.2.0, v10.16.0 - */ - pending: boolean; - /** - * events.EventEmitter - * 1. open - * 2. close - * 3. ready - */ - addListener(event: "close", listener: () => void): this; - addListener(event: "data", listener: (chunk: Buffer | string) => void): this; - addListener(event: "end", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "open", listener: (fd: number) => void): this; - addListener(event: "pause", listener: () => void): this; - addListener(event: "readable", listener: () => void): this; - addListener(event: "ready", listener: () => void): this; - addListener(event: "resume", listener: () => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - on(event: "close", listener: () => void): this; - on(event: "data", listener: (chunk: Buffer | string) => void): this; - on(event: "end", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "open", listener: (fd: number) => void): this; - on(event: "pause", listener: () => void): this; - on(event: "readable", listener: () => void): this; - on(event: "ready", listener: () => void): this; - on(event: "resume", listener: () => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: "close", listener: () => void): this; - once(event: "data", listener: (chunk: Buffer | string) => void): this; - once(event: "end", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "open", listener: (fd: number) => void): this; - once(event: "pause", listener: () => void): this; - once(event: "readable", listener: () => void): this; - once(event: "ready", listener: () => void): this; - once(event: "resume", listener: () => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; - prependListener(event: "end", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "open", listener: (fd: number) => void): this; - prependListener(event: "pause", listener: () => void): this; - prependListener(event: "readable", listener: () => void): this; - prependListener(event: "ready", listener: () => void): this; - prependListener(event: "resume", listener: () => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; - prependOnceListener(event: "end", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "open", listener: (fd: number) => void): this; - prependOnceListener(event: "pause", listener: () => void): this; - prependOnceListener(event: "readable", listener: () => void): this; - prependOnceListener(event: "ready", listener: () => void): this; - prependOnceListener(event: "resume", listener: () => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - } - /** - * * Extends `stream.Writable` - * - * Instances of `fs.WriteStream` are created and returned using the {@link createWriteStream} function. - * @since v0.1.93 - */ - export class WriteStream extends stream.Writable { - /** - * Closes `writeStream`. Optionally accepts a - * callback that will be executed once the `writeStream`is closed. - * @since v0.9.4 - */ - close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; - /** - * The number of bytes written so far. Does not include data that is still queued - * for writing. - * @since v0.4.7 - */ - bytesWritten: number; - /** - * The path to the file the stream is writing to as specified in the first - * argument to {@link createWriteStream}. If `path` is passed as a string, then`writeStream.path` will be a string. If `path` is passed as a `Buffer`, then`writeStream.path` will be a - * `Buffer`. - * @since v0.1.93 - */ - path: string | Buffer; - /** - * This property is `true` if the underlying file has not been opened yet, - * i.e. before the `'ready'` event is emitted. - * @since v11.2.0 - */ - pending: boolean; - /** - * events.EventEmitter - * 1. open - * 2. close - * 3. ready - */ - addListener(event: "close", listener: () => void): this; - addListener(event: "drain", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "finish", listener: () => void): this; - addListener(event: "open", listener: (fd: number) => void): this; - addListener(event: "pipe", listener: (src: stream.Readable) => void): this; - addListener(event: "ready", listener: () => void): this; - addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - on(event: "close", listener: () => void): this; - on(event: "drain", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "finish", listener: () => void): this; - on(event: "open", listener: (fd: number) => void): this; - on(event: "pipe", listener: (src: stream.Readable) => void): this; - on(event: "ready", listener: () => void): this; - on(event: "unpipe", listener: (src: stream.Readable) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: "close", listener: () => void): this; - once(event: "drain", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "finish", listener: () => void): this; - once(event: "open", listener: (fd: number) => void): this; - once(event: "pipe", listener: (src: stream.Readable) => void): this; - once(event: "ready", listener: () => void): this; - once(event: "unpipe", listener: (src: stream.Readable) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "drain", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "finish", listener: () => void): this; - prependListener(event: "open", listener: (fd: number) => void): this; - prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; - prependListener(event: "ready", listener: () => void): this; - prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "drain", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "finish", listener: () => void): this; - prependOnceListener(event: "open", listener: (fd: number) => void): this; - prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; - prependOnceListener(event: "ready", listener: () => void): this; - prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - } - /** - * Asynchronously rename file at `oldPath` to the pathname provided - * as `newPath`. In the case that `newPath` already exists, it will - * be overwritten. If there is a directory at `newPath`, an error will - * be raised instead. No arguments other than a possible exception are - * given to the completion callback. - * - * See also: [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html). - * - * ```js - * import { rename } from 'node:fs'; - * - * rename('oldFile.txt', 'newFile.txt', (err) => { - * if (err) throw err; - * console.log('Rename complete!'); - * }); - * ``` - * @since v0.0.2 - */ - export function rename(oldPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; - export namespace rename { - /** - * Asynchronous rename(2) - Change the name or location of a file or directory. - * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function __promisify__(oldPath: PathLike, newPath: PathLike): Promise; - } - /** - * Renames the file from `oldPath` to `newPath`. Returns `undefined`. - * - * See the POSIX [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html) documentation for more details. - * @since v0.1.21 - */ - export function renameSync(oldPath: PathLike, newPath: PathLike): void; - /** - * Truncates the file. No arguments other than a possible exception are - * given to the completion callback. A file descriptor can also be passed as the - * first argument. In this case, `fs.ftruncate()` is called. - * - * ```js - * import { truncate } from 'node:fs'; - * // Assuming that 'path/file.txt' is a regular file. - * truncate('path/file.txt', (err) => { - * if (err) throw err; - * console.log('path/file.txt was truncated'); - * }); - * ``` - * - * Passing a file descriptor is deprecated and may result in an error being thrown - * in the future. - * - * See the POSIX [`truncate(2)`](http://man7.org/linux/man-pages/man2/truncate.2.html) documentation for more details. - * @since v0.8.6 - * @param [len=0] - */ - export function truncate(path: PathLike, len: number | undefined | null, callback: NoParamCallback): void; - /** - * Asynchronous truncate(2) - Truncate a file to a specified length. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function truncate(path: PathLike, callback: NoParamCallback): void; - export namespace truncate { - /** - * Asynchronous truncate(2) - Truncate a file to a specified length. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param len If not specified, defaults to `0`. - */ - function __promisify__(path: PathLike, len?: number | null): Promise; - } - /** - * Truncates the file. Returns `undefined`. A file descriptor can also be - * passed as the first argument. In this case, `fs.ftruncateSync()` is called. - * - * Passing a file descriptor is deprecated and may result in an error being thrown - * in the future. - * @since v0.8.6 - * @param [len=0] - */ - export function truncateSync(path: PathLike, len?: number | null): void; - /** - * Truncates the file descriptor. No arguments other than a possible exception are - * given to the completion callback. - * - * See the POSIX [`ftruncate(2)`](http://man7.org/linux/man-pages/man2/ftruncate.2.html) documentation for more detail. - * - * If the file referred to by the file descriptor was larger than `len` bytes, only - * the first `len` bytes will be retained in the file. - * - * For example, the following program retains only the first four bytes of the - * file: - * - * ```js - * import { open, close, ftruncate } from 'node:fs'; - * - * function closeFd(fd) { - * close(fd, (err) => { - * if (err) throw err; - * }); - * } - * - * open('temp.txt', 'r+', (err, fd) => { - * if (err) throw err; - * - * try { - * ftruncate(fd, 4, (err) => { - * closeFd(fd); - * if (err) throw err; - * }); - * } catch (err) { - * closeFd(fd); - * if (err) throw err; - * } - * }); - * ``` - * - * If the file previously was shorter than `len` bytes, it is extended, and the - * extended part is filled with null bytes (`'\0'`): - * - * If `len` is negative then `0` will be used. - * @since v0.8.6 - * @param [len=0] - */ - export function ftruncate(fd: number, len: number | undefined | null, callback: NoParamCallback): void; - /** - * Asynchronous ftruncate(2) - Truncate a file to a specified length. - * @param fd A file descriptor. - */ - export function ftruncate(fd: number, callback: NoParamCallback): void; - export namespace ftruncate { - /** - * Asynchronous ftruncate(2) - Truncate a file to a specified length. - * @param fd A file descriptor. - * @param len If not specified, defaults to `0`. - */ - function __promisify__(fd: number, len?: number | null): Promise; - } - /** - * Truncates the file descriptor. Returns `undefined`. - * - * For detailed information, see the documentation of the asynchronous version of - * this API: {@link ftruncate}. - * @since v0.8.6 - * @param [len=0] - */ - export function ftruncateSync(fd: number, len?: number | null): void; - /** - * Asynchronously changes owner and group of a file. No arguments other than a - * possible exception are given to the completion callback. - * - * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. - * @since v0.1.97 - */ - export function chown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; - export namespace chown { - /** - * Asynchronous chown(2) - Change ownership of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(path: PathLike, uid: number, gid: number): Promise; - } - /** - * Synchronously changes owner and group of a file. Returns `undefined`. - * This is the synchronous version of {@link chown}. - * - * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. - * @since v0.1.97 - */ - export function chownSync(path: PathLike, uid: number, gid: number): void; - /** - * Sets the owner of the file. No arguments other than a possible exception are - * given to the completion callback. - * - * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. - * @since v0.4.7 - */ - export function fchown(fd: number, uid: number, gid: number, callback: NoParamCallback): void; - export namespace fchown { - /** - * Asynchronous fchown(2) - Change ownership of a file. - * @param fd A file descriptor. - */ - function __promisify__(fd: number, uid: number, gid: number): Promise; - } - /** - * Sets the owner of the file. Returns `undefined`. - * - * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. - * @since v0.4.7 - * @param uid The file's new owner's user id. - * @param gid The file's new group's group id. - */ - export function fchownSync(fd: number, uid: number, gid: number): void; - /** - * Set the owner of the symbolic link. No arguments other than a possible - * exception are given to the completion callback. - * - * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more detail. - */ - export function lchown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; - export namespace lchown { - /** - * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(path: PathLike, uid: number, gid: number): Promise; - } - /** - * Set the owner for the path. Returns `undefined`. - * - * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more details. - * @param uid The file's new owner's user id. - * @param gid The file's new group's group id. - */ - export function lchownSync(path: PathLike, uid: number, gid: number): void; - /** - * Changes the access and modification times of a file in the same way as {@link utimes}, with the difference that if the path refers to a symbolic - * link, then the link is not dereferenced: instead, the timestamps of the - * symbolic link itself are changed. - * - * No arguments other than a possible exception are given to the completion - * callback. - * @since v14.5.0, v12.19.0 - */ - export function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; - export namespace lutimes { - /** - * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, - * with the difference that if the path refers to a symbolic link, then the link is not - * dereferenced: instead, the timestamps of the symbolic link itself are changed. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; - } - /** - * Change the file system timestamps of the symbolic link referenced by `path`. - * Returns `undefined`, or throws an exception when parameters are incorrect or - * the operation fails. This is the synchronous version of {@link lutimes}. - * @since v14.5.0, v12.19.0 - */ - export function lutimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; - /** - * Asynchronously changes the permissions of a file. No arguments other than a - * possible exception are given to the completion callback. - * - * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. - * - * ```js - * import { chmod } from 'node:fs'; - * - * chmod('my_file.txt', 0o775, (err) => { - * if (err) throw err; - * console.log('The permissions for file "my_file.txt" have been changed!'); - * }); - * ``` - * @since v0.1.30 - */ - export function chmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; - export namespace chmod { - /** - * Asynchronous chmod(2) - Change permissions of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function __promisify__(path: PathLike, mode: Mode): Promise; - } - /** - * For detailed information, see the documentation of the asynchronous version of - * this API: {@link chmod}. - * - * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. - * @since v0.6.7 - */ - export function chmodSync(path: PathLike, mode: Mode): void; - /** - * Sets the permissions on the file. No arguments other than a possible exception - * are given to the completion callback. - * - * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. - * @since v0.4.7 - */ - export function fchmod(fd: number, mode: Mode, callback: NoParamCallback): void; - export namespace fchmod { - /** - * Asynchronous fchmod(2) - Change permissions of a file. - * @param fd A file descriptor. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function __promisify__(fd: number, mode: Mode): Promise; - } - /** - * Sets the permissions on the file. Returns `undefined`. - * - * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. - * @since v0.4.7 - */ - export function fchmodSync(fd: number, mode: Mode): void; - /** - * Changes the permissions on a symbolic link. No arguments other than a possible - * exception are given to the completion callback. - * - * This method is only implemented on macOS. - * - * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. - * @deprecated Since v0.4.7 - */ - export function lchmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; - /** @deprecated */ - export namespace lchmod { - /** - * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function __promisify__(path: PathLike, mode: Mode): Promise; - } - /** - * Changes the permissions on a symbolic link. Returns `undefined`. - * - * This method is only implemented on macOS. - * - * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. - * @deprecated Since v0.4.7 - */ - export function lchmodSync(path: PathLike, mode: Mode): void; - /** - * Asynchronous [`stat(2)`](http://man7.org/linux/man-pages/man2/stat.2.html). The callback gets two arguments `(err, stats)` where`stats` is an `fs.Stats` object. - * - * In case of an error, the `err.code` will be one of `Common System Errors`. - * - * {@link stat} follows symbolic links. Use {@link lstat} to look at the - * links themselves. - * - * Using `fs.stat()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. - * Instead, user code should open/read/write the file directly and handle the - * error raised if the file is not available. - * - * To check if a file exists without manipulating it afterwards, {@link access} is recommended. - * - * For example, given the following directory structure: - * - * ```text - * - txtDir - * -- file.txt - * - app.js - * ``` - * - * The next program will check for the stats of the given paths: - * - * ```js - * import { stat } from 'node:fs'; - * - * const pathsToCheck = ['./txtDir', './txtDir/file.txt']; - * - * for (let i = 0; i < pathsToCheck.length; i++) { - * stat(pathsToCheck[i], (err, stats) => { - * console.log(stats.isDirectory()); - * console.log(stats); - * }); - * } - * ``` - * - * The resulting output will resemble: - * - * ```console - * true - * Stats { - * dev: 16777220, - * mode: 16877, - * nlink: 3, - * uid: 501, - * gid: 20, - * rdev: 0, - * blksize: 4096, - * ino: 14214262, - * size: 96, - * blocks: 0, - * atimeMs: 1561174653071.963, - * mtimeMs: 1561174614583.3518, - * ctimeMs: 1561174626623.5366, - * birthtimeMs: 1561174126937.2893, - * atime: 2019-06-22T03:37:33.072Z, - * mtime: 2019-06-22T03:36:54.583Z, - * ctime: 2019-06-22T03:37:06.624Z, - * birthtime: 2019-06-22T03:28:46.937Z - * } - * false - * Stats { - * dev: 16777220, - * mode: 33188, - * nlink: 1, - * uid: 501, - * gid: 20, - * rdev: 0, - * blksize: 4096, - * ino: 14214074, - * size: 8, - * blocks: 8, - * atimeMs: 1561174616618.8555, - * mtimeMs: 1561174614584, - * ctimeMs: 1561174614583.8145, - * birthtimeMs: 1561174007710.7478, - * atime: 2019-06-22T03:36:56.619Z, - * mtime: 2019-06-22T03:36:54.584Z, - * ctime: 2019-06-22T03:36:54.584Z, - * birthtime: 2019-06-22T03:26:47.711Z - * } - * ``` - * @since v0.0.2 - */ - export function stat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; - export function stat( - path: PathLike, - options: - | (StatOptions & { - bigint?: false | undefined; - }) - | undefined, - callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, - ): void; - export function stat( - path: PathLike, - options: StatOptions & { - bigint: true; - }, - callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, - ): void; - export function stat( - path: PathLike, - options: StatOptions | undefined, - callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, - ): void; - export namespace stat { - /** - * Asynchronous stat(2) - Get file status. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__( - path: PathLike, - options?: StatOptions & { - bigint?: false | undefined; - }, - ): Promise; - function __promisify__( - path: PathLike, - options: StatOptions & { - bigint: true; - }, - ): Promise; - function __promisify__(path: PathLike, options?: StatOptions): Promise; - } - export interface StatSyncFn extends Function { - (path: PathLike, options?: undefined): Stats; - ( - path: PathLike, - options?: StatSyncOptions & { - bigint?: false | undefined; - throwIfNoEntry: false; - }, - ): Stats | undefined; - ( - path: PathLike, - options: StatSyncOptions & { - bigint: true; - throwIfNoEntry: false; - }, - ): BigIntStats | undefined; - ( - path: PathLike, - options?: StatSyncOptions & { - bigint?: false | undefined; - }, - ): Stats; - ( - path: PathLike, - options: StatSyncOptions & { - bigint: true; - }, - ): BigIntStats; - ( - path: PathLike, - options: StatSyncOptions & { - bigint: boolean; - throwIfNoEntry?: false | undefined; - }, - ): Stats | BigIntStats; - (path: PathLike, options?: StatSyncOptions): Stats | BigIntStats | undefined; - } - /** - * Synchronous stat(2) - Get file status. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export const statSync: StatSyncFn; - /** - * Invokes the callback with the `fs.Stats` for the file descriptor. - * - * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. - * @since v0.1.95 - */ - export function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; - export function fstat( - fd: number, - options: - | (StatOptions & { - bigint?: false | undefined; - }) - | undefined, - callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, - ): void; - export function fstat( - fd: number, - options: StatOptions & { - bigint: true; - }, - callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, - ): void; - export function fstat( - fd: number, - options: StatOptions | undefined, - callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, - ): void; - export namespace fstat { - /** - * Asynchronous fstat(2) - Get file status. - * @param fd A file descriptor. - */ - function __promisify__( - fd: number, - options?: StatOptions & { - bigint?: false | undefined; - }, - ): Promise; - function __promisify__( - fd: number, - options: StatOptions & { - bigint: true; - }, - ): Promise; - function __promisify__(fd: number, options?: StatOptions): Promise; - } - /** - * Retrieves the `fs.Stats` for the file descriptor. - * - * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. - * @since v0.1.95 - */ - export function fstatSync( - fd: number, - options?: StatOptions & { - bigint?: false | undefined; - }, - ): Stats; - export function fstatSync( - fd: number, - options: StatOptions & { - bigint: true; - }, - ): BigIntStats; - export function fstatSync(fd: number, options?: StatOptions): Stats | BigIntStats; - /** - * Retrieves the `fs.Stats` for the symbolic link referred to by the path. - * The callback gets two arguments `(err, stats)` where `stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if `path` is a symbolic - * link, then the link itself is stat-ed, not the file that it refers to. - * - * See the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) documentation for more details. - * @since v0.1.30 - */ - export function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; - export function lstat( - path: PathLike, - options: - | (StatOptions & { - bigint?: false | undefined; - }) - | undefined, - callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, - ): void; - export function lstat( - path: PathLike, - options: StatOptions & { - bigint: true; - }, - callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, - ): void; - export function lstat( - path: PathLike, - options: StatOptions | undefined, - callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, - ): void; - export namespace lstat { - /** - * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__( - path: PathLike, - options?: StatOptions & { - bigint?: false | undefined; - }, - ): Promise; - function __promisify__( - path: PathLike, - options: StatOptions & { - bigint: true; - }, - ): Promise; - function __promisify__(path: PathLike, options?: StatOptions): Promise; - } - /** - * Asynchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which - * contains `path`. The callback gets two arguments `(err, stats)` where `stats`is an `fs.StatFs` object. - * - * In case of an error, the `err.code` will be one of `Common System Errors`. - * @since v19.6.0, v18.15.0 - * @param path A path to an existing file or directory on the file system to be queried. - */ - export function statfs(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: StatsFs) => void): void; - export function statfs( - path: PathLike, - options: - | (StatFsOptions & { - bigint?: false | undefined; - }) - | undefined, - callback: (err: NodeJS.ErrnoException | null, stats: StatsFs) => void, - ): void; - export function statfs( - path: PathLike, - options: StatFsOptions & { - bigint: true; - }, - callback: (err: NodeJS.ErrnoException | null, stats: BigIntStatsFs) => void, - ): void; - export function statfs( - path: PathLike, - options: StatFsOptions | undefined, - callback: (err: NodeJS.ErrnoException | null, stats: StatsFs | BigIntStatsFs) => void, - ): void; - export namespace statfs { - /** - * Asynchronous statfs(2) - Returns information about the mounted file system which contains path. The callback gets two arguments (err, stats) where stats is an object. - * @param path A path to an existing file or directory on the file system to be queried. - */ - function __promisify__( - path: PathLike, - options?: StatFsOptions & { - bigint?: false | undefined; - }, - ): Promise; - function __promisify__( - path: PathLike, - options: StatFsOptions & { - bigint: true; - }, - ): Promise; - function __promisify__(path: PathLike, options?: StatFsOptions): Promise; - } - /** - * Synchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which - * contains `path`. - * - * In case of an error, the `err.code` will be one of `Common System Errors`. - * @since v19.6.0, v18.15.0 - * @param path A path to an existing file or directory on the file system to be queried. - */ - export function statfsSync( - path: PathLike, - options?: StatFsOptions & { - bigint?: false | undefined; - }, - ): StatsFs; - export function statfsSync( - path: PathLike, - options: StatFsOptions & { - bigint: true; - }, - ): BigIntStatsFs; - export function statfsSync(path: PathLike, options?: StatFsOptions): StatsFs | BigIntStatsFs; - /** - * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export const lstatSync: StatSyncFn; - /** - * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. No arguments other than - * a possible - * exception are given to the completion callback. - * @since v0.1.31 - */ - export function link(existingPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; - export namespace link { - /** - * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. - * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(existingPath: PathLike, newPath: PathLike): Promise; - } - /** - * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. Returns `undefined`. - * @since v0.1.31 - */ - export function linkSync(existingPath: PathLike, newPath: PathLike): void; - /** - * Creates the link called `path` pointing to `target`. No arguments other than a - * possible exception are given to the completion callback. - * - * See the POSIX [`symlink(2)`](http://man7.org/linux/man-pages/man2/symlink.2.html) documentation for more details. - * - * The `type` argument is only available on Windows and ignored on other platforms. - * It can be set to `'dir'`, `'file'`, or `'junction'`. If the `type` argument is - * not a string, Node.js will autodetect `target` type and use `'file'` or `'dir'`. - * If the `target` does not exist, `'file'` will be used. Windows junction points - * require the destination path to be absolute. When using `'junction'`, the`target` argument will automatically be normalized to absolute path. Junction - * points on NTFS volumes can only point to directories. - * - * Relative targets are relative to the link's parent directory. - * - * ```js - * import { symlink } from 'node:fs'; - * - * symlink('./mew', './mewtwo', callback); - * ``` - * - * The above example creates a symbolic link `mewtwo` which points to `mew` in the - * same directory: - * - * ```bash - * $ tree . - * . - * ├── mew - * └── mewtwo -> ./mew - * ``` - * @since v0.1.31 - * @param [type='null'] - */ - export function symlink( - target: PathLike, - path: PathLike, - type: symlink.Type | undefined | null, - callback: NoParamCallback, - ): void; - /** - * Asynchronous symlink(2) - Create a new symbolic link to an existing file. - * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. - * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. - */ - export function symlink(target: PathLike, path: PathLike, callback: NoParamCallback): void; - export namespace symlink { - /** - * Asynchronous symlink(2) - Create a new symbolic link to an existing file. - * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. - * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. - * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). - * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. - */ - function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise; - type Type = "dir" | "file" | "junction"; - } - /** - * Returns `undefined`. - * - * For detailed information, see the documentation of the asynchronous version of - * this API: {@link symlink}. - * @since v0.1.31 - * @param [type='null'] - */ - export function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; - /** - * Reads the contents of the symbolic link referred to by `path`. The callback gets - * two arguments `(err, linkString)`. - * - * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. - * - * The optional `options` argument can be a string specifying an encoding, or an - * object with an `encoding` property specifying the character encoding to use for - * the link path passed to the callback. If the `encoding` is set to `'buffer'`, - * the link path returned will be passed as a `Buffer` object. - * @since v0.1.31 - */ - export function readlink( - path: PathLike, - options: EncodingOption, - callback: (err: NodeJS.ErrnoException | null, linkString: string) => void, - ): void; - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readlink( - path: PathLike, - options: BufferEncodingOption, - callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void, - ): void; - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readlink( - path: PathLike, - options: EncodingOption, - callback: (err: NodeJS.ErrnoException | null, linkString: string | Buffer) => void, - ): void; - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function readlink( - path: PathLike, - callback: (err: NodeJS.ErrnoException | null, linkString: string) => void, - ): void; - export namespace readlink { - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options?: EncodingOption): Promise; - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options?: EncodingOption): Promise; - } - /** - * Returns the symbolic link's string value. - * - * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. - * - * The optional `options` argument can be a string specifying an encoding, or an - * object with an `encoding` property specifying the character encoding to use for - * the link path returned. If the `encoding` is set to `'buffer'`, - * the link path returned will be passed as a `Buffer` object. - * @since v0.1.31 - */ - export function readlinkSync(path: PathLike, options?: EncodingOption): string; - /** - * Synchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readlinkSync(path: PathLike, options: BufferEncodingOption): Buffer; - /** - * Synchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readlinkSync(path: PathLike, options?: EncodingOption): string | Buffer; - /** - * Asynchronously computes the canonical pathname by resolving `.`, `..`, and - * symbolic links. - * - * A canonical pathname is not necessarily unique. Hard links and bind mounts can - * expose a file system entity through many pathnames. - * - * This function behaves like [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html), with some exceptions: - * - * 1. No case conversion is performed on case-insensitive file systems. - * 2. The maximum number of symbolic links is platform-independent and generally - * (much) higher than what the native [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html) implementation supports. - * - * The `callback` gets two arguments `(err, resolvedPath)`. May use `process.cwd`to resolve relative paths. - * - * Only paths that can be converted to UTF8 strings are supported. - * - * The optional `options` argument can be a string specifying an encoding, or an - * object with an `encoding` property specifying the character encoding to use for - * the path passed to the callback. If the `encoding` is set to `'buffer'`, - * the path returned will be passed as a `Buffer` object. - * - * If `path` resolves to a socket or a pipe, the function will return a system - * dependent name for that object. - * @since v0.1.31 - */ - export function realpath( - path: PathLike, - options: EncodingOption, - callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, - ): void; - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function realpath( - path: PathLike, - options: BufferEncodingOption, - callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void, - ): void; - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function realpath( - path: PathLike, - options: EncodingOption, - callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void, - ): void; - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function realpath( - path: PathLike, - callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, - ): void; - export namespace realpath { - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options?: EncodingOption): Promise; - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options?: EncodingOption): Promise; - /** - * Asynchronous [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html). - * - * The `callback` gets two arguments `(err, resolvedPath)`. - * - * Only paths that can be converted to UTF8 strings are supported. - * - * The optional `options` argument can be a string specifying an encoding, or an - * object with an `encoding` property specifying the character encoding to use for - * the path passed to the callback. If the `encoding` is set to `'buffer'`, - * the path returned will be passed as a `Buffer` object. - * - * On Linux, when Node.js is linked against musl libc, the procfs file system must - * be mounted on `/proc` in order for this function to work. Glibc does not have - * this restriction. - * @since v9.2.0 - */ - function native( - path: PathLike, - options: EncodingOption, - callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, - ): void; - function native( - path: PathLike, - options: BufferEncodingOption, - callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void, - ): void; - function native( - path: PathLike, - options: EncodingOption, - callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void, - ): void; - function native( - path: PathLike, - callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, - ): void; - } - /** - * Returns the resolved pathname. - * - * For detailed information, see the documentation of the asynchronous version of - * this API: {@link realpath}. - * @since v0.1.31 - */ - export function realpathSync(path: PathLike, options?: EncodingOption): string; - /** - * Synchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function realpathSync(path: PathLike, options: BufferEncodingOption): Buffer; - /** - * Synchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function realpathSync(path: PathLike, options?: EncodingOption): string | Buffer; - export namespace realpathSync { - function native(path: PathLike, options?: EncodingOption): string; - function native(path: PathLike, options: BufferEncodingOption): Buffer; - function native(path: PathLike, options?: EncodingOption): string | Buffer; - } - /** - * Asynchronously removes a file or symbolic link. No arguments other than a - * possible exception are given to the completion callback. - * - * ```js - * import { unlink } from 'node:fs'; - * // Assuming that 'path/file.txt' is a regular file. - * unlink('path/file.txt', (err) => { - * if (err) throw err; - * console.log('path/file.txt was deleted'); - * }); - * ``` - * - * `fs.unlink()` will not work on a directory, empty or otherwise. To remove a - * directory, use {@link rmdir}. - * - * See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more details. - * @since v0.0.2 - */ - export function unlink(path: PathLike, callback: NoParamCallback): void; - export namespace unlink { - /** - * Asynchronous unlink(2) - delete a name and possibly the file it refers to. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(path: PathLike): Promise; - } - /** - * Synchronous [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html). Returns `undefined`. - * @since v0.1.21 - */ - export function unlinkSync(path: PathLike): void; - export interface RmDirOptions { - /** - * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or - * `EPERM` error is encountered, Node.js will retry the operation with a linear - * backoff wait of `retryDelay` ms longer on each try. This option represents the - * number of retries. This option is ignored if the `recursive` option is not - * `true`. - * @default 0 - */ - maxRetries?: number | undefined; - /** - * @deprecated since v14.14.0 In future versions of Node.js and will trigger a warning - * `fs.rmdir(path, { recursive: true })` will throw if `path` does not exist or is a file. - * Use `fs.rm(path, { recursive: true, force: true })` instead. - * - * If `true`, perform a recursive directory removal. In - * recursive mode, operations are retried on failure. - * @default false - */ - recursive?: boolean | undefined; - /** - * The amount of time in milliseconds to wait between retries. - * This option is ignored if the `recursive` option is not `true`. - * @default 100 - */ - retryDelay?: number | undefined; - } - /** - * Asynchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). No arguments other than a possible exception are given - * to the completion callback. - * - * Using `fs.rmdir()` on a file (not a directory) results in an `ENOENT` error on - * Windows and an `ENOTDIR` error on POSIX. - * - * To get a behavior similar to the `rm -rf` Unix command, use {@link rm} with options `{ recursive: true, force: true }`. - * @since v0.0.2 - */ - export function rmdir(path: PathLike, callback: NoParamCallback): void; - export function rmdir(path: PathLike, options: RmDirOptions, callback: NoParamCallback): void; - export namespace rmdir { - /** - * Asynchronous rmdir(2) - delete a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(path: PathLike, options?: RmDirOptions): Promise; - } - /** - * Synchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). Returns `undefined`. - * - * Using `fs.rmdirSync()` on a file (not a directory) results in an `ENOENT` error - * on Windows and an `ENOTDIR` error on POSIX. - * - * To get a behavior similar to the `rm -rf` Unix command, use {@link rmSync} with options `{ recursive: true, force: true }`. - * @since v0.1.21 - */ - export function rmdirSync(path: PathLike, options?: RmDirOptions): void; - export interface RmOptions { - /** - * When `true`, exceptions will be ignored if `path` does not exist. - * @default false - */ - force?: boolean | undefined; - /** - * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or - * `EPERM` error is encountered, Node.js will retry the operation with a linear - * backoff wait of `retryDelay` ms longer on each try. This option represents the - * number of retries. This option is ignored if the `recursive` option is not - * `true`. - * @default 0 - */ - maxRetries?: number | undefined; - /** - * If `true`, perform a recursive directory removal. In - * recursive mode, operations are retried on failure. - * @default false - */ - recursive?: boolean | undefined; - /** - * The amount of time in milliseconds to wait between retries. - * This option is ignored if the `recursive` option is not `true`. - * @default 100 - */ - retryDelay?: number | undefined; - } - /** - * Asynchronously removes files and directories (modeled on the standard POSIX `rm`utility). No arguments other than a possible exception are given to the - * completion callback. - * @since v14.14.0 - */ - export function rm(path: PathLike, callback: NoParamCallback): void; - export function rm(path: PathLike, options: RmOptions, callback: NoParamCallback): void; - export namespace rm { - /** - * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). - */ - function __promisify__(path: PathLike, options?: RmOptions): Promise; - } - /** - * Synchronously removes files and directories (modeled on the standard POSIX `rm`utility). Returns `undefined`. - * @since v14.14.0 - */ - export function rmSync(path: PathLike, options?: RmOptions): void; - export interface MakeDirectoryOptions { - /** - * Indicates whether parent folders should be created. - * If a folder was created, the path to the first created folder will be returned. - * @default false - */ - recursive?: boolean | undefined; - /** - * A file mode. If a string is passed, it is parsed as an octal integer. If not specified - * @default 0o777 - */ - mode?: Mode | undefined; - } - /** - * Asynchronously creates a directory. - * - * The callback is given a possible exception and, if `recursive` is `true`, the - * first directory path created, `(err[, path])`.`path` can still be `undefined` when `recursive` is `true`, if no directory was - * created (for instance, if it was previously created). - * - * The optional `options` argument can be an integer specifying `mode` (permission - * and sticky bits), or an object with a `mode` property and a `recursive`property indicating whether parent directories should be created. Calling`fs.mkdir()` when `path` is a directory that - * exists results in an error only - * when `recursive` is false. If `recursive` is false and the directory exists, - * an `EEXIST` error occurs. - * - * ```js - * import { mkdir } from 'node:fs'; - * - * // Create ./tmp/a/apple, regardless of whether ./tmp and ./tmp/a exist. - * mkdir('./tmp/a/apple', { recursive: true }, (err) => { - * if (err) throw err; - * }); - * ``` - * - * On Windows, using `fs.mkdir()` on the root directory even with recursion will - * result in an error: - * - * ```js - * import { mkdir } from 'node:fs'; - * - * mkdir('/', { recursive: true }, (err) => { - * // => [Error: EPERM: operation not permitted, mkdir 'C:\'] - * }); - * ``` - * - * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. - * @since v0.1.8 - */ - export function mkdir( - path: PathLike, - options: MakeDirectoryOptions & { - recursive: true; - }, - callback: (err: NodeJS.ErrnoException | null, path?: string) => void, - ): void; - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - export function mkdir( - path: PathLike, - options: - | Mode - | (MakeDirectoryOptions & { - recursive?: false | undefined; - }) - | null - | undefined, - callback: NoParamCallback, - ): void; - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - export function mkdir( - path: PathLike, - options: Mode | MakeDirectoryOptions | null | undefined, - callback: (err: NodeJS.ErrnoException | null, path?: string) => void, - ): void; - /** - * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function mkdir(path: PathLike, callback: NoParamCallback): void; - export namespace mkdir { - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - function __promisify__( - path: PathLike, - options: MakeDirectoryOptions & { - recursive: true; - }, - ): Promise; - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - function __promisify__( - path: PathLike, - options?: - | Mode - | (MakeDirectoryOptions & { - recursive?: false | undefined; - }) - | null, - ): Promise; - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - function __promisify__( - path: PathLike, - options?: Mode | MakeDirectoryOptions | null, - ): Promise; - } - /** - * Synchronously creates a directory. Returns `undefined`, or if `recursive` is`true`, the first directory path created. - * This is the synchronous version of {@link mkdir}. - * - * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. - * @since v0.1.21 - */ - export function mkdirSync( - path: PathLike, - options: MakeDirectoryOptions & { - recursive: true; - }, - ): string | undefined; - /** - * Synchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - export function mkdirSync( - path: PathLike, - options?: - | Mode - | (MakeDirectoryOptions & { - recursive?: false | undefined; - }) - | null, - ): void; - /** - * Synchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - export function mkdirSync(path: PathLike, options?: Mode | MakeDirectoryOptions | null): string | undefined; - /** - * Creates a unique temporary directory. - * - * Generates six random characters to be appended behind a required`prefix` to create a unique temporary directory. Due to platform - * inconsistencies, avoid trailing `X` characters in `prefix`. Some platforms, - * notably the BSDs, can return more than six random characters, and replace - * trailing `X` characters in `prefix` with random characters. - * - * The created directory path is passed as a string to the callback's second - * parameter. - * - * The optional `options` argument can be a string specifying an encoding, or an - * object with an `encoding` property specifying the character encoding to use. - * - * ```js - * import { mkdtemp } from 'node:fs'; - * import { join } from 'node:path'; - * import { tmpdir } from 'node:os'; - * - * mkdtemp(join(tmpdir(), 'foo-'), (err, directory) => { - * if (err) throw err; - * console.log(directory); - * // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2 - * }); - * ``` - * - * The `fs.mkdtemp()` method will append the six randomly selected characters - * directly to the `prefix` string. For instance, given a directory `/tmp`, if the - * intention is to create a temporary directory _within_`/tmp`, the `prefix`must end with a trailing platform-specific path separator - * (`require('node:path').sep`). - * - * ```js - * import { tmpdir } from 'node:os'; - * import { mkdtemp } from 'node:fs'; - * - * // The parent directory for the new temporary directory - * const tmpDir = tmpdir(); - * - * // This method is *INCORRECT*: - * mkdtemp(tmpDir, (err, directory) => { - * if (err) throw err; - * console.log(directory); - * // Will print something similar to `/tmpabc123`. - * // A new temporary directory is created at the file system root - * // rather than *within* the /tmp directory. - * }); - * - * // This method is *CORRECT*: - * import { sep } from 'node:path'; - * mkdtemp(`${tmpDir}${sep}`, (err, directory) => { - * if (err) throw err; - * console.log(directory); - * // Will print something similar to `/tmp/abc123`. - * // A new temporary directory is created within - * // the /tmp directory. - * }); - * ``` - * @since v5.10.0 - */ - export function mkdtemp( - prefix: string, - options: EncodingOption, - callback: (err: NodeJS.ErrnoException | null, folder: string) => void, - ): void; - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function mkdtemp( - prefix: string, - options: - | "buffer" - | { - encoding: "buffer"; - }, - callback: (err: NodeJS.ErrnoException | null, folder: Buffer) => void, - ): void; - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function mkdtemp( - prefix: string, - options: EncodingOption, - callback: (err: NodeJS.ErrnoException | null, folder: string | Buffer) => void, - ): void; - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - */ - export function mkdtemp( - prefix: string, - callback: (err: NodeJS.ErrnoException | null, folder: string) => void, - ): void; - export namespace mkdtemp { - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(prefix: string, options?: EncodingOption): Promise; - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(prefix: string, options: BufferEncodingOption): Promise; - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(prefix: string, options?: EncodingOption): Promise; - } - /** - * Returns the created directory path. - * - * For detailed information, see the documentation of the asynchronous version of - * this API: {@link mkdtemp}. - * - * The optional `options` argument can be a string specifying an encoding, or an - * object with an `encoding` property specifying the character encoding to use. - * @since v5.10.0 - */ - export function mkdtempSync(prefix: string, options?: EncodingOption): string; - /** - * Synchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function mkdtempSync(prefix: string, options: BufferEncodingOption): Buffer; - /** - * Synchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function mkdtempSync(prefix: string, options?: EncodingOption): string | Buffer; - /** - * Reads the contents of a directory. The callback gets two arguments `(err, files)`where `files` is an array of the names of the files in the directory excluding`'.'` and `'..'`. - * - * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. - * - * The optional `options` argument can be a string specifying an encoding, or an - * object with an `encoding` property specifying the character encoding to use for - * the filenames passed to the callback. If the `encoding` is set to `'buffer'`, - * the filenames returned will be passed as `Buffer` objects. - * - * If `options.withFileTypes` is set to `true`, the `files` array will contain `fs.Dirent` objects. - * @since v0.1.8 - */ - export function readdir( - path: PathLike, - options: - | { - encoding: BufferEncoding | null; - withFileTypes?: false | undefined; - recursive?: boolean | undefined; - } - | BufferEncoding - | undefined - | null, - callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, - ): void; - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readdir( - path: PathLike, - options: - | { - encoding: "buffer"; - withFileTypes?: false | undefined; - recursive?: boolean | undefined; - } - | "buffer", - callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void, - ): void; - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readdir( - path: PathLike, - options: - | (ObjectEncodingOptions & { - withFileTypes?: false | undefined; - recursive?: boolean | undefined; - }) - | BufferEncoding - | undefined - | null, - callback: (err: NodeJS.ErrnoException | null, files: string[] | Buffer[]) => void, - ): void; - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function readdir( - path: PathLike, - callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, - ): void; - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. - */ - export function readdir( - path: PathLike, - options: ObjectEncodingOptions & { - withFileTypes: true; - recursive?: boolean | undefined; - }, - callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void, - ): void; - export namespace readdir { - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__( - path: PathLike, - options?: - | { - encoding: BufferEncoding | null; - withFileTypes?: false | undefined; - recursive?: boolean | undefined; - } - | BufferEncoding - | null, - ): Promise; - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__( - path: PathLike, - options: - | "buffer" - | { - encoding: "buffer"; - withFileTypes?: false | undefined; - recursive?: boolean | undefined; - }, - ): Promise; - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__( - path: PathLike, - options?: - | (ObjectEncodingOptions & { - withFileTypes?: false | undefined; - recursive?: boolean | undefined; - }) - | BufferEncoding - | null, - ): Promise; - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options If called with `withFileTypes: true` the result data will be an array of Dirent - */ - function __promisify__( - path: PathLike, - options: ObjectEncodingOptions & { - withFileTypes: true; - recursive?: boolean | undefined; - }, - ): Promise; - } - /** - * Reads the contents of the directory. - * - * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. - * - * The optional `options` argument can be a string specifying an encoding, or an - * object with an `encoding` property specifying the character encoding to use for - * the filenames returned. If the `encoding` is set to `'buffer'`, - * the filenames returned will be passed as `Buffer` objects. - * - * If `options.withFileTypes` is set to `true`, the result will contain `fs.Dirent` objects. - * @since v0.1.21 - */ - export function readdirSync( - path: PathLike, - options?: - | { - encoding: BufferEncoding | null; - withFileTypes?: false | undefined; - recursive?: boolean | undefined; - } - | BufferEncoding - | null, - ): string[]; - /** - * Synchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readdirSync( - path: PathLike, - options: - | { - encoding: "buffer"; - withFileTypes?: false | undefined; - recursive?: boolean | undefined; - } - | "buffer", - ): Buffer[]; - /** - * Synchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readdirSync( - path: PathLike, - options?: - | (ObjectEncodingOptions & { - withFileTypes?: false | undefined; - recursive?: boolean | undefined; - }) - | BufferEncoding - | null, - ): string[] | Buffer[]; - /** - * Synchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. - */ - export function readdirSync( - path: PathLike, - options: ObjectEncodingOptions & { - withFileTypes: true; - recursive?: boolean | undefined; - }, - ): Dirent[]; - /** - * Closes the file descriptor. No arguments other than a possible exception are - * given to the completion callback. - * - * Calling `fs.close()` on any file descriptor (`fd`) that is currently in use - * through any other `fs` operation may lead to undefined behavior. - * - * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. - * @since v0.0.2 - */ - export function close(fd: number, callback?: NoParamCallback): void; - export namespace close { - /** - * Asynchronous close(2) - close a file descriptor. - * @param fd A file descriptor. - */ - function __promisify__(fd: number): Promise; - } - /** - * Closes the file descriptor. Returns `undefined`. - * - * Calling `fs.closeSync()` on any file descriptor (`fd`) that is currently in use - * through any other `fs` operation may lead to undefined behavior. - * - * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. - * @since v0.1.21 - */ - export function closeSync(fd: number): void; - /** - * Asynchronous file open. See the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more details. - * - * `mode` sets the file mode (permission and sticky bits), but only if the file was - * created. On Windows, only the write permission can be manipulated; see {@link chmod}. - * - * The callback gets two arguments `(err, fd)`. - * - * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented - * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains - * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). - * - * Functions based on `fs.open()` exhibit this behavior as well:`fs.writeFile()`, `fs.readFile()`, etc. - * @since v0.0.2 - * @param [flags='r'] See `support of file system `flags``. - * @param [mode=0o666] - */ - export function open( - path: PathLike, - flags: OpenMode | undefined, - mode: Mode | undefined | null, - callback: (err: NodeJS.ErrnoException | null, fd: number) => void, - ): void; - /** - * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param [flags='r'] See `support of file system `flags``. - */ - export function open( - path: PathLike, - flags: OpenMode | undefined, - callback: (err: NodeJS.ErrnoException | null, fd: number) => void, - ): void; - /** - * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function open(path: PathLike, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; - export namespace open { - /** - * Asynchronous open(2) - open and possibly create a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. - */ - function __promisify__(path: PathLike, flags: OpenMode, mode?: Mode | null): Promise; - } - /** - * Returns an integer representing the file descriptor. - * - * For detailed information, see the documentation of the asynchronous version of - * this API: {@link open}. - * @since v0.1.21 - * @param [flags='r'] - * @param [mode=0o666] - */ - export function openSync(path: PathLike, flags: OpenMode, mode?: Mode | null): number; - /** - * Change the file system timestamps of the object referenced by `path`. - * - * The `atime` and `mtime` arguments follow these rules: - * - * * Values can be either numbers representing Unix epoch time in seconds,`Date`s, or a numeric string like `'123456789.0'`. - * * If the value can not be converted to a number, or is `NaN`, `Infinity`, or`-Infinity`, an `Error` will be thrown. - * @since v0.4.2 - */ - export function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; - export namespace utimes { - /** - * Asynchronously change file timestamps of the file referenced by the supplied path. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; - } - /** - * Returns `undefined`. - * - * For detailed information, see the documentation of the asynchronous version of - * this API: {@link utimes}. - * @since v0.4.2 - */ - export function utimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; - /** - * Change the file system timestamps of the object referenced by the supplied file - * descriptor. See {@link utimes}. - * @since v0.4.2 - */ - export function futimes(fd: number, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; - export namespace futimes { - /** - * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - function __promisify__(fd: number, atime: TimeLike, mtime: TimeLike): Promise; - } - /** - * Synchronous version of {@link futimes}. Returns `undefined`. - * @since v0.4.2 - */ - export function futimesSync(fd: number, atime: TimeLike, mtime: TimeLike): void; - /** - * Request that all data for the open file descriptor is flushed to the storage - * device. The specific implementation is operating system and device specific. - * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. No arguments other - * than a possible exception are given to the completion callback. - * @since v0.1.96 - */ - export function fsync(fd: number, callback: NoParamCallback): void; - export namespace fsync { - /** - * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. - * @param fd A file descriptor. - */ - function __promisify__(fd: number): Promise; - } - /** - * Request that all data for the open file descriptor is flushed to the storage - * device. The specific implementation is operating system and device specific. - * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. Returns `undefined`. - * @since v0.1.96 - */ - export function fsyncSync(fd: number): void; - /** - * Write `buffer` to the file specified by `fd`. - * - * `offset` determines the part of the buffer to be written, and `length` is - * an integer specifying the number of bytes to write. - * - * `position` refers to the offset from the beginning of the file where this data - * should be written. If `typeof position !== 'number'`, the data will be written - * at the current position. See [`pwrite(2)`](http://man7.org/linux/man-pages/man2/pwrite.2.html). - * - * The callback will be given three arguments `(err, bytesWritten, buffer)` where`bytesWritten` specifies how many _bytes_ were written from `buffer`. - * - * If this method is invoked as its `util.promisify()` ed version, it returns - * a promise for an `Object` with `bytesWritten` and `buffer` properties. - * - * It is unsafe to use `fs.write()` multiple times on the same file without waiting - * for the callback. For this scenario, {@link createWriteStream} is - * recommended. - * - * On Linux, positional writes don't work when the file is opened in append mode. - * The kernel ignores the position argument and always appends the data to - * the end of the file. - * @since v0.0.2 - * @param [offset=0] - * @param [length=buffer.byteLength - offset] - * @param [position='null'] - */ - export function write( - fd: number, - buffer: TBuffer, - offset: number | undefined | null, - length: number | undefined | null, - position: number | undefined | null, - callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, - ): void; - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. - */ - export function write( - fd: number, - buffer: TBuffer, - offset: number | undefined | null, - length: number | undefined | null, - callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, - ): void; - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - */ - export function write( - fd: number, - buffer: TBuffer, - offset: number | undefined | null, - callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, - ): void; - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - */ - export function write( - fd: number, - buffer: TBuffer, - callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, - ): void; - /** - * Asynchronously writes `string` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param string A string to write. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - * @param encoding The expected string encoding. - */ - export function write( - fd: number, - string: string, - position: number | undefined | null, - encoding: BufferEncoding | undefined | null, - callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, - ): void; - /** - * Asynchronously writes `string` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param string A string to write. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - */ - export function write( - fd: number, - string: string, - position: number | undefined | null, - callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, - ): void; - /** - * Asynchronously writes `string` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param string A string to write. - */ - export function write( - fd: number, - string: string, - callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, - ): void; - export namespace write { - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - */ - function __promisify__( - fd: number, - buffer?: TBuffer, - offset?: number, - length?: number, - position?: number | null, - ): Promise<{ - bytesWritten: number; - buffer: TBuffer; - }>; - /** - * Asynchronously writes `string` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param string A string to write. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - * @param encoding The expected string encoding. - */ - function __promisify__( - fd: number, - string: string, - position?: number | null, - encoding?: BufferEncoding | null, - ): Promise<{ - bytesWritten: number; - buffer: string; - }>; - } - /** - * For detailed information, see the documentation of the asynchronous version of - * this API: {@link write}. - * @since v0.1.21 - * @param [offset=0] - * @param [length=buffer.byteLength - offset] - * @param [position='null'] - * @return The number of bytes written. - */ - export function writeSync( - fd: number, - buffer: NodeJS.ArrayBufferView, - offset?: number | null, - length?: number | null, - position?: number | null, - ): number; - /** - * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. - * @param fd A file descriptor. - * @param string A string to write. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - * @param encoding The expected string encoding. - */ - export function writeSync( - fd: number, - string: string, - position?: number | null, - encoding?: BufferEncoding | null, - ): number; - export type ReadPosition = number | bigint; - export interface ReadSyncOptions { - /** - * @default 0 - */ - offset?: number | undefined; - /** - * @default `length of buffer` - */ - length?: number | undefined; - /** - * @default null - */ - position?: ReadPosition | null | undefined; - } - export interface ReadAsyncOptions extends ReadSyncOptions { - buffer?: TBuffer; - } - /** - * Read data from the file specified by `fd`. - * - * The callback is given the three arguments, `(err, bytesRead, buffer)`. - * - * If the file is not modified concurrently, the end-of-file is reached when the - * number of bytes read is zero. - * - * If this method is invoked as its `util.promisify()` ed version, it returns - * a promise for an `Object` with `bytesRead` and `buffer` properties. - * @since v0.0.2 - * @param buffer The buffer that the data will be written to. - * @param offset The position in `buffer` to write the data to. - * @param length The number of bytes to read. - * @param position Specifies where to begin reading from in the file. If `position` is `null` or `-1 `, data will be read from the current file position, and the file position will be updated. If - * `position` is an integer, the file position will be unchanged. - */ - export function read( - fd: number, - buffer: TBuffer, - offset: number, - length: number, - position: ReadPosition | null, - callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, - ): void; - /** - * Similar to the above `fs.read` function, this version takes an optional `options` object. - * If not otherwise specified in an `options` object, - * `buffer` defaults to `Buffer.alloc(16384)`, - * `offset` defaults to `0`, - * `length` defaults to `buffer.byteLength`, `- offset` as of Node 17.6.0 - * `position` defaults to `null` - * @since v12.17.0, 13.11.0 - */ - export function read( - fd: number, - options: ReadAsyncOptions, - callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, - ): void; - export function read( - fd: number, - callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: NodeJS.ArrayBufferView) => void, - ): void; - export namespace read { - /** - * @param fd A file descriptor. - * @param buffer The buffer that the data will be written to. - * @param offset The offset in the buffer at which to start writing. - * @param length The number of bytes to read. - * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. - */ - function __promisify__( - fd: number, - buffer: TBuffer, - offset: number, - length: number, - position: number | null, - ): Promise<{ - bytesRead: number; - buffer: TBuffer; - }>; - function __promisify__( - fd: number, - options: ReadAsyncOptions, - ): Promise<{ - bytesRead: number; - buffer: TBuffer; - }>; - function __promisify__(fd: number): Promise<{ - bytesRead: number; - buffer: NodeJS.ArrayBufferView; - }>; - } - /** - * Returns the number of `bytesRead`. - * - * For detailed information, see the documentation of the asynchronous version of - * this API: {@link read}. - * @since v0.1.21 - * @param [position='null'] - */ - export function readSync( - fd: number, - buffer: NodeJS.ArrayBufferView, - offset: number, - length: number, - position: ReadPosition | null, - ): number; - /** - * Similar to the above `fs.readSync` function, this version takes an optional `options` object. - * If no `options` object is specified, it will default with the above values. - */ - export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, opts?: ReadSyncOptions): number; - /** - * Asynchronously reads the entire contents of a file. - * - * ```js - * import { readFile } from 'node:fs'; - * - * readFile('/etc/passwd', (err, data) => { - * if (err) throw err; - * console.log(data); - * }); - * ``` - * - * The callback is passed two arguments `(err, data)`, where `data` is the - * contents of the file. - * - * If no encoding is specified, then the raw buffer is returned. - * - * If `options` is a string, then it specifies the encoding: - * - * ```js - * import { readFile } from 'node:fs'; - * - * readFile('/etc/passwd', 'utf8', callback); - * ``` - * - * When the path is a directory, the behavior of `fs.readFile()` and {@link readFileSync} is platform-specific. On macOS, Linux, and Windows, an - * error will be returned. On FreeBSD, a representation of the directory's contents - * will be returned. - * - * ```js - * import { readFile } from 'node:fs'; - * - * // macOS, Linux, and Windows - * readFile('', (err, data) => { - * // => [Error: EISDIR: illegal operation on a directory, read ] - * }); - * - * // FreeBSD - * readFile('', (err, data) => { - * // => null, - * }); - * ``` - * - * It is possible to abort an ongoing request using an `AbortSignal`. If a - * request is aborted the callback is called with an `AbortError`: - * - * ```js - * import { readFile } from 'node:fs'; - * - * const controller = new AbortController(); - * const signal = controller.signal; - * readFile(fileInfo[0].name, { signal }, (err, buf) => { - * // ... - * }); - * // When you want to abort the request - * controller.abort(); - * ``` - * - * The `fs.readFile()` function buffers the entire file. To minimize memory costs, - * when possible prefer streaming via `fs.createReadStream()`. - * - * Aborting an ongoing request does not abort individual operating - * system requests but rather the internal buffering `fs.readFile` performs. - * @since v0.1.29 - * @param path filename or file descriptor - */ - export function readFile( - path: PathOrFileDescriptor, - options: - | ({ - encoding?: null | undefined; - flag?: string | undefined; - } & Abortable) - | undefined - | null, - callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void, - ): void; - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - export function readFile( - path: PathOrFileDescriptor, - options: - | ({ - encoding: BufferEncoding; - flag?: string | undefined; - } & Abortable) - | BufferEncoding, - callback: (err: NodeJS.ErrnoException | null, data: string) => void, - ): void; - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - export function readFile( - path: PathOrFileDescriptor, - options: - | (ObjectEncodingOptions & { - flag?: string | undefined; - } & Abortable) - | BufferEncoding - | undefined - | null, - callback: (err: NodeJS.ErrnoException | null, data: string | Buffer) => void, - ): void; - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - */ - export function readFile( - path: PathOrFileDescriptor, - callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void, - ): void; - export namespace readFile { - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function __promisify__( - path: PathOrFileDescriptor, - options?: { - encoding?: null | undefined; - flag?: string | undefined; - } | null, - ): Promise; - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function __promisify__( - path: PathOrFileDescriptor, - options: - | { - encoding: BufferEncoding; - flag?: string | undefined; - } - | BufferEncoding, - ): Promise; - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function __promisify__( - path: PathOrFileDescriptor, - options?: - | (ObjectEncodingOptions & { - flag?: string | undefined; - }) - | BufferEncoding - | null, - ): Promise; - } - /** - * Returns the contents of the `path`. - * - * For detailed information, see the documentation of the asynchronous version of - * this API: {@link readFile}. - * - * If the `encoding` option is specified then this function returns a - * string. Otherwise it returns a buffer. - * - * Similar to {@link readFile}, when the path is a directory, the behavior of`fs.readFileSync()` is platform-specific. - * - * ```js - * import { readFileSync } from 'node:fs'; - * - * // macOS, Linux, and Windows - * readFileSync(''); - * // => [Error: EISDIR: illegal operation on a directory, read ] - * - * // FreeBSD - * readFileSync(''); // => - * ``` - * @since v0.1.8 - * @param path filename or file descriptor - */ - export function readFileSync( - path: PathOrFileDescriptor, - options?: { - encoding?: null | undefined; - flag?: string | undefined; - } | null, - ): Buffer; - /** - * Synchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - export function readFileSync( - path: PathOrFileDescriptor, - options: - | { - encoding: BufferEncoding; - flag?: string | undefined; - } - | BufferEncoding, - ): string; - /** - * Synchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - export function readFileSync( - path: PathOrFileDescriptor, - options?: - | (ObjectEncodingOptions & { - flag?: string | undefined; - }) - | BufferEncoding - | null, - ): string | Buffer; - export type WriteFileOptions = - | ( - & ObjectEncodingOptions - & Abortable - & { - mode?: Mode | undefined; - flag?: string | undefined; - flush?: boolean | undefined; - } - ) - | BufferEncoding - | null; - /** - * When `file` is a filename, asynchronously writes data to the file, replacing the - * file if it already exists. `data` can be a string or a buffer. - * - * When `file` is a file descriptor, the behavior is similar to calling`fs.write()` directly (which is recommended). See the notes below on using - * a file descriptor. - * - * The `encoding` option is ignored if `data` is a buffer. - * - * The `mode` option only affects the newly created file. See {@link open} for more details. - * - * ```js - * import { writeFile } from 'node:fs'; - * import { Buffer } from 'node:buffer'; - * - * const data = new Uint8Array(Buffer.from('Hello Node.js')); - * writeFile('message.txt', data, (err) => { - * if (err) throw err; - * console.log('The file has been saved!'); - * }); - * ``` - * - * If `options` is a string, then it specifies the encoding: - * - * ```js - * import { writeFile } from 'node:fs'; - * - * writeFile('message.txt', 'Hello Node.js', 'utf8', callback); - * ``` - * - * It is unsafe to use `fs.writeFile()` multiple times on the same file without - * waiting for the callback. For this scenario, {@link createWriteStream} is - * recommended. - * - * Similarly to `fs.readFile` \- `fs.writeFile` is a convenience method that - * performs multiple `write` calls internally to write the buffer passed to it. - * For performance sensitive code consider using {@link createWriteStream}. - * - * It is possible to use an `AbortSignal` to cancel an `fs.writeFile()`. - * Cancelation is "best effort", and some amount of data is likely still - * to be written. - * - * ```js - * import { writeFile } from 'node:fs'; - * import { Buffer } from 'node:buffer'; - * - * const controller = new AbortController(); - * const { signal } = controller; - * const data = new Uint8Array(Buffer.from('Hello Node.js')); - * writeFile('message.txt', data, { signal }, (err) => { - * // When a request is aborted - the callback is called with an AbortError - * }); - * // When the request should be aborted - * controller.abort(); - * ``` - * - * Aborting an ongoing request does not abort individual operating - * system requests but rather the internal buffering `fs.writeFile` performs. - * @since v0.1.29 - * @param file filename or file descriptor - */ - export function writeFile( - file: PathOrFileDescriptor, - data: string | NodeJS.ArrayBufferView, - options: WriteFileOptions, - callback: NoParamCallback, - ): void; - /** - * Asynchronously writes data to a file, replacing the file if it already exists. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - */ - export function writeFile( - path: PathOrFileDescriptor, - data: string | NodeJS.ArrayBufferView, - callback: NoParamCallback, - ): void; - export namespace writeFile { - /** - * Asynchronously writes data to a file, replacing the file if it already exists. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'w'` is used. - */ - function __promisify__( - path: PathOrFileDescriptor, - data: string | NodeJS.ArrayBufferView, - options?: WriteFileOptions, - ): Promise; - } - /** - * Returns `undefined`. - * - * The `mode` option only affects the newly created file. See {@link open} for more details. - * - * For detailed information, see the documentation of the asynchronous version of - * this API: {@link writeFile}. - * @since v0.1.29 - * @param file filename or file descriptor - */ - export function writeFileSync( - file: PathOrFileDescriptor, - data: string | NodeJS.ArrayBufferView, - options?: WriteFileOptions, - ): void; - /** - * Asynchronously append data to a file, creating the file if it does not yet - * exist. `data` can be a string or a `Buffer`. - * - * The `mode` option only affects the newly created file. See {@link open} for more details. - * - * ```js - * import { appendFile } from 'node:fs'; - * - * appendFile('message.txt', 'data to append', (err) => { - * if (err) throw err; - * console.log('The "data to append" was appended to file!'); - * }); - * ``` - * - * If `options` is a string, then it specifies the encoding: - * - * ```js - * import { appendFile } from 'node:fs'; - * - * appendFile('message.txt', 'data to append', 'utf8', callback); - * ``` - * - * The `path` may be specified as a numeric file descriptor that has been opened - * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will - * not be closed automatically. - * - * ```js - * import { open, close, appendFile } from 'node:fs'; - * - * function closeFd(fd) { - * close(fd, (err) => { - * if (err) throw err; - * }); - * } - * - * open('message.txt', 'a', (err, fd) => { - * if (err) throw err; - * - * try { - * appendFile(fd, 'data to append', 'utf8', (err) => { - * closeFd(fd); - * if (err) throw err; - * }); - * } catch (err) { - * closeFd(fd); - * throw err; - * } - * }); - * ``` - * @since v0.6.7 - * @param path filename or file descriptor - */ - export function appendFile( - path: PathOrFileDescriptor, - data: string | Uint8Array, - options: WriteFileOptions, - callback: NoParamCallback, - ): void; - /** - * Asynchronously append data to a file, creating the file if it does not exist. - * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - */ - export function appendFile(file: PathOrFileDescriptor, data: string | Uint8Array, callback: NoParamCallback): void; - export namespace appendFile { - /** - * Asynchronously append data to a file, creating the file if it does not exist. - * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'a'` is used. - */ - function __promisify__( - file: PathOrFileDescriptor, - data: string | Uint8Array, - options?: WriteFileOptions, - ): Promise; - } - /** - * Synchronously append data to a file, creating the file if it does not yet - * exist. `data` can be a string or a `Buffer`. - * - * The `mode` option only affects the newly created file. See {@link open} for more details. - * - * ```js - * import { appendFileSync } from 'node:fs'; - * - * try { - * appendFileSync('message.txt', 'data to append'); - * console.log('The "data to append" was appended to file!'); - * } catch (err) { - * // Handle the error - * } - * ``` - * - * If `options` is a string, then it specifies the encoding: - * - * ```js - * import { appendFileSync } from 'node:fs'; - * - * appendFileSync('message.txt', 'data to append', 'utf8'); - * ``` - * - * The `path` may be specified as a numeric file descriptor that has been opened - * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will - * not be closed automatically. - * - * ```js - * import { openSync, closeSync, appendFileSync } from 'node:fs'; - * - * let fd; - * - * try { - * fd = openSync('message.txt', 'a'); - * appendFileSync(fd, 'data to append', 'utf8'); - * } catch (err) { - * // Handle the error - * } finally { - * if (fd !== undefined) - * closeSync(fd); - * } - * ``` - * @since v0.6.7 - * @param path filename or file descriptor - */ - export function appendFileSync( - path: PathOrFileDescriptor, - data: string | Uint8Array, - options?: WriteFileOptions, - ): void; - /** - * Watch for changes on `filename`. The callback `listener` will be called each - * time the file is accessed. - * - * The `options` argument may be omitted. If provided, it should be an object. The`options` object may contain a boolean named `persistent` that indicates - * whether the process should continue to run as long as files are being watched. - * The `options` object may specify an `interval` property indicating how often the - * target should be polled in milliseconds. - * - * The `listener` gets two arguments the current stat object and the previous - * stat object: - * - * ```js - * import { watchFile } from 'fs'; - * - * watchFile('message.text', (curr, prev) => { - * console.log(`the current mtime is: ${curr.mtime}`); - * console.log(`the previous mtime was: ${prev.mtime}`); - * }); - * ``` - * - * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, - * the numeric values in these objects are specified as `BigInt`s. - * - * To be notified when the file was modified, not just accessed, it is necessary - * to compare `curr.mtimeMs` and `prev.mtimeMs`. - * - * When an `fs.watchFile` operation results in an `ENOENT` error, it - * will invoke the listener once, with all the fields zeroed (or, for dates, the - * Unix Epoch). If the file is created later on, the listener will be called - * again, with the latest stat objects. This is a change in functionality since - * v0.10. - * - * Using {@link watch} is more efficient than `fs.watchFile` and`fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and`fs.unwatchFile` when possible. - * - * When a file being watched by `fs.watchFile()` disappears and reappears, - * then the contents of `previous` in the second callback event (the file's - * reappearance) will be the same as the contents of `previous` in the first - * callback event (its disappearance). - * - * This happens when: - * - * * the file is deleted, followed by a restore - * * the file is renamed and then renamed a second time back to its original name - * @since v0.1.31 - */ - export interface WatchFileOptions { - bigint?: boolean | undefined; - persistent?: boolean | undefined; - interval?: number | undefined; - } - /** - * Watch for changes on `filename`. The callback `listener` will be called each - * time the file is accessed. - * - * The `options` argument may be omitted. If provided, it should be an object. The`options` object may contain a boolean named `persistent` that indicates - * whether the process should continue to run as long as files are being watched. - * The `options` object may specify an `interval` property indicating how often the - * target should be polled in milliseconds. - * - * The `listener` gets two arguments the current stat object and the previous - * stat object: - * - * ```js - * import { watchFile } from 'node:fs'; - * - * watchFile('message.text', (curr, prev) => { - * console.log(`the current mtime is: ${curr.mtime}`); - * console.log(`the previous mtime was: ${prev.mtime}`); - * }); - * ``` - * - * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, - * the numeric values in these objects are specified as `BigInt`s. - * - * To be notified when the file was modified, not just accessed, it is necessary - * to compare `curr.mtimeMs` and `prev.mtimeMs`. - * - * When an `fs.watchFile` operation results in an `ENOENT` error, it - * will invoke the listener once, with all the fields zeroed (or, for dates, the - * Unix Epoch). If the file is created later on, the listener will be called - * again, with the latest stat objects. This is a change in functionality since - * v0.10. - * - * Using {@link watch} is more efficient than `fs.watchFile` and`fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and`fs.unwatchFile` when possible. - * - * When a file being watched by `fs.watchFile()` disappears and reappears, - * then the contents of `previous` in the second callback event (the file's - * reappearance) will be the same as the contents of `previous` in the first - * callback event (its disappearance). - * - * This happens when: - * - * * the file is deleted, followed by a restore - * * the file is renamed and then renamed a second time back to its original name - * @since v0.1.31 - */ - export function watchFile( - filename: PathLike, - options: - | (WatchFileOptions & { - bigint?: false | undefined; - }) - | undefined, - listener: StatsListener, - ): StatWatcher; - export function watchFile( - filename: PathLike, - options: - | (WatchFileOptions & { - bigint: true; - }) - | undefined, - listener: BigIntStatsListener, - ): StatWatcher; - /** - * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - */ - export function watchFile(filename: PathLike, listener: StatsListener): StatWatcher; - /** - * Stop watching for changes on `filename`. If `listener` is specified, only that - * particular listener is removed. Otherwise, _all_ listeners are removed, - * effectively stopping watching of `filename`. - * - * Calling `fs.unwatchFile()` with a filename that is not being watched is a - * no-op, not an error. - * - * Using {@link watch} is more efficient than `fs.watchFile()` and`fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()`and `fs.unwatchFile()` when possible. - * @since v0.1.31 - * @param listener Optional, a listener previously attached using `fs.watchFile()` - */ - export function unwatchFile(filename: PathLike, listener?: StatsListener): void; - export function unwatchFile(filename: PathLike, listener?: BigIntStatsListener): void; - export interface WatchOptions extends Abortable { - encoding?: BufferEncoding | "buffer" | undefined; - persistent?: boolean | undefined; - recursive?: boolean | undefined; - } - export type WatchEventType = "rename" | "change"; - export type WatchListener = (event: WatchEventType, filename: T | null) => void; - export type StatsListener = (curr: Stats, prev: Stats) => void; - export type BigIntStatsListener = (curr: BigIntStats, prev: BigIntStats) => void; - /** - * Watch for changes on `filename`, where `filename` is either a file or a - * directory. - * - * The second argument is optional. If `options` is provided as a string, it - * specifies the `encoding`. Otherwise `options` should be passed as an object. - * - * The listener callback gets two arguments `(eventType, filename)`. `eventType`is either `'rename'` or `'change'`, and `filename` is the name of the file - * which triggered the event. - * - * On most platforms, `'rename'` is emitted whenever a filename appears or - * disappears in the directory. - * - * The listener callback is attached to the `'change'` event fired by `fs.FSWatcher`, but it is not the same thing as the `'change'` value of`eventType`. - * - * If a `signal` is passed, aborting the corresponding AbortController will close - * the returned `fs.FSWatcher`. - * @since v0.5.10 - * @param listener - */ - export function watch( - filename: PathLike, - options: - | (WatchOptions & { - encoding: "buffer"; - }) - | "buffer", - listener?: WatchListener, - ): FSWatcher; - /** - * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `persistent` is not supplied, the default of `true` is used. - * If `recursive` is not supplied, the default of `false` is used. - */ - export function watch( - filename: PathLike, - options?: WatchOptions | BufferEncoding | null, - listener?: WatchListener, - ): FSWatcher; - /** - * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `persistent` is not supplied, the default of `true` is used. - * If `recursive` is not supplied, the default of `false` is used. - */ - export function watch( - filename: PathLike, - options: WatchOptions | string, - listener?: WatchListener, - ): FSWatcher; - /** - * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - */ - export function watch(filename: PathLike, listener?: WatchListener): FSWatcher; - /** - * Test whether or not the given path exists by checking with the file system. - * Then call the `callback` argument with either true or false: - * - * ```js - * import { exists } from 'node:fs'; - * - * exists('/etc/passwd', (e) => { - * console.log(e ? 'it exists' : 'no passwd!'); - * }); - * ``` - * - * **The parameters for this callback are not consistent with other Node.js** - * **callbacks.** Normally, the first parameter to a Node.js callback is an `err`parameter, optionally followed by other parameters. The `fs.exists()` callback - * has only one boolean parameter. This is one reason `fs.access()` is recommended - * instead of `fs.exists()`. - * - * Using `fs.exists()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. Doing - * so introduces a race condition, since other processes may change the file's - * state between the two calls. Instead, user code should open/read/write the - * file directly and handle the error raised if the file does not exist. - * - * **write (NOT RECOMMENDED)** - * - * ```js - * import { exists, open, close } from 'node:fs'; - * - * exists('myfile', (e) => { - * if (e) { - * console.error('myfile already exists'); - * } else { - * open('myfile', 'wx', (err, fd) => { - * if (err) throw err; - * - * try { - * writeMyData(fd); - * } finally { - * close(fd, (err) => { - * if (err) throw err; - * }); - * } - * }); - * } - * }); - * ``` - * - * **write (RECOMMENDED)** - * - * ```js - * import { open, close } from 'node:fs'; - * open('myfile', 'wx', (err, fd) => { - * if (err) { - * if (err.code === 'EEXIST') { - * console.error('myfile already exists'); - * return; - * } - * - * throw err; - * } - * - * try { - * writeMyData(fd); - * } finally { - * close(fd, (err) => { - * if (err) throw err; - * }); - * } - * }); - * ``` - * - * **read (NOT RECOMMENDED)** - * - * ```js - * import { open, close, exists } from 'node:fs'; - * - * exists('myfile', (e) => { - * if (e) { - * open('myfile', 'r', (err, fd) => { - * if (err) throw err; - * - * try { - * readMyData(fd); - * } finally { - * close(fd, (err) => { - * if (err) throw err; - * }); - * } - * }); - * } else { - * console.error('myfile does not exist'); - * } - * }); - * ``` - * - * **read (RECOMMENDED)** - * - * ```js - * import { open, close } from 'node:fs'; - * - * open('myfile', 'r', (err, fd) => { - * if (err) { - * if (err.code === 'ENOENT') { - * console.error('myfile does not exist'); - * return; - * } - * - * throw err; - * } - * - * try { - * readMyData(fd); - * } finally { - * close(fd, (err) => { - * if (err) throw err; - * }); - * } - * }); - * ``` - * - * The "not recommended" examples above check for existence and then use the - * file; the "recommended" examples are better because they use the file directly - * and handle the error, if any. - * - * In general, check for the existence of a file only if the file won't be - * used directly, for example when its existence is a signal from another - * process. - * @since v0.0.2 - * @deprecated Since v1.0.0 - Use {@link stat} or {@link access} instead. - */ - export function exists(path: PathLike, callback: (exists: boolean) => void): void; - /** @deprecated */ - export namespace exists { - /** - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function __promisify__(path: PathLike): Promise; - } - /** - * Returns `true` if the path exists, `false` otherwise. - * - * For detailed information, see the documentation of the asynchronous version of - * this API: {@link exists}. - * - * `fs.exists()` is deprecated, but `fs.existsSync()` is not. The `callback`parameter to `fs.exists()` accepts parameters that are inconsistent with other - * Node.js callbacks. `fs.existsSync()` does not use a callback. - * - * ```js - * import { existsSync } from 'node:fs'; - * - * if (existsSync('/etc/passwd')) - * console.log('The path exists.'); - * ``` - * @since v0.1.21 - */ - export function existsSync(path: PathLike): boolean; - export namespace constants { - // File Access Constants - /** Constant for fs.access(). File is visible to the calling process. */ - const F_OK: number; - /** Constant for fs.access(). File can be read by the calling process. */ - const R_OK: number; - /** Constant for fs.access(). File can be written by the calling process. */ - const W_OK: number; - /** Constant for fs.access(). File can be executed by the calling process. */ - const X_OK: number; - // File Copy Constants - /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ - const COPYFILE_EXCL: number; - /** - * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. - * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. - */ - const COPYFILE_FICLONE: number; - /** - * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. - * If the underlying platform does not support copy-on-write, then the operation will fail with an error. - */ - const COPYFILE_FICLONE_FORCE: number; - // File Open Constants - /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ - const O_RDONLY: number; - /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ - const O_WRONLY: number; - /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ - const O_RDWR: number; - /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ - const O_CREAT: number; - /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ - const O_EXCL: number; - /** - * Constant for fs.open(). Flag indicating that if path identifies a terminal device, - * opening the path shall not cause that terminal to become the controlling terminal for the process - * (if the process does not already have one). - */ - const O_NOCTTY: number; - /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ - const O_TRUNC: number; - /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ - const O_APPEND: number; - /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ - const O_DIRECTORY: number; - /** - * constant for fs.open(). - * Flag indicating reading accesses to the file system will no longer result in - * an update to the atime information associated with the file. - * This flag is available on Linux operating systems only. - */ - const O_NOATIME: number; - /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ - const O_NOFOLLOW: number; - /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ - const O_SYNC: number; - /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ - const O_DSYNC: number; - /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ - const O_SYMLINK: number; - /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ - const O_DIRECT: number; - /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ - const O_NONBLOCK: number; - // File Type Constants - /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ - const S_IFMT: number; - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ - const S_IFREG: number; - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ - const S_IFDIR: number; - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ - const S_IFCHR: number; - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ - const S_IFBLK: number; - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ - const S_IFIFO: number; - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ - const S_IFLNK: number; - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ - const S_IFSOCK: number; - // File Mode Constants - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ - const S_IRWXU: number; - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ - const S_IRUSR: number; - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ - const S_IWUSR: number; - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ - const S_IXUSR: number; - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ - const S_IRWXG: number; - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ - const S_IRGRP: number; - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ - const S_IWGRP: number; - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ - const S_IXGRP: number; - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ - const S_IRWXO: number; - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ - const S_IROTH: number; - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ - const S_IWOTH: number; - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ - const S_IXOTH: number; - /** - * When set, a memory file mapping is used to access the file. This flag - * is available on Windows operating systems only. On other operating systems, - * this flag is ignored. - */ - const UV_FS_O_FILEMAP: number; - } - /** - * Tests a user's permissions for the file or directory specified by `path`. - * The `mode` argument is an optional integer that specifies the accessibility - * checks to be performed. `mode` should be either the value `fs.constants.F_OK`or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`,`fs.constants.W_OK`, and `fs.constants.X_OK` - * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for - * possible values of `mode`. - * - * The final argument, `callback`, is a callback function that is invoked with - * a possible error argument. If any of the accessibility checks fail, the error - * argument will be an `Error` object. The following examples check if`package.json` exists, and if it is readable or writable. - * - * ```js - * import { access, constants } from 'node:fs'; - * - * const file = 'package.json'; - * - * // Check if the file exists in the current directory. - * access(file, constants.F_OK, (err) => { - * console.log(`${file} ${err ? 'does not exist' : 'exists'}`); - * }); - * - * // Check if the file is readable. - * access(file, constants.R_OK, (err) => { - * console.log(`${file} ${err ? 'is not readable' : 'is readable'}`); - * }); - * - * // Check if the file is writable. - * access(file, constants.W_OK, (err) => { - * console.log(`${file} ${err ? 'is not writable' : 'is writable'}`); - * }); - * - * // Check if the file is readable and writable. - * access(file, constants.R_OK | constants.W_OK, (err) => { - * console.log(`${file} ${err ? 'is not' : 'is'} readable and writable`); - * }); - * ``` - * - * Do not use `fs.access()` to check for the accessibility of a file before calling`fs.open()`, `fs.readFile()`, or `fs.writeFile()`. Doing - * so introduces a race condition, since other processes may change the file's - * state between the two calls. Instead, user code should open/read/write the - * file directly and handle the error raised if the file is not accessible. - * - * **write (NOT RECOMMENDED)** - * - * ```js - * import { access, open, close } from 'node:fs'; - * - * access('myfile', (err) => { - * if (!err) { - * console.error('myfile already exists'); - * return; - * } - * - * open('myfile', 'wx', (err, fd) => { - * if (err) throw err; - * - * try { - * writeMyData(fd); - * } finally { - * close(fd, (err) => { - * if (err) throw err; - * }); - * } - * }); - * }); - * ``` - * - * **write (RECOMMENDED)** - * - * ```js - * import { open, close } from 'node:fs'; - * - * open('myfile', 'wx', (err, fd) => { - * if (err) { - * if (err.code === 'EEXIST') { - * console.error('myfile already exists'); - * return; - * } - * - * throw err; - * } - * - * try { - * writeMyData(fd); - * } finally { - * close(fd, (err) => { - * if (err) throw err; - * }); - * } - * }); - * ``` - * - * **read (NOT RECOMMENDED)** - * - * ```js - * import { access, open, close } from 'node:fs'; - * access('myfile', (err) => { - * if (err) { - * if (err.code === 'ENOENT') { - * console.error('myfile does not exist'); - * return; - * } - * - * throw err; - * } - * - * open('myfile', 'r', (err, fd) => { - * if (err) throw err; - * - * try { - * readMyData(fd); - * } finally { - * close(fd, (err) => { - * if (err) throw err; - * }); - * } - * }); - * }); - * ``` - * - * **read (RECOMMENDED)** - * - * ```js - * import { open, close } from 'node:fs'; - * - * open('myfile', 'r', (err, fd) => { - * if (err) { - * if (err.code === 'ENOENT') { - * console.error('myfile does not exist'); - * return; - * } - * - * throw err; - * } - * - * try { - * readMyData(fd); - * } finally { - * close(fd, (err) => { - * if (err) throw err; - * }); - * } - * }); - * ``` - * - * The "not recommended" examples above check for accessibility and then use the - * file; the "recommended" examples are better because they use the file directly - * and handle the error, if any. - * - * In general, check for the accessibility of a file only if the file will not be - * used directly, for example when its accessibility is a signal from another - * process. - * - * On Windows, access-control policies (ACLs) on a directory may limit access to - * a file or directory. The `fs.access()` function, however, does not check the - * ACL and therefore may report that a path is accessible even if the ACL restricts - * the user from reading or writing to it. - * @since v0.11.15 - * @param [mode=fs.constants.F_OK] - */ - export function access(path: PathLike, mode: number | undefined, callback: NoParamCallback): void; - /** - * Asynchronously tests a user's permissions for the file specified by path. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - */ - export function access(path: PathLike, callback: NoParamCallback): void; - export namespace access { - /** - * Asynchronously tests a user's permissions for the file specified by path. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function __promisify__(path: PathLike, mode?: number): Promise; - } - /** - * Synchronously tests a user's permissions for the file or directory specified - * by `path`. The `mode` argument is an optional integer that specifies the - * accessibility checks to be performed. `mode` should be either the value`fs.constants.F_OK` or a mask consisting of the bitwise OR of any of`fs.constants.R_OK`, `fs.constants.W_OK`, and - * `fs.constants.X_OK` (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for - * possible values of `mode`. - * - * If any of the accessibility checks fail, an `Error` will be thrown. Otherwise, - * the method will return `undefined`. - * - * ```js - * import { accessSync, constants } from 'node:fs'; - * - * try { - * accessSync('etc/passwd', constants.R_OK | constants.W_OK); - * console.log('can read/write'); - * } catch (err) { - * console.error('no access!'); - * } - * ``` - * @since v0.11.15 - * @param [mode=fs.constants.F_OK] - */ - export function accessSync(path: PathLike, mode?: number): void; - interface StreamOptions { - flags?: string | undefined; - encoding?: BufferEncoding | undefined; - fd?: number | promises.FileHandle | undefined; - mode?: number | undefined; - autoClose?: boolean | undefined; - emitClose?: boolean | undefined; - start?: number | undefined; - signal?: AbortSignal | null | undefined; - highWaterMark?: number | undefined; - } - interface FSImplementation { - open?: (...args: any[]) => any; - close?: (...args: any[]) => any; - } - interface CreateReadStreamFSImplementation extends FSImplementation { - read: (...args: any[]) => any; - } - interface CreateWriteStreamFSImplementation extends FSImplementation { - write: (...args: any[]) => any; - writev?: (...args: any[]) => any; - } - interface ReadStreamOptions extends StreamOptions { - fs?: CreateReadStreamFSImplementation | null | undefined; - end?: number | undefined; - } - interface WriteStreamOptions extends StreamOptions { - fs?: CreateWriteStreamFSImplementation | null | undefined; - flush?: boolean | undefined; - } - /** - * Unlike the 16 KiB default `highWaterMark` for a `stream.Readable`, the stream - * returned by this method has a default `highWaterMark` of 64 KiB. - * - * `options` can include `start` and `end` values to read a range of bytes from - * the file instead of the entire file. Both `start` and `end` are inclusive and - * start counting at 0, allowed values are in the - * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `fd` is specified and `start` is - * omitted or `undefined`, `fs.createReadStream()` reads sequentially from the - * current file position. The `encoding` can be any one of those accepted by `Buffer`. - * - * If `fd` is specified, `ReadStream` will ignore the `path` argument and will use - * the specified file descriptor. This means that no `'open'` event will be - * emitted. `fd` should be blocking; non-blocking `fd`s should be passed to `net.Socket`. - * - * If `fd` points to a character device that only supports blocking reads - * (such as keyboard or sound card), read operations do not finish until data is - * available. This can prevent the process from exiting and the stream from - * closing naturally. - * - * By default, the stream will emit a `'close'` event after it has been - * destroyed. Set the `emitClose` option to `false` to change this behavior. - * - * By providing the `fs` option, it is possible to override the corresponding `fs`implementations for `open`, `read`, and `close`. When providing the `fs` option, - * an override for `read` is required. If no `fd` is provided, an override for`open` is also required. If `autoClose` is `true`, an override for `close` is - * also required. - * - * ```js - * import { createReadStream } from 'node:fs'; - * - * // Create a stream from some character device. - * const stream = createReadStream('/dev/input/event0'); - * setTimeout(() => { - * stream.close(); // This may not close the stream. - * // Artificially marking end-of-stream, as if the underlying resource had - * // indicated end-of-file by itself, allows the stream to close. - * // This does not cancel pending read operations, and if there is such an - * // operation, the process may still not be able to exit successfully - * // until it finishes. - * stream.push(null); - * stream.read(0); - * }, 100); - * ``` - * - * If `autoClose` is false, then the file descriptor won't be closed, even if - * there's an error. It is the application's responsibility to close it and make - * sure there's no file descriptor leak. If `autoClose` is set to true (default - * behavior), on `'error'` or `'end'` the file descriptor will be closed - * automatically. - * - * `mode` sets the file mode (permission and sticky bits), but only if the - * file was created. - * - * An example to read the last 10 bytes of a file which is 100 bytes long: - * - * ```js - * import { createReadStream } from 'node:fs'; - * - * createReadStream('sample.txt', { start: 90, end: 99 }); - * ``` - * - * If `options` is a string, then it specifies the encoding. - * @since v0.1.31 - */ - export function createReadStream(path: PathLike, options?: BufferEncoding | ReadStreamOptions): ReadStream; - /** - * `options` may also include a `start` option to allow writing data at some - * position past the beginning of the file, allowed values are in the - * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than - * replacing it may require the `flags` option to be set to `r+` rather than the - * default `w`. The `encoding` can be any one of those accepted by `Buffer`. - * - * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'`the file descriptor will be closed automatically. If `autoClose` is false, - * then the file descriptor won't be closed, even if there's an error. - * It is the application's responsibility to close it and make sure there's no - * file descriptor leak. - * - * By default, the stream will emit a `'close'` event after it has been - * destroyed. Set the `emitClose` option to `false` to change this behavior. - * - * By providing the `fs` option it is possible to override the corresponding `fs`implementations for `open`, `write`, `writev`, and `close`. Overriding `write()`without `writev()` can reduce - * performance as some optimizations (`_writev()`) - * will be disabled. When providing the `fs` option, overrides for at least one of`write` and `writev` are required. If no `fd` option is supplied, an override - * for `open` is also required. If `autoClose` is `true`, an override for `close`is also required. - * - * Like `fs.ReadStream`, if `fd` is specified, `fs.WriteStream` will ignore the`path` argument and will use the specified file descriptor. This means that no`'open'` event will be - * emitted. `fd` should be blocking; non-blocking `fd`s - * should be passed to `net.Socket`. - * - * If `options` is a string, then it specifies the encoding. - * @since v0.1.31 - */ - export function createWriteStream(path: PathLike, options?: BufferEncoding | WriteStreamOptions): WriteStream; - /** - * Forces all currently queued I/O operations associated with the file to the - * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. No arguments other - * than a possible - * exception are given to the completion callback. - * @since v0.1.96 - */ - export function fdatasync(fd: number, callback: NoParamCallback): void; - export namespace fdatasync { - /** - * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. - * @param fd A file descriptor. - */ - function __promisify__(fd: number): Promise; - } - /** - * Forces all currently queued I/O operations associated with the file to the - * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. Returns `undefined`. - * @since v0.1.96 - */ - export function fdatasyncSync(fd: number): void; - /** - * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it - * already exists. No arguments other than a possible exception are given to the - * callback function. Node.js makes no guarantees about the atomicity of the copy - * operation. If an error occurs after the destination file has been opened for - * writing, Node.js will attempt to remove the destination. - * - * `mode` is an optional integer that specifies the behavior - * of the copy operation. It is possible to create a mask consisting of the bitwise - * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). - * - * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already - * exists. - * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a - * copy-on-write reflink. If the platform does not support copy-on-write, then a - * fallback copy mechanism is used. - * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to - * create a copy-on-write reflink. If the platform does not support - * copy-on-write, then the operation will fail. - * - * ```js - * import { copyFile, constants } from 'node:fs'; - * - * function callback(err) { - * if (err) throw err; - * console.log('source.txt was copied to destination.txt'); - * } - * - * // destination.txt will be created or overwritten by default. - * copyFile('source.txt', 'destination.txt', callback); - * - * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. - * copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback); - * ``` - * @since v8.5.0 - * @param src source filename to copy - * @param dest destination filename of the copy operation - * @param [mode=0] modifiers for copy operation. - */ - export function copyFile(src: PathLike, dest: PathLike, callback: NoParamCallback): void; - export function copyFile(src: PathLike, dest: PathLike, mode: number, callback: NoParamCallback): void; - export namespace copyFile { - function __promisify__(src: PathLike, dst: PathLike, mode?: number): Promise; - } - /** - * Synchronously copies `src` to `dest`. By default, `dest` is overwritten if it - * already exists. Returns `undefined`. Node.js makes no guarantees about the - * atomicity of the copy operation. If an error occurs after the destination file - * has been opened for writing, Node.js will attempt to remove the destination. - * - * `mode` is an optional integer that specifies the behavior - * of the copy operation. It is possible to create a mask consisting of the bitwise - * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). - * - * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already - * exists. - * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a - * copy-on-write reflink. If the platform does not support copy-on-write, then a - * fallback copy mechanism is used. - * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to - * create a copy-on-write reflink. If the platform does not support - * copy-on-write, then the operation will fail. - * - * ```js - * import { copyFileSync, constants } from 'node:fs'; - * - * // destination.txt will be created or overwritten by default. - * copyFileSync('source.txt', 'destination.txt'); - * console.log('source.txt was copied to destination.txt'); - * - * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. - * copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL); - * ``` - * @since v8.5.0 - * @param src source filename to copy - * @param dest destination filename of the copy operation - * @param [mode=0] modifiers for copy operation. - */ - export function copyFileSync(src: PathLike, dest: PathLike, mode?: number): void; - /** - * Write an array of `ArrayBufferView`s to the file specified by `fd` using`writev()`. - * - * `position` is the offset from the beginning of the file where this data - * should be written. If `typeof position !== 'number'`, the data will be written - * at the current position. - * - * The callback will be given three arguments: `err`, `bytesWritten`, and`buffers`. `bytesWritten` is how many bytes were written from `buffers`. - * - * If this method is `util.promisify()` ed, it returns a promise for an`Object` with `bytesWritten` and `buffers` properties. - * - * It is unsafe to use `fs.writev()` multiple times on the same file without - * waiting for the callback. For this scenario, use {@link createWriteStream}. - * - * On Linux, positional writes don't work when the file is opened in append mode. - * The kernel ignores the position argument and always appends the data to - * the end of the file. - * @since v12.9.0 - * @param [position='null'] - */ - export function writev( - fd: number, - buffers: readonly NodeJS.ArrayBufferView[], - cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void, - ): void; - export function writev( - fd: number, - buffers: readonly NodeJS.ArrayBufferView[], - position: number, - cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void, - ): void; - export interface WriteVResult { - bytesWritten: number; - buffers: NodeJS.ArrayBufferView[]; - } - export namespace writev { - function __promisify__( - fd: number, - buffers: readonly NodeJS.ArrayBufferView[], - position?: number, - ): Promise; - } - /** - * For detailed information, see the documentation of the asynchronous version of - * this API: {@link writev}. - * @since v12.9.0 - * @param [position='null'] - * @return The number of bytes written. - */ - export function writevSync(fd: number, buffers: readonly NodeJS.ArrayBufferView[], position?: number): number; - /** - * Read from a file specified by `fd` and write to an array of `ArrayBufferView`s - * using `readv()`. - * - * `position` is the offset from the beginning of the file from where data - * should be read. If `typeof position !== 'number'`, the data will be read - * from the current position. - * - * The callback will be given three arguments: `err`, `bytesRead`, and`buffers`. `bytesRead` is how many bytes were read from the file. - * - * If this method is invoked as its `util.promisify()` ed version, it returns - * a promise for an `Object` with `bytesRead` and `buffers` properties. - * @since v13.13.0, v12.17.0 - * @param [position='null'] - */ - export function readv( - fd: number, - buffers: readonly NodeJS.ArrayBufferView[], - cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void, - ): void; - export function readv( - fd: number, - buffers: readonly NodeJS.ArrayBufferView[], - position: number, - cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void, - ): void; - export interface ReadVResult { - bytesRead: number; - buffers: NodeJS.ArrayBufferView[]; - } - export namespace readv { - function __promisify__( - fd: number, - buffers: readonly NodeJS.ArrayBufferView[], - position?: number, - ): Promise; - } - /** - * For detailed information, see the documentation of the asynchronous version of - * this API: {@link readv}. - * @since v13.13.0, v12.17.0 - * @param [position='null'] - * @return The number of bytes read. - */ - export function readvSync(fd: number, buffers: readonly NodeJS.ArrayBufferView[], position?: number): number; - - export interface OpenAsBlobOptions { - /** - * An optional mime type for the blob. - * - * @default 'undefined' - */ - type?: string | undefined; - } - - /** - * Returns a `Blob` whose data is backed by the given file. - * - * The file must not be modified after the `Blob` is created. Any modifications - * will cause reading the `Blob` data to fail with a `DOMException` error. - * Synchronous stat operations on the file when the `Blob` is created, and before - * each read in order to detect whether the file data has been modified on disk. - * - * ```js - * import { openAsBlob } from 'node:fs'; - * - * const blob = await openAsBlob('the.file.txt'); - * const ab = await blob.arrayBuffer(); - * blob.stream(); - * ``` - * @since v19.8.0 - * @experimental - */ - export function openAsBlob(path: PathLike, options?: OpenAsBlobOptions): Promise; - - export interface OpenDirOptions { - /** - * @default 'utf8' - */ - encoding?: BufferEncoding | undefined; - /** - * Number of directory entries that are buffered - * internally when reading from the directory. Higher values lead to better - * performance but higher memory usage. - * @default 32 - */ - bufferSize?: number | undefined; - /** - * @default false - */ - recursive?: boolean; - } - /** - * Synchronously open a directory. See [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html). - * - * Creates an `fs.Dir`, which contains all further functions for reading from - * and cleaning up the directory. - * - * The `encoding` option sets the encoding for the `path` while opening the - * directory and subsequent read operations. - * @since v12.12.0 - */ - export function opendirSync(path: PathLike, options?: OpenDirOptions): Dir; - /** - * Asynchronously open a directory. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for - * more details. - * - * Creates an `fs.Dir`, which contains all further functions for reading from - * and cleaning up the directory. - * - * The `encoding` option sets the encoding for the `path` while opening the - * directory and subsequent read operations. - * @since v12.12.0 - */ - export function opendir(path: PathLike, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; - export function opendir( - path: PathLike, - options: OpenDirOptions, - cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void, - ): void; - export namespace opendir { - function __promisify__(path: PathLike, options?: OpenDirOptions): Promise; - } - export interface BigIntStats extends StatsBase { - atimeNs: bigint; - mtimeNs: bigint; - ctimeNs: bigint; - birthtimeNs: bigint; - } - export interface BigIntOptions { - bigint: true; - } - export interface StatOptions { - bigint?: boolean | undefined; - } - export interface StatSyncOptions extends StatOptions { - throwIfNoEntry?: boolean | undefined; - } - interface CopyOptionsBase { - /** - * Dereference symlinks - * @default false - */ - dereference?: boolean; - /** - * When `force` is `false`, and the destination - * exists, throw an error. - * @default false - */ - errorOnExist?: boolean; - /** - * Overwrite existing file or directory. _The copy - * operation will ignore errors if you set this to false and the destination - * exists. Use the `errorOnExist` option to change this behavior. - * @default true - */ - force?: boolean; - /** - * Modifiers for copy operation. See `mode` flag of {@link copyFileSync()} - */ - mode?: number; - /** - * When `true` timestamps from `src` will - * be preserved. - * @default false - */ - preserveTimestamps?: boolean; - /** - * Copy directories recursively. - * @default false - */ - recursive?: boolean; - /** - * When true, path resolution for symlinks will be skipped - * @default false - */ - verbatimSymlinks?: boolean; - } - export interface CopyOptions extends CopyOptionsBase { - /** - * Function to filter copied files/directories. Return - * `true` to copy the item, `false` to ignore it. - */ - filter?(source: string, destination: string): boolean | Promise; - } - export interface CopySyncOptions extends CopyOptionsBase { - /** - * Function to filter copied files/directories. Return - * `true` to copy the item, `false` to ignore it. - */ - filter?(source: string, destination: string): boolean; - } - /** - * Asynchronously copies the entire directory structure from `src` to `dest`, - * including subdirectories and files. - * - * When copying a directory to another directory, globs are not supported and - * behavior is similar to `cp dir1/ dir2/`. - * @since v16.7.0 - * @experimental - * @param src source path to copy. - * @param dest destination path to copy to. - */ - export function cp( - source: string | URL, - destination: string | URL, - callback: (err: NodeJS.ErrnoException | null) => void, - ): void; - export function cp( - source: string | URL, - destination: string | URL, - opts: CopyOptions, - callback: (err: NodeJS.ErrnoException | null) => void, - ): void; - /** - * Synchronously copies the entire directory structure from `src` to `dest`, - * including subdirectories and files. - * - * When copying a directory to another directory, globs are not supported and - * behavior is similar to `cp dir1/ dir2/`. - * @since v16.7.0 - * @experimental - * @param src source path to copy. - * @param dest destination path to copy to. - */ - export function cpSync(source: string | URL, destination: string | URL, opts?: CopySyncOptions): void; -} -declare module "node:fs" { - export * from "fs"; -} diff --git a/node_modules/@types/node/ts4.8/fs/promises.d.ts b/node_modules/@types/node/ts4.8/fs/promises.d.ts deleted file mode 100644 index 88a9fc33e91344c14cf676cb9317eda1f1cb96f7..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/fs/promises.d.ts +++ /dev/null @@ -1,1239 +0,0 @@ -/** - * The `fs/promises` API provides asynchronous file system methods that return - * promises. - * - * The promise APIs use the underlying Node.js threadpool to perform file - * system operations off the event loop thread. These operations are not - * synchronized or threadsafe. Care must be taken when performing multiple - * concurrent modifications on the same file or data corruption may occur. - * @since v10.0.0 - */ -declare module "fs/promises" { - import { Abortable } from "node:events"; - import { Stream } from "node:stream"; - import { ReadableStream } from "node:stream/web"; - import { - BigIntStats, - BigIntStatsFs, - BufferEncodingOption, - constants as fsConstants, - CopyOptions, - Dir, - Dirent, - MakeDirectoryOptions, - Mode, - ObjectEncodingOptions, - OpenDirOptions, - OpenMode, - PathLike, - ReadStream, - ReadVResult, - RmDirOptions, - RmOptions, - StatFsOptions, - StatOptions, - Stats, - StatsFs, - TimeLike, - WatchEventType, - WatchOptions, - WriteStream, - WriteVResult, - } from "node:fs"; - import { Interface as ReadlineInterface } from "node:readline"; - interface FileChangeInfo { - eventType: WatchEventType; - filename: T | null; - } - interface FlagAndOpenMode { - mode?: Mode | undefined; - flag?: OpenMode | undefined; - } - interface FileReadResult { - bytesRead: number; - buffer: T; - } - interface FileReadOptions { - /** - * @default `Buffer.alloc(0xffff)` - */ - buffer?: T; - /** - * @default 0 - */ - offset?: number | null; - /** - * @default `buffer.byteLength` - */ - length?: number | null; - position?: number | null; - } - interface CreateReadStreamOptions { - encoding?: BufferEncoding | null | undefined; - autoClose?: boolean | undefined; - emitClose?: boolean | undefined; - start?: number | undefined; - end?: number | undefined; - highWaterMark?: number | undefined; - } - interface CreateWriteStreamOptions { - encoding?: BufferEncoding | null | undefined; - autoClose?: boolean | undefined; - emitClose?: boolean | undefined; - start?: number | undefined; - highWaterMark?: number | undefined; - flush?: boolean | undefined; - } - interface ReadableWebStreamOptions { - /** - * Whether to open a normal or a `'bytes'` stream. - * @since v20.0.0 - */ - type?: "bytes" | undefined; - } - // TODO: Add `EventEmitter` close - interface FileHandle { - /** - * The numeric file descriptor managed by the {FileHandle} object. - * @since v10.0.0 - */ - readonly fd: number; - /** - * Alias of `filehandle.writeFile()`. - * - * When operating on file handles, the mode cannot be changed from what it was set - * to with `fsPromises.open()`. Therefore, this is equivalent to `filehandle.writeFile()`. - * @since v10.0.0 - * @return Fulfills with `undefined` upon success. - */ - appendFile( - data: string | Uint8Array, - options?: - | (ObjectEncodingOptions & FlagAndOpenMode & { flush?: boolean | undefined }) - | BufferEncoding - | null, - ): Promise; - /** - * Changes the ownership of the file. A wrapper for [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html). - * @since v10.0.0 - * @param uid The file's new owner's user id. - * @param gid The file's new group's group id. - * @return Fulfills with `undefined` upon success. - */ - chown(uid: number, gid: number): Promise; - /** - * Modifies the permissions on the file. See [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html). - * @since v10.0.0 - * @param mode the file mode bit mask. - * @return Fulfills with `undefined` upon success. - */ - chmod(mode: Mode): Promise; - /** - * Unlike the 16 KiB default `highWaterMark` for a `stream.Readable`, the stream - * returned by this method has a default `highWaterMark` of 64 KiB. - * - * `options` can include `start` and `end` values to read a range of bytes from - * the file instead of the entire file. Both `start` and `end` are inclusive and - * start counting at 0, allowed values are in the - * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `start` is - * omitted or `undefined`, `filehandle.createReadStream()` reads sequentially from - * the current file position. The `encoding` can be any one of those accepted by `Buffer`. - * - * If the `FileHandle` points to a character device that only supports blocking - * reads (such as keyboard or sound card), read operations do not finish until data - * is available. This can prevent the process from exiting and the stream from - * closing naturally. - * - * By default, the stream will emit a `'close'` event after it has been - * destroyed. Set the `emitClose` option to `false` to change this behavior. - * - * ```js - * import { open } from 'node:fs/promises'; - * - * const fd = await open('/dev/input/event0'); - * // Create a stream from some character device. - * const stream = fd.createReadStream(); - * setTimeout(() => { - * stream.close(); // This may not close the stream. - * // Artificially marking end-of-stream, as if the underlying resource had - * // indicated end-of-file by itself, allows the stream to close. - * // This does not cancel pending read operations, and if there is such an - * // operation, the process may still not be able to exit successfully - * // until it finishes. - * stream.push(null); - * stream.read(0); - * }, 100); - * ``` - * - * If `autoClose` is false, then the file descriptor won't be closed, even if - * there's an error. It is the application's responsibility to close it and make - * sure there's no file descriptor leak. If `autoClose` is set to true (default - * behavior), on `'error'` or `'end'` the file descriptor will be closed - * automatically. - * - * An example to read the last 10 bytes of a file which is 100 bytes long: - * - * ```js - * import { open } from 'node:fs/promises'; - * - * const fd = await open('sample.txt'); - * fd.createReadStream({ start: 90, end: 99 }); - * ``` - * @since v16.11.0 - */ - createReadStream(options?: CreateReadStreamOptions): ReadStream; - /** - * `options` may also include a `start` option to allow writing data at some - * position past the beginning of the file, allowed values are in the - * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than - * replacing it may require the `flags` `open` option to be set to `r+` rather than - * the default `r`. The `encoding` can be any one of those accepted by `Buffer`. - * - * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'`the file descriptor will be closed automatically. If `autoClose` is false, - * then the file descriptor won't be closed, even if there's an error. - * It is the application's responsibility to close it and make sure there's no - * file descriptor leak. - * - * By default, the stream will emit a `'close'` event after it has been - * destroyed. Set the `emitClose` option to `false` to change this behavior. - * @since v16.11.0 - */ - createWriteStream(options?: CreateWriteStreamOptions): WriteStream; - /** - * Forces all currently queued I/O operations associated with the file to the - * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. - * - * Unlike `filehandle.sync` this method does not flush modified metadata. - * @since v10.0.0 - * @return Fulfills with `undefined` upon success. - */ - datasync(): Promise; - /** - * Request that all data for the open file descriptor is flushed to the storage - * device. The specific implementation is operating system and device specific. - * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. - * @since v10.0.0 - * @return Fulfills with `undefined` upon success. - */ - sync(): Promise; - /** - * Reads data from the file and stores that in the given buffer. - * - * If the file is not modified concurrently, the end-of-file is reached when the - * number of bytes read is zero. - * @since v10.0.0 - * @param buffer A buffer that will be filled with the file data read. - * @param offset The location in the buffer at which to start filling. - * @param length The number of bytes to read. - * @param position The location where to begin reading data from the file. If `null`, data will be read from the current file position, and the position will be updated. If `position` is an - * integer, the current file position will remain unchanged. - * @return Fulfills upon success with an object with two properties: - */ - read( - buffer: T, - offset?: number | null, - length?: number | null, - position?: number | null, - ): Promise>; - read(options?: FileReadOptions): Promise>; - /** - * Returns a `ReadableStream` that may be used to read the files data. - * - * An error will be thrown if this method is called more than once or is called - * after the `FileHandle` is closed or closing. - * - * ```js - * import { - * open, - * } from 'node:fs/promises'; - * - * const file = await open('./some/file/to/read'); - * - * for await (const chunk of file.readableWebStream()) - * console.log(chunk); - * - * await file.close(); - * ``` - * - * While the `ReadableStream` will read the file to completion, it will not - * close the `FileHandle` automatically. User code must still call the`fileHandle.close()` method. - * @since v17.0.0 - * @experimental - */ - readableWebStream(options?: ReadableWebStreamOptions): ReadableStream; - /** - * Asynchronously reads the entire contents of a file. - * - * If `options` is a string, then it specifies the `encoding`. - * - * The `FileHandle` has to support reading. - * - * If one or more `filehandle.read()` calls are made on a file handle and then a`filehandle.readFile()` call is made, the data will be read from the current - * position till the end of the file. It doesn't always read from the beginning - * of the file. - * @since v10.0.0 - * @return Fulfills upon a successful read with the contents of the file. If no encoding is specified (using `options.encoding`), the data is returned as a {Buffer} object. Otherwise, the - * data will be a string. - */ - readFile( - options?: { - encoding?: null | undefined; - flag?: OpenMode | undefined; - } | null, - ): Promise; - /** - * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. - * The `FileHandle` must have been opened for reading. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - readFile( - options: - | { - encoding: BufferEncoding; - flag?: OpenMode | undefined; - } - | BufferEncoding, - ): Promise; - /** - * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. - * The `FileHandle` must have been opened for reading. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - readFile( - options?: - | (ObjectEncodingOptions & { - flag?: OpenMode | undefined; - }) - | BufferEncoding - | null, - ): Promise; - /** - * Convenience method to create a `readline` interface and stream over the file. - * See `filehandle.createReadStream()` for the options. - * - * ```js - * import { open } from 'node:fs/promises'; - * - * const file = await open('./some/file/to/read'); - * - * for await (const line of file.readLines()) { - * console.log(line); - * } - * ``` - * @since v18.11.0 - */ - readLines(options?: CreateReadStreamOptions): ReadlineInterface; - /** - * @since v10.0.0 - * @return Fulfills with an {fs.Stats} for the file. - */ - stat( - opts?: StatOptions & { - bigint?: false | undefined; - }, - ): Promise; - stat( - opts: StatOptions & { - bigint: true; - }, - ): Promise; - stat(opts?: StatOptions): Promise; - /** - * Truncates the file. - * - * If the file was larger than `len` bytes, only the first `len` bytes will be - * retained in the file. - * - * The following example retains only the first four bytes of the file: - * - * ```js - * import { open } from 'node:fs/promises'; - * - * let filehandle = null; - * try { - * filehandle = await open('temp.txt', 'r+'); - * await filehandle.truncate(4); - * } finally { - * await filehandle?.close(); - * } - * ``` - * - * If the file previously was shorter than `len` bytes, it is extended, and the - * extended part is filled with null bytes (`'\0'`): - * - * If `len` is negative then `0` will be used. - * @since v10.0.0 - * @param [len=0] - * @return Fulfills with `undefined` upon success. - */ - truncate(len?: number): Promise; - /** - * Change the file system timestamps of the object referenced by the `FileHandle` then fulfills the promise with no arguments upon success. - * @since v10.0.0 - */ - utimes(atime: TimeLike, mtime: TimeLike): Promise; - /** - * Asynchronously writes data to a file, replacing the file if it already exists.`data` can be a string, a buffer, an - * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an - * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. - * The promise is fulfilled with no arguments upon success. - * - * If `options` is a string, then it specifies the `encoding`. - * - * The `FileHandle` has to support writing. - * - * It is unsafe to use `filehandle.writeFile()` multiple times on the same file - * without waiting for the promise to be fulfilled (or rejected). - * - * If one or more `filehandle.write()` calls are made on a file handle and then a`filehandle.writeFile()` call is made, the data will be written from the - * current position till the end of the file. It doesn't always write from the - * beginning of the file. - * @since v10.0.0 - */ - writeFile( - data: string | Uint8Array, - options?: - | (ObjectEncodingOptions & FlagAndOpenMode & Abortable & { flush?: boolean | undefined }) - | BufferEncoding - | null, - ): Promise; - /** - * Write `buffer` to the file. - * - * The promise is fulfilled with an object containing two properties: - * - * It is unsafe to use `filehandle.write()` multiple times on the same file - * without waiting for the promise to be fulfilled (or rejected). For this - * scenario, use `filehandle.createWriteStream()`. - * - * On Linux, positional writes do not work when the file is opened in append mode. - * The kernel ignores the position argument and always appends the data to - * the end of the file. - * @since v10.0.0 - * @param offset The start position from within `buffer` where the data to write begins. - * @param [length=buffer.byteLength - offset] The number of bytes from `buffer` to write. - * @param [position='null'] The offset from the beginning of the file where the data from `buffer` should be written. If `position` is not a `number`, the data will be written at the current - * position. See the POSIX pwrite(2) documentation for more detail. - */ - write( - buffer: TBuffer, - offset?: number | null, - length?: number | null, - position?: number | null, - ): Promise<{ - bytesWritten: number; - buffer: TBuffer; - }>; - write( - data: string, - position?: number | null, - encoding?: BufferEncoding | null, - ): Promise<{ - bytesWritten: number; - buffer: string; - }>; - /** - * Write an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s to the file. - * - * The promise is fulfilled with an object containing a two properties: - * - * It is unsafe to call `writev()` multiple times on the same file without waiting - * for the promise to be fulfilled (or rejected). - * - * On Linux, positional writes don't work when the file is opened in append mode. - * The kernel ignores the position argument and always appends the data to - * the end of the file. - * @since v12.9.0 - * @param [position='null'] The offset from the beginning of the file where the data from `buffers` should be written. If `position` is not a `number`, the data will be written at the current - * position. - */ - writev(buffers: readonly NodeJS.ArrayBufferView[], position?: number): Promise; - /** - * Read from a file and write to an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s - * @since v13.13.0, v12.17.0 - * @param [position='null'] The offset from the beginning of the file where the data should be read from. If `position` is not a `number`, the data will be read from the current position. - * @return Fulfills upon success an object containing two properties: - */ - readv(buffers: readonly NodeJS.ArrayBufferView[], position?: number): Promise; - /** - * Closes the file handle after waiting for any pending operation on the handle to - * complete. - * - * ```js - * import { open } from 'node:fs/promises'; - * - * let filehandle; - * try { - * filehandle = await open('thefile.txt', 'r'); - * } finally { - * await filehandle?.close(); - * } - * ``` - * @since v10.0.0 - * @return Fulfills with `undefined` upon success. - */ - close(): Promise; - /** - * An alias for {@link FileHandle.close()}. - * @since v20.4.0 - */ - [Symbol.asyncDispose](): Promise; - } - const constants: typeof fsConstants; - /** - * Tests a user's permissions for the file or directory specified by `path`. - * The `mode` argument is an optional integer that specifies the accessibility - * checks to be performed. `mode` should be either the value `fs.constants.F_OK`or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`,`fs.constants.W_OK`, and `fs.constants.X_OK` - * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for - * possible values of `mode`. - * - * If the accessibility check is successful, the promise is fulfilled with no - * value. If any of the accessibility checks fail, the promise is rejected - * with an [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object. The following example checks if the file`/etc/passwd` can be read and - * written by the current process. - * - * ```js - * import { access, constants } from 'node:fs/promises'; - * - * try { - * await access('/etc/passwd', constants.R_OK | constants.W_OK); - * console.log('can access'); - * } catch { - * console.error('cannot access'); - * } - * ``` - * - * Using `fsPromises.access()` to check for the accessibility of a file before - * calling `fsPromises.open()` is not recommended. Doing so introduces a race - * condition, since other processes may change the file's state between the two - * calls. Instead, user code should open/read/write the file directly and handle - * the error raised if the file is not accessible. - * @since v10.0.0 - * @param [mode=fs.constants.F_OK] - * @return Fulfills with `undefined` upon success. - */ - function access(path: PathLike, mode?: number): Promise; - /** - * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it - * already exists. - * - * No guarantees are made about the atomicity of the copy operation. If an - * error occurs after the destination file has been opened for writing, an attempt - * will be made to remove the destination. - * - * ```js - * import { copyFile, constants } from 'node:fs/promises'; - * - * try { - * await copyFile('source.txt', 'destination.txt'); - * console.log('source.txt was copied to destination.txt'); - * } catch { - * console.error('The file could not be copied'); - * } - * - * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. - * try { - * await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL); - * console.log('source.txt was copied to destination.txt'); - * } catch { - * console.error('The file could not be copied'); - * } - * ``` - * @since v10.0.0 - * @param src source filename to copy - * @param dest destination filename of the copy operation - * @param [mode=0] Optional modifiers that specify the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. - * `fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`) - * @return Fulfills with `undefined` upon success. - */ - function copyFile(src: PathLike, dest: PathLike, mode?: number): Promise; - /** - * Opens a `FileHandle`. - * - * Refer to the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more detail. - * - * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented - * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains - * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). - * @since v10.0.0 - * @param [flags='r'] See `support of file system `flags``. - * @param [mode=0o666] Sets the file mode (permission and sticky bits) if the file is created. - * @return Fulfills with a {FileHandle} object. - */ - function open(path: PathLike, flags?: string | number, mode?: Mode): Promise; - /** - * Renames `oldPath` to `newPath`. - * @since v10.0.0 - * @return Fulfills with `undefined` upon success. - */ - function rename(oldPath: PathLike, newPath: PathLike): Promise; - /** - * Truncates (shortens or extends the length) of the content at `path` to `len`bytes. - * @since v10.0.0 - * @param [len=0] - * @return Fulfills with `undefined` upon success. - */ - function truncate(path: PathLike, len?: number): Promise; - /** - * Removes the directory identified by `path`. - * - * Using `fsPromises.rmdir()` on a file (not a directory) results in the - * promise being rejected with an `ENOENT` error on Windows and an `ENOTDIR`error on POSIX. - * - * To get a behavior similar to the `rm -rf` Unix command, use `fsPromises.rm()` with options `{ recursive: true, force: true }`. - * @since v10.0.0 - * @return Fulfills with `undefined` upon success. - */ - function rmdir(path: PathLike, options?: RmDirOptions): Promise; - /** - * Removes files and directories (modeled on the standard POSIX `rm` utility). - * @since v14.14.0 - * @return Fulfills with `undefined` upon success. - */ - function rm(path: PathLike, options?: RmOptions): Promise; - /** - * Asynchronously creates a directory. - * - * The optional `options` argument can be an integer specifying `mode` (permission - * and sticky bits), or an object with a `mode` property and a `recursive`property indicating whether parent directories should be created. Calling`fsPromises.mkdir()` when `path` is a directory - * that exists results in a - * rejection only when `recursive` is false. - * - * ```js - * import { mkdir } from 'node:fs/promises'; - * - * try { - * const projectFolder = new URL('./test/project/', import.meta.url); - * const createDir = await mkdir(projectFolder, { recursive: true }); - * - * console.log(`created ${createDir}`); - * } catch (err) { - * console.error(err.message); - * } - * ``` - * @since v10.0.0 - * @return Upon success, fulfills with `undefined` if `recursive` is `false`, or the first directory path created if `recursive` is `true`. - */ - function mkdir( - path: PathLike, - options: MakeDirectoryOptions & { - recursive: true; - }, - ): Promise; - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - function mkdir( - path: PathLike, - options?: - | Mode - | (MakeDirectoryOptions & { - recursive?: false | undefined; - }) - | null, - ): Promise; - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - function mkdir(path: PathLike, options?: Mode | MakeDirectoryOptions | null): Promise; - /** - * Reads the contents of a directory. - * - * The optional `options` argument can be a string specifying an encoding, or an - * object with an `encoding` property specifying the character encoding to use for - * the filenames. If the `encoding` is set to `'buffer'`, the filenames returned - * will be passed as `Buffer` objects. - * - * If `options.withFileTypes` is set to `true`, the returned array will contain `fs.Dirent` objects. - * - * ```js - * import { readdir } from 'node:fs/promises'; - * - * try { - * const files = await readdir(path); - * for (const file of files) - * console.log(file); - * } catch (err) { - * console.error(err); - * } - * ``` - * @since v10.0.0 - * @return Fulfills with an array of the names of the files in the directory excluding `'.'` and `'..'`. - */ - function readdir( - path: PathLike, - options?: - | (ObjectEncodingOptions & { - withFileTypes?: false | undefined; - recursive?: boolean | undefined; - }) - | BufferEncoding - | null, - ): Promise; - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readdir( - path: PathLike, - options: - | { - encoding: "buffer"; - withFileTypes?: false | undefined; - recursive?: boolean | undefined; - } - | "buffer", - ): Promise; - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readdir( - path: PathLike, - options?: - | (ObjectEncodingOptions & { - withFileTypes?: false | undefined; - recursive?: boolean | undefined; - }) - | BufferEncoding - | null, - ): Promise; - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. - */ - function readdir( - path: PathLike, - options: ObjectEncodingOptions & { - withFileTypes: true; - recursive?: boolean | undefined; - }, - ): Promise; - /** - * Reads the contents of the symbolic link referred to by `path`. See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more detail. The promise is - * fulfilled with the`linkString` upon success. - * - * The optional `options` argument can be a string specifying an encoding, or an - * object with an `encoding` property specifying the character encoding to use for - * the link path returned. If the `encoding` is set to `'buffer'`, the link path - * returned will be passed as a `Buffer` object. - * @since v10.0.0 - * @return Fulfills with the `linkString` upon success. - */ - function readlink(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readlink(path: PathLike, options: BufferEncodingOption): Promise; - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readlink(path: PathLike, options?: ObjectEncodingOptions | string | null): Promise; - /** - * Creates a symbolic link. - * - * The `type` argument is only used on Windows platforms and can be one of `'dir'`,`'file'`, or `'junction'`. If the `type` argument is not a string, Node.js will - * autodetect `target` type and use `'file'` or `'dir'`. If the `target` does not - * exist, `'file'` will be used. Windows junction points require the destination - * path to be absolute. When using `'junction'`, the `target` argument will - * automatically be normalized to absolute path. Junction points on NTFS volumes - * can only point to directories. - * @since v10.0.0 - * @param [type='null'] - * @return Fulfills with `undefined` upon success. - */ - function symlink(target: PathLike, path: PathLike, type?: string | null): Promise; - /** - * Equivalent to `fsPromises.stat()` unless `path` refers to a symbolic link, - * in which case the link itself is stat-ed, not the file that it refers to. - * Refer to the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) document for more detail. - * @since v10.0.0 - * @return Fulfills with the {fs.Stats} object for the given symbolic link `path`. - */ - function lstat( - path: PathLike, - opts?: StatOptions & { - bigint?: false | undefined; - }, - ): Promise; - function lstat( - path: PathLike, - opts: StatOptions & { - bigint: true; - }, - ): Promise; - function lstat(path: PathLike, opts?: StatOptions): Promise; - /** - * @since v10.0.0 - * @return Fulfills with the {fs.Stats} object for the given `path`. - */ - function stat( - path: PathLike, - opts?: StatOptions & { - bigint?: false | undefined; - }, - ): Promise; - function stat( - path: PathLike, - opts: StatOptions & { - bigint: true; - }, - ): Promise; - function stat(path: PathLike, opts?: StatOptions): Promise; - /** - * @since v19.6.0, v18.15.0 - * @return Fulfills with the {fs.StatFs} object for the given `path`. - */ - function statfs( - path: PathLike, - opts?: StatFsOptions & { - bigint?: false | undefined; - }, - ): Promise; - function statfs( - path: PathLike, - opts: StatFsOptions & { - bigint: true; - }, - ): Promise; - function statfs(path: PathLike, opts?: StatFsOptions): Promise; - /** - * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. - * @since v10.0.0 - * @return Fulfills with `undefined` upon success. - */ - function link(existingPath: PathLike, newPath: PathLike): Promise; - /** - * If `path` refers to a symbolic link, then the link is removed without affecting - * the file or directory to which that link refers. If the `path` refers to a file - * path that is not a symbolic link, the file is deleted. See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more detail. - * @since v10.0.0 - * @return Fulfills with `undefined` upon success. - */ - function unlink(path: PathLike): Promise; - /** - * Changes the permissions of a file. - * @since v10.0.0 - * @return Fulfills with `undefined` upon success. - */ - function chmod(path: PathLike, mode: Mode): Promise; - /** - * Changes the permissions on a symbolic link. - * - * This method is only implemented on macOS. - * @deprecated Since v10.0.0 - * @return Fulfills with `undefined` upon success. - */ - function lchmod(path: PathLike, mode: Mode): Promise; - /** - * Changes the ownership on a symbolic link. - * @since v10.0.0 - * @return Fulfills with `undefined` upon success. - */ - function lchown(path: PathLike, uid: number, gid: number): Promise; - /** - * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, with the difference that if the path refers to a - * symbolic link, then the link is not dereferenced: instead, the timestamps of - * the symbolic link itself are changed. - * @since v14.5.0, v12.19.0 - * @return Fulfills with `undefined` upon success. - */ - function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; - /** - * Changes the ownership of a file. - * @since v10.0.0 - * @return Fulfills with `undefined` upon success. - */ - function chown(path: PathLike, uid: number, gid: number): Promise; - /** - * Change the file system timestamps of the object referenced by `path`. - * - * The `atime` and `mtime` arguments follow these rules: - * - * * Values can be either numbers representing Unix epoch time, `Date`s, or a - * numeric string like `'123456789.0'`. - * * If the value can not be converted to a number, or is `NaN`, `Infinity`, or`-Infinity`, an `Error` will be thrown. - * @since v10.0.0 - * @return Fulfills with `undefined` upon success. - */ - function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; - /** - * Determines the actual location of `path` using the same semantics as the`fs.realpath.native()` function. - * - * Only paths that can be converted to UTF8 strings are supported. - * - * The optional `options` argument can be a string specifying an encoding, or an - * object with an `encoding` property specifying the character encoding to use for - * the path. If the `encoding` is set to `'buffer'`, the path returned will be - * passed as a `Buffer` object. - * - * On Linux, when Node.js is linked against musl libc, the procfs file system must - * be mounted on `/proc` in order for this function to work. Glibc does not have - * this restriction. - * @since v10.0.0 - * @return Fulfills with the resolved path upon success. - */ - function realpath(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function realpath(path: PathLike, options: BufferEncodingOption): Promise; - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function realpath( - path: PathLike, - options?: ObjectEncodingOptions | BufferEncoding | null, - ): Promise; - /** - * Creates a unique temporary directory. A unique directory name is generated by - * appending six random characters to the end of the provided `prefix`. Due to - * platform inconsistencies, avoid trailing `X` characters in `prefix`. Some - * platforms, notably the BSDs, can return more than six random characters, and - * replace trailing `X` characters in `prefix` with random characters. - * - * The optional `options` argument can be a string specifying an encoding, or an - * object with an `encoding` property specifying the character encoding to use. - * - * ```js - * import { mkdtemp } from 'node:fs/promises'; - * import { join } from 'node:path'; - * import { tmpdir } from 'node:os'; - * - * try { - * await mkdtemp(join(tmpdir(), 'foo-')); - * } catch (err) { - * console.error(err); - * } - * ``` - * - * The `fsPromises.mkdtemp()` method will append the six randomly selected - * characters directly to the `prefix` string. For instance, given a directory`/tmp`, if the intention is to create a temporary directory _within_`/tmp`, the`prefix` must end with a trailing - * platform-specific path separator - * (`require('node:path').sep`). - * @since v10.0.0 - * @return Fulfills with a string containing the file system path of the newly created temporary directory. - */ - function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function mkdtemp(prefix: string, options: BufferEncodingOption): Promise; - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; - /** - * Asynchronously writes data to a file, replacing the file if it already exists.`data` can be a string, a buffer, an - * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an - * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. - * - * The `encoding` option is ignored if `data` is a buffer. - * - * If `options` is a string, then it specifies the encoding. - * - * The `mode` option only affects the newly created file. See `fs.open()` for more details. - * - * Any specified `FileHandle` has to support writing. - * - * It is unsafe to use `fsPromises.writeFile()` multiple times on the same file - * without waiting for the promise to be settled. - * - * Similarly to `fsPromises.readFile` \- `fsPromises.writeFile` is a convenience - * method that performs multiple `write` calls internally to write the buffer - * passed to it. For performance sensitive code consider using `fs.createWriteStream()` or `filehandle.createWriteStream()`. - * - * It is possible to use an `AbortSignal` to cancel an `fsPromises.writeFile()`. - * Cancelation is "best effort", and some amount of data is likely still - * to be written. - * - * ```js - * import { writeFile } from 'node:fs/promises'; - * import { Buffer } from 'node:buffer'; - * - * try { - * const controller = new AbortController(); - * const { signal } = controller; - * const data = new Uint8Array(Buffer.from('Hello Node.js')); - * const promise = writeFile('message.txt', data, { signal }); - * - * // Abort the request before the promise settles. - * controller.abort(); - * - * await promise; - * } catch (err) { - * // When a request is aborted - err is an AbortError - * console.error(err); - * } - * ``` - * - * Aborting an ongoing request does not abort individual operating - * system requests but rather the internal buffering `fs.writeFile` performs. - * @since v10.0.0 - * @param file filename or `FileHandle` - * @return Fulfills with `undefined` upon success. - */ - function writeFile( - file: PathLike | FileHandle, - data: - | string - | NodeJS.ArrayBufferView - | Iterable - | AsyncIterable - | Stream, - options?: - | (ObjectEncodingOptions & { - mode?: Mode | undefined; - flag?: OpenMode | undefined; - } & Abortable) - | BufferEncoding - | null, - ): Promise; - /** - * Asynchronously append data to a file, creating the file if it does not yet - * exist. `data` can be a string or a `Buffer`. - * - * If `options` is a string, then it specifies the `encoding`. - * - * The `mode` option only affects the newly created file. See `fs.open()` for more details. - * - * The `path` may be specified as a `FileHandle` that has been opened - * for appending (using `fsPromises.open()`). - * @since v10.0.0 - * @param path filename or {FileHandle} - * @return Fulfills with `undefined` upon success. - */ - function appendFile( - path: PathLike | FileHandle, - data: string | Uint8Array, - options?: (ObjectEncodingOptions & FlagAndOpenMode & { flush?: boolean | undefined }) | BufferEncoding | null, - ): Promise; - /** - * Asynchronously reads the entire contents of a file. - * - * If no encoding is specified (using `options.encoding`), the data is returned - * as a `Buffer` object. Otherwise, the data will be a string. - * - * If `options` is a string, then it specifies the encoding. - * - * When the `path` is a directory, the behavior of `fsPromises.readFile()` is - * platform-specific. On macOS, Linux, and Windows, the promise will be rejected - * with an error. On FreeBSD, a representation of the directory's contents will be - * returned. - * - * An example of reading a `package.json` file located in the same directory of the - * running code: - * - * ```js - * import { readFile } from 'node:fs/promises'; - * try { - * const filePath = new URL('./package.json', import.meta.url); - * const contents = await readFile(filePath, { encoding: 'utf8' }); - * console.log(contents); - * } catch (err) { - * console.error(err.message); - * } - * ``` - * - * It is possible to abort an ongoing `readFile` using an `AbortSignal`. If a - * request is aborted the promise returned is rejected with an `AbortError`: - * - * ```js - * import { readFile } from 'node:fs/promises'; - * - * try { - * const controller = new AbortController(); - * const { signal } = controller; - * const promise = readFile(fileName, { signal }); - * - * // Abort the request before the promise settles. - * controller.abort(); - * - * await promise; - * } catch (err) { - * // When a request is aborted - err is an AbortError - * console.error(err); - * } - * ``` - * - * Aborting an ongoing request does not abort individual operating - * system requests but rather the internal buffering `fs.readFile` performs. - * - * Any specified `FileHandle` has to support reading. - * @since v10.0.0 - * @param path filename or `FileHandle` - * @return Fulfills with the contents of the file. - */ - function readFile( - path: PathLike | FileHandle, - options?: - | ({ - encoding?: null | undefined; - flag?: OpenMode | undefined; - } & Abortable) - | null, - ): Promise; - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function readFile( - path: PathLike | FileHandle, - options: - | ({ - encoding: BufferEncoding; - flag?: OpenMode | undefined; - } & Abortable) - | BufferEncoding, - ): Promise; - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function readFile( - path: PathLike | FileHandle, - options?: - | ( - & ObjectEncodingOptions - & Abortable - & { - flag?: OpenMode | undefined; - } - ) - | BufferEncoding - | null, - ): Promise; - /** - * Asynchronously open a directory for iterative scanning. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for more detail. - * - * Creates an `fs.Dir`, which contains all further functions for reading from - * and cleaning up the directory. - * - * The `encoding` option sets the encoding for the `path` while opening the - * directory and subsequent read operations. - * - * Example using async iteration: - * - * ```js - * import { opendir } from 'node:fs/promises'; - * - * try { - * const dir = await opendir('./'); - * for await (const dirent of dir) - * console.log(dirent.name); - * } catch (err) { - * console.error(err); - * } - * ``` - * - * When using the async iterator, the `fs.Dir` object will be automatically - * closed after the iterator exits. - * @since v12.12.0 - * @return Fulfills with an {fs.Dir}. - */ - function opendir(path: PathLike, options?: OpenDirOptions): Promise; - /** - * Returns an async iterator that watches for changes on `filename`, where `filename`is either a file or a directory. - * - * ```js - * const { watch } = require('node:fs/promises'); - * - * const ac = new AbortController(); - * const { signal } = ac; - * setTimeout(() => ac.abort(), 10000); - * - * (async () => { - * try { - * const watcher = watch(__filename, { signal }); - * for await (const event of watcher) - * console.log(event); - * } catch (err) { - * if (err.name === 'AbortError') - * return; - * throw err; - * } - * })(); - * ``` - * - * On most platforms, `'rename'` is emitted whenever a filename appears or - * disappears in the directory. - * - * All the `caveats` for `fs.watch()` also apply to `fsPromises.watch()`. - * @since v15.9.0, v14.18.0 - * @return of objects with the properties: - */ - function watch( - filename: PathLike, - options: - | (WatchOptions & { - encoding: "buffer"; - }) - | "buffer", - ): AsyncIterable>; - /** - * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `persistent` is not supplied, the default of `true` is used. - * If `recursive` is not supplied, the default of `false` is used. - */ - function watch(filename: PathLike, options?: WatchOptions | BufferEncoding): AsyncIterable>; - /** - * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `persistent` is not supplied, the default of `true` is used. - * If `recursive` is not supplied, the default of `false` is used. - */ - function watch( - filename: PathLike, - options: WatchOptions | string, - ): AsyncIterable> | AsyncIterable>; - /** - * Asynchronously copies the entire directory structure from `src` to `dest`, - * including subdirectories and files. - * - * When copying a directory to another directory, globs are not supported and - * behavior is similar to `cp dir1/ dir2/`. - * @since v16.7.0 - * @experimental - * @param src source path to copy. - * @param dest destination path to copy to. - * @return Fulfills with `undefined` upon success. - */ - function cp(source: string | URL, destination: string | URL, opts?: CopyOptions): Promise; -} -declare module "node:fs/promises" { - export * from "fs/promises"; -} diff --git a/node_modules/@types/node/ts4.8/globals.d.ts b/node_modules/@types/node/ts4.8/globals.d.ts deleted file mode 100644 index 5f250062b0295a95916ad2acd6ae8141ff2b5e71..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/globals.d.ts +++ /dev/null @@ -1,411 +0,0 @@ -export {}; // Make this a module - -// #region Fetch and friends -// Conditional type aliases, used at the end of this file. -// Will either be empty if lib-dom is included, or the undici version otherwise. -type _Request = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Request; -type _Response = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Response; -type _FormData = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").FormData; -type _Headers = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Headers; -type _RequestInit = typeof globalThis extends { onmessage: any } ? {} - : import("undici-types").RequestInit; -type _ResponseInit = typeof globalThis extends { onmessage: any } ? {} - : import("undici-types").ResponseInit; -type _File = typeof globalThis extends { onmessage: any } ? {} : import("node:buffer").File; -// #endregion Fetch and friends - -declare global { - // Declare "static" methods in Error - interface ErrorConstructor { - /** Create .stack property on a target object */ - captureStackTrace(targetObject: object, constructorOpt?: Function): void; - - /** - * Optional override for formatting stack traces - * - * @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces - */ - prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; - - stackTraceLimit: number; - } - - /*-----------------------------------------------* - * * - * GLOBAL * - * * - ------------------------------------------------*/ - - // For backwards compability - interface NodeRequire extends NodeJS.Require {} - interface RequireResolve extends NodeJS.RequireResolve {} - interface NodeModule extends NodeJS.Module {} - - var process: NodeJS.Process; - var console: Console; - - var __filename: string; - var __dirname: string; - - var require: NodeRequire; - var module: NodeModule; - - // Same as module.exports - var exports: any; - - /** - * Only available if `--expose-gc` is passed to the process. - */ - var gc: undefined | (() => void); - - // #region borrowed - // from https://github.com/microsoft/TypeScript/blob/38da7c600c83e7b31193a62495239a0fe478cb67/lib/lib.webworker.d.ts#L633 until moved to separate lib - /** A controller object that allows you to abort one or more DOM requests as and when desired. */ - interface AbortController { - /** - * Returns the AbortSignal object associated with this object. - */ - - readonly signal: AbortSignal; - /** - * Invoking this method will set this object's AbortSignal's aborted flag and signal to any observers that the associated activity is to be aborted. - */ - abort(reason?: any): void; - } - - /** A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. */ - interface AbortSignal extends EventTarget { - /** - * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. - */ - readonly aborted: boolean; - readonly reason: any; - onabort: null | ((this: AbortSignal, event: Event) => any); - throwIfAborted(): void; - } - - var AbortController: typeof globalThis extends { onmessage: any; AbortController: infer T } ? T - : { - prototype: AbortController; - new(): AbortController; - }; - - var AbortSignal: typeof globalThis extends { onmessage: any; AbortSignal: infer T } ? T - : { - prototype: AbortSignal; - new(): AbortSignal; - abort(reason?: any): AbortSignal; - timeout(milliseconds: number): AbortSignal; - }; - // #endregion borrowed - - // #region Disposable - interface SymbolConstructor { - /** - * A method that is used to release resources held by an object. Called by the semantics of the `using` statement. - */ - readonly dispose: unique symbol; - - /** - * A method that is used to asynchronously release resources held by an object. Called by the semantics of the `await using` statement. - */ - readonly asyncDispose: unique symbol; - } - - interface Disposable { - [Symbol.dispose](): void; - } - - interface AsyncDisposable { - [Symbol.asyncDispose](): PromiseLike; - } - // #endregion Disposable - - // #region ArrayLike.at() - interface RelativeIndexable { - /** - * Takes an integer value and returns the item at that index, - * allowing for positive and negative integers. - * Negative integers count back from the last item in the array. - */ - at(index: number): T | undefined; - } - interface String extends RelativeIndexable {} - interface Array extends RelativeIndexable {} - interface ReadonlyArray extends RelativeIndexable {} - interface Int8Array extends RelativeIndexable {} - interface Uint8Array extends RelativeIndexable {} - interface Uint8ClampedArray extends RelativeIndexable {} - interface Int16Array extends RelativeIndexable {} - interface Uint16Array extends RelativeIndexable {} - interface Int32Array extends RelativeIndexable {} - interface Uint32Array extends RelativeIndexable {} - interface Float32Array extends RelativeIndexable {} - interface Float64Array extends RelativeIndexable {} - interface BigInt64Array extends RelativeIndexable {} - interface BigUint64Array extends RelativeIndexable {} - // #endregion ArrayLike.at() end - - /** - * @since v17.0.0 - * - * Creates a deep clone of an object. - */ - function structuredClone( - value: T, - transfer?: { transfer: ReadonlyArray }, - ): T; - - /*----------------------------------------------* - * * - * GLOBAL INTERFACES * - * * - *-----------------------------------------------*/ - namespace NodeJS { - interface CallSite { - /** - * Value of "this" - */ - getThis(): unknown; - - /** - * Type of "this" as a string. - * This is the name of the function stored in the constructor field of - * "this", if available. Otherwise the object's [[Class]] internal - * property. - */ - getTypeName(): string | null; - - /** - * Current function - */ - getFunction(): Function | undefined; - - /** - * Name of the current function, typically its name property. - * If a name property is not available an attempt will be made to try - * to infer a name from the function's context. - */ - getFunctionName(): string | null; - - /** - * Name of the property [of "this" or one of its prototypes] that holds - * the current function - */ - getMethodName(): string | null; - - /** - * Name of the script [if this function was defined in a script] - */ - getFileName(): string | undefined; - - /** - * Current line number [if this function was defined in a script] - */ - getLineNumber(): number | null; - - /** - * Current column number [if this function was defined in a script] - */ - getColumnNumber(): number | null; - - /** - * A call site object representing the location where eval was called - * [if this function was created using a call to eval] - */ - getEvalOrigin(): string | undefined; - - /** - * Is this a toplevel invocation, that is, is "this" the global object? - */ - isToplevel(): boolean; - - /** - * Does this call take place in code defined by a call to eval? - */ - isEval(): boolean; - - /** - * Is this call in native V8 code? - */ - isNative(): boolean; - - /** - * Is this a constructor call? - */ - isConstructor(): boolean; - - /** - * is this an async call (i.e. await, Promise.all(), or Promise.any())? - */ - isAsync(): boolean; - - /** - * is this an async call to Promise.all()? - */ - isPromiseAll(): boolean; - - /** - * returns the index of the promise element that was followed in - * Promise.all() or Promise.any() for async stack traces, or null - * if the CallSite is not an async - */ - getPromiseIndex(): number | null; - - getScriptNameOrSourceURL(): string; - getScriptHash(): string; - - getEnclosingColumnNumber(): number; - getEnclosingLineNumber(): number; - getPosition(): number; - - toString(): string; - } - - interface ErrnoException extends Error { - errno?: number | undefined; - code?: string | undefined; - path?: string | undefined; - syscall?: string | undefined; - } - - interface ReadableStream extends EventEmitter { - readable: boolean; - read(size?: number): string | Buffer; - setEncoding(encoding: BufferEncoding): this; - pause(): this; - resume(): this; - isPaused(): boolean; - pipe(destination: T, options?: { end?: boolean | undefined }): T; - unpipe(destination?: WritableStream): this; - unshift(chunk: string | Uint8Array, encoding?: BufferEncoding): void; - wrap(oldStream: ReadableStream): this; - [Symbol.asyncIterator](): AsyncIterableIterator; - } - - interface WritableStream extends EventEmitter { - writable: boolean; - write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean; - write(str: string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean; - end(cb?: () => void): this; - end(data: string | Uint8Array, cb?: () => void): this; - end(str: string, encoding?: BufferEncoding, cb?: () => void): this; - } - - interface ReadWriteStream extends ReadableStream, WritableStream {} - - interface RefCounted { - ref(): this; - unref(): this; - } - - type TypedArray = - | Uint8Array - | Uint8ClampedArray - | Uint16Array - | Uint32Array - | Int8Array - | Int16Array - | Int32Array - | BigUint64Array - | BigInt64Array - | Float32Array - | Float64Array; - type ArrayBufferView = TypedArray | DataView; - - interface Require { - (id: string): any; - resolve: RequireResolve; - cache: Dict; - /** - * @deprecated - */ - extensions: RequireExtensions; - main: Module | undefined; - } - - interface RequireResolve { - (id: string, options?: { paths?: string[] | undefined }): string; - paths(request: string): string[] | null; - } - - interface RequireExtensions extends Dict<(m: Module, filename: string) => any> { - ".js": (m: Module, filename: string) => any; - ".json": (m: Module, filename: string) => any; - ".node": (m: Module, filename: string) => any; - } - interface Module { - /** - * `true` if the module is running during the Node.js preload - */ - isPreloading: boolean; - exports: any; - require: Require; - id: string; - filename: string; - loaded: boolean; - /** @deprecated since v14.6.0 Please use `require.main` and `module.children` instead. */ - parent: Module | null | undefined; - children: Module[]; - /** - * @since v11.14.0 - * - * The directory name of the module. This is usually the same as the path.dirname() of the module.id. - */ - path: string; - paths: string[]; - } - - interface Dict { - [key: string]: T | undefined; - } - - interface ReadOnlyDict { - readonly [key: string]: T | undefined; - } - } - - interface RequestInit extends _RequestInit {} - - function fetch( - input: string | URL | globalThis.Request, - init?: RequestInit, - ): Promise; - - interface Request extends _Request {} - var Request: typeof globalThis extends { - onmessage: any; - Request: infer T; - } ? T - : typeof import("undici-types").Request; - - interface ResponseInit extends _ResponseInit {} - - interface Response extends _Response {} - var Response: typeof globalThis extends { - onmessage: any; - Response: infer T; - } ? T - : typeof import("undici-types").Response; - - interface FormData extends _FormData {} - var FormData: typeof globalThis extends { - onmessage: any; - FormData: infer T; - } ? T - : typeof import("undici-types").FormData; - - interface Headers extends _Headers {} - var Headers: typeof globalThis extends { - onmessage: any; - Headers: infer T; - } ? T - : typeof import("undici-types").Headers; - - interface File extends _File {} - var File: typeof globalThis extends { - onmessage: any; - File: infer T; - } ? T - : typeof import("node:buffer").File; -} diff --git a/node_modules/@types/node/ts4.8/globals.global.d.ts b/node_modules/@types/node/ts4.8/globals.global.d.ts deleted file mode 100644 index ef1198c05024940c44e3c1a6429c26091fe2a94f..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/globals.global.d.ts +++ /dev/null @@ -1 +0,0 @@ -declare var global: typeof globalThis; diff --git a/node_modules/@types/node/ts4.8/http.d.ts b/node_modules/@types/node/ts4.8/http.d.ts deleted file mode 100644 index 710fe59423d657b7b7ea26113a8c41d97ec47134..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/http.d.ts +++ /dev/null @@ -1,1887 +0,0 @@ -/** - * To use the HTTP server and client one must `require('node:http')`. - * - * The HTTP interfaces in Node.js are designed to support many features - * of the protocol which have been traditionally difficult to use. - * In particular, large, possibly chunk-encoded, messages. The interface is - * careful to never buffer entire requests or responses, so the - * user is able to stream data. - * - * HTTP message headers are represented by an object like this: - * - * ```json - * { "content-length": "123", - * "content-type": "text/plain", - * "connection": "keep-alive", - * "host": "example.com", - * "accept": "*" } - * ``` - * - * Keys are lowercased. Values are not modified. - * - * In order to support the full spectrum of possible HTTP applications, the Node.js - * HTTP API is very low-level. It deals with stream handling and message - * parsing only. It parses a message into headers and body but it does not - * parse the actual headers or the body. - * - * See `message.headers` for details on how duplicate headers are handled. - * - * The raw headers as they were received are retained in the `rawHeaders`property, which is an array of `[key, value, key2, value2, ...]`. For - * example, the previous message header object might have a `rawHeaders`list like the following: - * - * ```js - * [ 'ConTent-Length', '123456', - * 'content-LENGTH', '123', - * 'content-type', 'text/plain', - * 'CONNECTION', 'keep-alive', - * 'Host', 'example.com', - * 'accepT', '*' ] - * ``` - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/http.js) - */ -declare module "http" { - import * as stream from "node:stream"; - import { URL } from "node:url"; - import { LookupOptions } from "node:dns"; - import { EventEmitter } from "node:events"; - import { LookupFunction, Server as NetServer, Socket, TcpSocketConnectOpts } from "node:net"; - // incoming headers will never contain number - interface IncomingHttpHeaders extends NodeJS.Dict { - accept?: string | undefined; - "accept-language"?: string | undefined; - "accept-patch"?: string | undefined; - "accept-ranges"?: string | undefined; - "access-control-allow-credentials"?: string | undefined; - "access-control-allow-headers"?: string | undefined; - "access-control-allow-methods"?: string | undefined; - "access-control-allow-origin"?: string | undefined; - "access-control-expose-headers"?: string | undefined; - "access-control-max-age"?: string | undefined; - "access-control-request-headers"?: string | undefined; - "access-control-request-method"?: string | undefined; - age?: string | undefined; - allow?: string | undefined; - "alt-svc"?: string | undefined; - authorization?: string | undefined; - "cache-control"?: string | undefined; - connection?: string | undefined; - "content-disposition"?: string | undefined; - "content-encoding"?: string | undefined; - "content-language"?: string | undefined; - "content-length"?: string | undefined; - "content-location"?: string | undefined; - "content-range"?: string | undefined; - "content-type"?: string | undefined; - cookie?: string | undefined; - date?: string | undefined; - etag?: string | undefined; - expect?: string | undefined; - expires?: string | undefined; - forwarded?: string | undefined; - from?: string | undefined; - host?: string | undefined; - "if-match"?: string | undefined; - "if-modified-since"?: string | undefined; - "if-none-match"?: string | undefined; - "if-unmodified-since"?: string | undefined; - "last-modified"?: string | undefined; - location?: string | undefined; - origin?: string | undefined; - pragma?: string | undefined; - "proxy-authenticate"?: string | undefined; - "proxy-authorization"?: string | undefined; - "public-key-pins"?: string | undefined; - range?: string | undefined; - referer?: string | undefined; - "retry-after"?: string | undefined; - "sec-websocket-accept"?: string | undefined; - "sec-websocket-extensions"?: string | undefined; - "sec-websocket-key"?: string | undefined; - "sec-websocket-protocol"?: string | undefined; - "sec-websocket-version"?: string | undefined; - "set-cookie"?: string[] | undefined; - "strict-transport-security"?: string | undefined; - tk?: string | undefined; - trailer?: string | undefined; - "transfer-encoding"?: string | undefined; - upgrade?: string | undefined; - "user-agent"?: string | undefined; - vary?: string | undefined; - via?: string | undefined; - warning?: string | undefined; - "www-authenticate"?: string | undefined; - } - // outgoing headers allows numbers (as they are converted internally to strings) - type OutgoingHttpHeader = number | string | string[]; - interface OutgoingHttpHeaders extends NodeJS.Dict { - accept?: string | string[] | undefined; - "accept-charset"?: string | string[] | undefined; - "accept-encoding"?: string | string[] | undefined; - "accept-language"?: string | string[] | undefined; - "accept-ranges"?: string | undefined; - "access-control-allow-credentials"?: string | undefined; - "access-control-allow-headers"?: string | undefined; - "access-control-allow-methods"?: string | undefined; - "access-control-allow-origin"?: string | undefined; - "access-control-expose-headers"?: string | undefined; - "access-control-max-age"?: string | undefined; - "access-control-request-headers"?: string | undefined; - "access-control-request-method"?: string | undefined; - age?: string | undefined; - allow?: string | undefined; - authorization?: string | undefined; - "cache-control"?: string | undefined; - "cdn-cache-control"?: string | undefined; - connection?: string | string[] | undefined; - "content-disposition"?: string | undefined; - "content-encoding"?: string | undefined; - "content-language"?: string | undefined; - "content-length"?: string | number | undefined; - "content-location"?: string | undefined; - "content-range"?: string | undefined; - "content-security-policy"?: string | undefined; - "content-security-policy-report-only"?: string | undefined; - cookie?: string | string[] | undefined; - dav?: string | string[] | undefined; - dnt?: string | undefined; - date?: string | undefined; - etag?: string | undefined; - expect?: string | undefined; - expires?: string | undefined; - forwarded?: string | undefined; - from?: string | undefined; - host?: string | undefined; - "if-match"?: string | undefined; - "if-modified-since"?: string | undefined; - "if-none-match"?: string | undefined; - "if-range"?: string | undefined; - "if-unmodified-since"?: string | undefined; - "last-modified"?: string | undefined; - link?: string | string[] | undefined; - location?: string | undefined; - "max-forwards"?: string | undefined; - origin?: string | undefined; - prgama?: string | string[] | undefined; - "proxy-authenticate"?: string | string[] | undefined; - "proxy-authorization"?: string | undefined; - "public-key-pins"?: string | undefined; - "public-key-pins-report-only"?: string | undefined; - range?: string | undefined; - referer?: string | undefined; - "referrer-policy"?: string | undefined; - refresh?: string | undefined; - "retry-after"?: string | undefined; - "sec-websocket-accept"?: string | undefined; - "sec-websocket-extensions"?: string | string[] | undefined; - "sec-websocket-key"?: string | undefined; - "sec-websocket-protocol"?: string | string[] | undefined; - "sec-websocket-version"?: string | undefined; - server?: string | undefined; - "set-cookie"?: string | string[] | undefined; - "strict-transport-security"?: string | undefined; - te?: string | undefined; - trailer?: string | undefined; - "transfer-encoding"?: string | undefined; - "user-agent"?: string | undefined; - upgrade?: string | undefined; - "upgrade-insecure-requests"?: string | undefined; - vary?: string | undefined; - via?: string | string[] | undefined; - warning?: string | undefined; - "www-authenticate"?: string | string[] | undefined; - "x-content-type-options"?: string | undefined; - "x-dns-prefetch-control"?: string | undefined; - "x-frame-options"?: string | undefined; - "x-xss-protection"?: string | undefined; - } - interface ClientRequestArgs { - _defaultAgent?: Agent | undefined; - agent?: Agent | boolean | undefined; - auth?: string | null | undefined; - // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L278 - createConnection?: - | ((options: ClientRequestArgs, oncreate: (err: Error, socket: Socket) => void) => Socket) - | undefined; - defaultPort?: number | string | undefined; - family?: number | undefined; - headers?: OutgoingHttpHeaders | undefined; - hints?: LookupOptions["hints"]; - host?: string | null | undefined; - hostname?: string | null | undefined; - insecureHTTPParser?: boolean | undefined; - localAddress?: string | undefined; - localPort?: number | undefined; - lookup?: LookupFunction | undefined; - /** - * @default 16384 - */ - maxHeaderSize?: number | undefined; - method?: string | undefined; - path?: string | null | undefined; - port?: number | string | null | undefined; - protocol?: string | null | undefined; - setHost?: boolean | undefined; - signal?: AbortSignal | undefined; - socketPath?: string | undefined; - timeout?: number | undefined; - uniqueHeaders?: Array | undefined; - joinDuplicateHeaders?: boolean; - } - interface ServerOptions< - Request extends typeof IncomingMessage = typeof IncomingMessage, - Response extends typeof ServerResponse = typeof ServerResponse, - > { - /** - * Specifies the `IncomingMessage` class to be used. Useful for extending the original `IncomingMessage`. - */ - IncomingMessage?: Request | undefined; - /** - * Specifies the `ServerResponse` class to be used. Useful for extending the original `ServerResponse`. - */ - ServerResponse?: Response | undefined; - /** - * Sets the timeout value in milliseconds for receiving the entire request from the client. - * @see Server.requestTimeout for more information. - * @default 300000 - * @since v18.0.0 - */ - requestTimeout?: number | undefined; - /** - * It joins the field line values of multiple headers in a request with `, ` instead of discarding the duplicates. - * @default false - * @since v18.14.0 - */ - joinDuplicateHeaders?: boolean; - /** - * The number of milliseconds of inactivity a server needs to wait for additional incoming data, - * after it has finished writing the last response, before a socket will be destroyed. - * @see Server.keepAliveTimeout for more information. - * @default 5000 - * @since v18.0.0 - */ - keepAliveTimeout?: number | undefined; - /** - * Sets the interval value in milliseconds to check for request and headers timeout in incomplete requests. - * @default 30000 - */ - connectionsCheckingInterval?: number | undefined; - /** - * Optionally overrides all `socket`s' `readableHighWaterMark` and `writableHighWaterMark`. - * This affects `highWaterMark` property of both `IncomingMessage` and `ServerResponse`. - * Default: @see stream.getDefaultHighWaterMark(). - * @since v20.1.0 - */ - highWaterMark?: number | undefined; - /** - * Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. - * Using the insecure parser should be avoided. - * See --insecure-http-parser for more information. - * @default false - */ - insecureHTTPParser?: boolean | undefined; - /** - * Optionally overrides the value of - * `--max-http-header-size` for requests received by this server, i.e. - * the maximum length of request headers in bytes. - * @default 16384 - * @since v13.3.0 - */ - maxHeaderSize?: number | undefined; - /** - * If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. - * @default true - * @since v16.5.0 - */ - noDelay?: boolean | undefined; - /** - * If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, - * similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`. - * @default false - * @since v16.5.0 - */ - keepAlive?: boolean | undefined; - /** - * If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. - * @default 0 - * @since v16.5.0 - */ - keepAliveInitialDelay?: number | undefined; - /** - * A list of response headers that should be sent only once. - * If the header's value is an array, the items will be joined using `; `. - */ - uniqueHeaders?: Array | undefined; - } - type RequestListener< - Request extends typeof IncomingMessage = typeof IncomingMessage, - Response extends typeof ServerResponse = typeof ServerResponse, - > = (req: InstanceType, res: InstanceType & { req: InstanceType }) => void; - /** - * @since v0.1.17 - */ - class Server< - Request extends typeof IncomingMessage = typeof IncomingMessage, - Response extends typeof ServerResponse = typeof ServerResponse, - > extends NetServer { - constructor(requestListener?: RequestListener); - constructor(options: ServerOptions, requestListener?: RequestListener); - /** - * Sets the timeout value for sockets, and emits a `'timeout'` event on - * the Server object, passing the socket as an argument, if a timeout - * occurs. - * - * If there is a `'timeout'` event listener on the Server object, then it - * will be called with the timed-out socket as an argument. - * - * By default, the Server does not timeout sockets. However, if a callback - * is assigned to the Server's `'timeout'` event, timeouts must be handled - * explicitly. - * @since v0.9.12 - * @param [msecs=0 (no timeout)] - */ - setTimeout(msecs?: number, callback?: () => void): this; - setTimeout(callback: () => void): this; - /** - * Limits maximum incoming headers count. If set to 0, no limit will be applied. - * @since v0.7.0 - */ - maxHeadersCount: number | null; - /** - * The maximum number of requests socket can handle - * before closing keep alive connection. - * - * A value of `0` will disable the limit. - * - * When the limit is reached it will set the `Connection` header value to `close`, - * but will not actually close the connection, subsequent requests sent - * after the limit is reached will get `503 Service Unavailable` as a response. - * @since v16.10.0 - */ - maxRequestsPerSocket: number | null; - /** - * The number of milliseconds of inactivity before a socket is presumed - * to have timed out. - * - * A value of `0` will disable the timeout behavior on incoming connections. - * - * The socket timeout logic is set up on connection, so changing this - * value only affects new connections to the server, not any existing connections. - * @since v0.9.12 - */ - timeout: number; - /** - * Limit the amount of time the parser will wait to receive the complete HTTP - * headers. - * - * If the timeout expires, the server responds with status 408 without - * forwarding the request to the request listener and then closes the connection. - * - * It must be set to a non-zero value (e.g. 120 seconds) to protect against - * potential Denial-of-Service attacks in case the server is deployed without a - * reverse proxy in front. - * @since v11.3.0, v10.14.0 - */ - headersTimeout: number; - /** - * The number of milliseconds of inactivity a server needs to wait for additional - * incoming data, after it has finished writing the last response, before a socket - * will be destroyed. If the server receives new data before the keep-alive - * timeout has fired, it will reset the regular inactivity timeout, i.e.,`server.timeout`. - * - * A value of `0` will disable the keep-alive timeout behavior on incoming - * connections. - * A value of `0` makes the http server behave similarly to Node.js versions prior - * to 8.0.0, which did not have a keep-alive timeout. - * - * The socket timeout logic is set up on connection, so changing this value only - * affects new connections to the server, not any existing connections. - * @since v8.0.0 - */ - keepAliveTimeout: number; - /** - * Sets the timeout value in milliseconds for receiving the entire request from - * the client. - * - * If the timeout expires, the server responds with status 408 without - * forwarding the request to the request listener and then closes the connection. - * - * It must be set to a non-zero value (e.g. 120 seconds) to protect against - * potential Denial-of-Service attacks in case the server is deployed without a - * reverse proxy in front. - * @since v14.11.0 - */ - requestTimeout: number; - /** - * Closes all connections connected to this server. - * @since v18.2.0 - */ - closeAllConnections(): void; - /** - * Closes all connections connected to this server which are not sending a request - * or waiting for a response. - * @since v18.2.0 - */ - closeIdleConnections(): void; - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "connection", listener: (socket: Socket) => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "listening", listener: () => void): this; - addListener(event: "checkContinue", listener: RequestListener): this; - addListener(event: "checkExpectation", listener: RequestListener): this; - addListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; - addListener( - event: "connect", - listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, - ): this; - addListener(event: "dropRequest", listener: (req: InstanceType, socket: stream.Duplex) => void): this; - addListener(event: "request", listener: RequestListener): this; - addListener( - event: "upgrade", - listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, - ): this; - emit(event: string, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "connection", socket: Socket): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "listening"): boolean; - emit( - event: "checkContinue", - req: InstanceType, - res: InstanceType & { req: InstanceType }, - ): boolean; - emit( - event: "checkExpectation", - req: InstanceType, - res: InstanceType & { req: InstanceType }, - ): boolean; - emit(event: "clientError", err: Error, socket: stream.Duplex): boolean; - emit(event: "connect", req: InstanceType, socket: stream.Duplex, head: Buffer): boolean; - emit(event: "dropRequest", req: InstanceType, socket: stream.Duplex): boolean; - emit( - event: "request", - req: InstanceType, - res: InstanceType & { req: InstanceType }, - ): boolean; - emit(event: "upgrade", req: InstanceType, socket: stream.Duplex, head: Buffer): boolean; - on(event: string, listener: (...args: any[]) => void): this; - on(event: "close", listener: () => void): this; - on(event: "connection", listener: (socket: Socket) => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "listening", listener: () => void): this; - on(event: "checkContinue", listener: RequestListener): this; - on(event: "checkExpectation", listener: RequestListener): this; - on(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; - on(event: "connect", listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; - on(event: "dropRequest", listener: (req: InstanceType, socket: stream.Duplex) => void): this; - on(event: "request", listener: RequestListener): this; - on(event: "upgrade", listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; - once(event: string, listener: (...args: any[]) => void): this; - once(event: "close", listener: () => void): this; - once(event: "connection", listener: (socket: Socket) => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "listening", listener: () => void): this; - once(event: "checkContinue", listener: RequestListener): this; - once(event: "checkExpectation", listener: RequestListener): this; - once(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; - once( - event: "connect", - listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, - ): this; - once(event: "dropRequest", listener: (req: InstanceType, socket: stream.Duplex) => void): this; - once(event: "request", listener: RequestListener): this; - once( - event: "upgrade", - listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, - ): this; - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "connection", listener: (socket: Socket) => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "listening", listener: () => void): this; - prependListener(event: "checkContinue", listener: RequestListener): this; - prependListener(event: "checkExpectation", listener: RequestListener): this; - prependListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; - prependListener( - event: "connect", - listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, - ): this; - prependListener( - event: "dropRequest", - listener: (req: InstanceType, socket: stream.Duplex) => void, - ): this; - prependListener(event: "request", listener: RequestListener): this; - prependListener( - event: "upgrade", - listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, - ): this; - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "listening", listener: () => void): this; - prependOnceListener(event: "checkContinue", listener: RequestListener): this; - prependOnceListener(event: "checkExpectation", listener: RequestListener): this; - prependOnceListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; - prependOnceListener( - event: "connect", - listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, - ): this; - prependOnceListener( - event: "dropRequest", - listener: (req: InstanceType, socket: stream.Duplex) => void, - ): this; - prependOnceListener(event: "request", listener: RequestListener): this; - prependOnceListener( - event: "upgrade", - listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, - ): this; - } - /** - * This class serves as the parent class of {@link ClientRequest} and {@link ServerResponse}. It is an abstract outgoing message from - * the perspective of the participants of an HTTP transaction. - * @since v0.1.17 - */ - class OutgoingMessage extends stream.Writable { - readonly req: Request; - chunkedEncoding: boolean; - shouldKeepAlive: boolean; - useChunkedEncodingByDefault: boolean; - sendDate: boolean; - /** - * @deprecated Use `writableEnded` instead. - */ - finished: boolean; - /** - * Read-only. `true` if the headers were sent, otherwise `false`. - * @since v0.9.3 - */ - readonly headersSent: boolean; - /** - * Alias of `outgoingMessage.socket`. - * @since v0.3.0 - * @deprecated Since v15.12.0,v14.17.1 - Use `socket` instead. - */ - readonly connection: Socket | null; - /** - * Reference to the underlying socket. Usually, users will not want to access - * this property. - * - * After calling `outgoingMessage.end()`, this property will be nulled. - * @since v0.3.0 - */ - readonly socket: Socket | null; - constructor(); - /** - * Once a socket is associated with the message and is connected,`socket.setTimeout()` will be called with `msecs` as the first parameter. - * @since v0.9.12 - * @param callback Optional function to be called when a timeout occurs. Same as binding to the `timeout` event. - */ - setTimeout(msecs: number, callback?: () => void): this; - /** - * Sets a single header value. If the header already exists in the to-be-sent - * headers, its value will be replaced. Use an array of strings to send multiple - * headers with the same name. - * @since v0.4.0 - * @param name Header name - * @param value Header value - */ - setHeader(name: string, value: number | string | readonly string[]): this; - /** - * Append a single header value for the header object. - * - * If the value is an array, this is equivalent of calling this method multiple - * times. - * - * If there were no previous value for the header, this is equivalent of calling `outgoingMessage.setHeader(name, value)`. - * - * Depending of the value of `options.uniqueHeaders` when the client request or the - * server were created, this will end up in the header being sent multiple times or - * a single time with values joined using `; `. - * @since v18.3.0, v16.17.0 - * @param name Header name - * @param value Header value - */ - appendHeader(name: string, value: string | readonly string[]): this; - /** - * Gets the value of the HTTP header with the given name. If that header is not - * set, the returned value will be `undefined`. - * @since v0.4.0 - * @param name Name of header - */ - getHeader(name: string): number | string | string[] | undefined; - /** - * Returns a shallow copy of the current outgoing headers. Since a shallow - * copy is used, array values may be mutated without additional calls to - * various header-related HTTP module methods. The keys of the returned - * object are the header names and the values are the respective header - * values. All header names are lowercase. - * - * The object returned by the `outgoingMessage.getHeaders()` method does - * not prototypically inherit from the JavaScript `Object`. This means that - * typical `Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`, - * and others are not defined and will not work. - * - * ```js - * outgoingMessage.setHeader('Foo', 'bar'); - * outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); - * - * const headers = outgoingMessage.getHeaders(); - * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } - * ``` - * @since v7.7.0 - */ - getHeaders(): OutgoingHttpHeaders; - /** - * Returns an array containing the unique names of the current outgoing headers. - * All names are lowercase. - * @since v7.7.0 - */ - getHeaderNames(): string[]; - /** - * Returns `true` if the header identified by `name` is currently set in the - * outgoing headers. The header name is case-insensitive. - * - * ```js - * const hasContentType = outgoingMessage.hasHeader('content-type'); - * ``` - * @since v7.7.0 - */ - hasHeader(name: string): boolean; - /** - * Removes a header that is queued for implicit sending. - * - * ```js - * outgoingMessage.removeHeader('Content-Encoding'); - * ``` - * @since v0.4.0 - * @param name Header name - */ - removeHeader(name: string): void; - /** - * Adds HTTP trailers (headers but at the end of the message) to the message. - * - * Trailers will **only** be emitted if the message is chunked encoded. If not, - * the trailers will be silently discarded. - * - * HTTP requires the `Trailer` header to be sent to emit trailers, - * with a list of header field names in its value, e.g. - * - * ```js - * message.writeHead(200, { 'Content-Type': 'text/plain', - * 'Trailer': 'Content-MD5' }); - * message.write(fileData); - * message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' }); - * message.end(); - * ``` - * - * Attempting to set a header field name or value that contains invalid characters - * will result in a `TypeError` being thrown. - * @since v0.3.0 - */ - addTrailers(headers: OutgoingHttpHeaders | ReadonlyArray<[string, string]>): void; - /** - * Flushes the message headers. - * - * For efficiency reason, Node.js normally buffers the message headers - * until `outgoingMessage.end()` is called or the first chunk of message data - * is written. It then tries to pack the headers and data into a single TCP - * packet. - * - * It is usually desired (it saves a TCP round-trip), but not when the first - * data is not sent until possibly much later. `outgoingMessage.flushHeaders()`bypasses the optimization and kickstarts the message. - * @since v1.6.0 - */ - flushHeaders(): void; - } - /** - * This object is created internally by an HTTP server, not by the user. It is - * passed as the second parameter to the `'request'` event. - * @since v0.1.17 - */ - class ServerResponse extends OutgoingMessage { - /** - * When using implicit headers (not calling `response.writeHead()` explicitly), - * this property controls the status code that will be sent to the client when - * the headers get flushed. - * - * ```js - * response.statusCode = 404; - * ``` - * - * After response header was sent to the client, this property indicates the - * status code which was sent out. - * @since v0.4.0 - */ - statusCode: number; - /** - * When using implicit headers (not calling `response.writeHead()` explicitly), - * this property controls the status message that will be sent to the client when - * the headers get flushed. If this is left as `undefined` then the standard - * message for the status code will be used. - * - * ```js - * response.statusMessage = 'Not found'; - * ``` - * - * After response header was sent to the client, this property indicates the - * status message which was sent out. - * @since v0.11.8 - */ - statusMessage: string; - /** - * If set to `true`, Node.js will check whether the `Content-Length`header value and the size of the body, in bytes, are equal. - * Mismatching the `Content-Length` header value will result - * in an `Error` being thrown, identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`. - * @since v18.10.0, v16.18.0 - */ - strictContentLength: boolean; - constructor(req: Request); - assignSocket(socket: Socket): void; - detachSocket(socket: Socket): void; - /** - * Sends an HTTP/1.1 100 Continue message to the client, indicating that - * the request body should be sent. See the `'checkContinue'` event on`Server`. - * @since v0.3.0 - */ - writeContinue(callback?: () => void): void; - /** - * Sends an HTTP/1.1 103 Early Hints message to the client with a Link header, - * indicating that the user agent can preload/preconnect the linked resources. - * The `hints` is an object containing the values of headers to be sent with - * early hints message. The optional `callback` argument will be called when - * the response message has been written. - * - * **Example** - * - * ```js - * const earlyHintsLink = '; rel=preload; as=style'; - * response.writeEarlyHints({ - * 'link': earlyHintsLink, - * }); - * - * const earlyHintsLinks = [ - * '; rel=preload; as=style', - * '; rel=preload; as=script', - * ]; - * response.writeEarlyHints({ - * 'link': earlyHintsLinks, - * 'x-trace-id': 'id for diagnostics', - * }); - * - * const earlyHintsCallback = () => console.log('early hints message sent'); - * response.writeEarlyHints({ - * 'link': earlyHintsLinks, - * }, earlyHintsCallback); - * ``` - * @since v18.11.0 - * @param hints An object containing the values of headers - * @param callback Will be called when the response message has been written - */ - writeEarlyHints(hints: Record, callback?: () => void): void; - /** - * Sends a response header to the request. The status code is a 3-digit HTTP - * status code, like `404`. The last argument, `headers`, are the response headers. - * Optionally one can give a human-readable `statusMessage` as the second - * argument. - * - * `headers` may be an `Array` where the keys and values are in the same list. - * It is _not_ a list of tuples. So, the even-numbered offsets are key values, - * and the odd-numbered offsets are the associated values. The array is in the same - * format as `request.rawHeaders`. - * - * Returns a reference to the `ServerResponse`, so that calls can be chained. - * - * ```js - * const body = 'hello world'; - * response - * .writeHead(200, { - * 'Content-Length': Buffer.byteLength(body), - * 'Content-Type': 'text/plain', - * }) - * .end(body); - * ``` - * - * This method must only be called once on a message and it must - * be called before `response.end()` is called. - * - * If `response.write()` or `response.end()` are called before calling - * this, the implicit/mutable headers will be calculated and call this function. - * - * When headers have been set with `response.setHeader()`, they will be merged - * with any headers passed to `response.writeHead()`, with the headers passed - * to `response.writeHead()` given precedence. - * - * If this method is called and `response.setHeader()` has not been called, - * it will directly write the supplied header values onto the network channel - * without caching internally, and the `response.getHeader()` on the header - * will not yield the expected result. If progressive population of headers is - * desired with potential future retrieval and modification, use `response.setHeader()` instead. - * - * ```js - * // Returns content-type = text/plain - * const server = http.createServer((req, res) => { - * res.setHeader('Content-Type', 'text/html'); - * res.setHeader('X-Foo', 'bar'); - * res.writeHead(200, { 'Content-Type': 'text/plain' }); - * res.end('ok'); - * }); - * ``` - * - * `Content-Length` is read in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. Node.js - * will check whether `Content-Length` and the length of the body which has - * been transmitted are equal or not. - * - * Attempting to set a header field name or value that contains invalid characters - * will result in a \[`Error`\]\[\] being thrown. - * @since v0.1.30 - */ - writeHead( - statusCode: number, - statusMessage?: string, - headers?: OutgoingHttpHeaders | OutgoingHttpHeader[], - ): this; - writeHead(statusCode: number, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this; - /** - * Sends a HTTP/1.1 102 Processing message to the client, indicating that - * the request body should be sent. - * @since v10.0.0 - */ - writeProcessing(): void; - } - interface InformationEvent { - statusCode: number; - statusMessage: string; - httpVersion: string; - httpVersionMajor: number; - httpVersionMinor: number; - headers: IncomingHttpHeaders; - rawHeaders: string[]; - } - /** - * This object is created internally and returned from {@link request}. It - * represents an _in-progress_ request whose header has already been queued. The - * header is still mutable using the `setHeader(name, value)`,`getHeader(name)`, `removeHeader(name)` API. The actual header will - * be sent along with the first data chunk or when calling `request.end()`. - * - * To get the response, add a listener for `'response'` to the request object.`'response'` will be emitted from the request object when the response - * headers have been received. The `'response'` event is executed with one - * argument which is an instance of {@link IncomingMessage}. - * - * During the `'response'` event, one can add listeners to the - * response object; particularly to listen for the `'data'` event. - * - * If no `'response'` handler is added, then the response will be - * entirely discarded. However, if a `'response'` event handler is added, - * then the data from the response object **must** be consumed, either by - * calling `response.read()` whenever there is a `'readable'` event, or - * by adding a `'data'` handler, or by calling the `.resume()` method. - * Until the data is consumed, the `'end'` event will not fire. Also, until - * the data is read it will consume memory that can eventually lead to a - * 'process out of memory' error. - * - * For backward compatibility, `res` will only emit `'error'` if there is an`'error'` listener registered. - * - * Set `Content-Length` header to limit the response body size. - * If `response.strictContentLength` is set to `true`, mismatching the`Content-Length` header value will result in an `Error` being thrown, - * identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`. - * - * `Content-Length` value should be in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. - * @since v0.1.17 - */ - class ClientRequest extends OutgoingMessage { - /** - * The `request.aborted` property will be `true` if the request has - * been aborted. - * @since v0.11.14 - * @deprecated Since v17.0.0,v16.12.0 - Check `destroyed` instead. - */ - aborted: boolean; - /** - * The request host. - * @since v14.5.0, v12.19.0 - */ - host: string; - /** - * The request protocol. - * @since v14.5.0, v12.19.0 - */ - protocol: string; - /** - * When sending request through a keep-alive enabled agent, the underlying socket - * might be reused. But if server closes connection at unfortunate time, client - * may run into a 'ECONNRESET' error. - * - * ```js - * import http from 'node:http'; - * - * // Server has a 5 seconds keep-alive timeout by default - * http - * .createServer((req, res) => { - * res.write('hello\n'); - * res.end(); - * }) - * .listen(3000); - * - * setInterval(() => { - * // Adapting a keep-alive agent - * http.get('http://localhost:3000', { agent }, (res) => { - * res.on('data', (data) => { - * // Do nothing - * }); - * }); - * }, 5000); // Sending request on 5s interval so it's easy to hit idle timeout - * ``` - * - * By marking a request whether it reused socket or not, we can do - * automatic error retry base on it. - * - * ```js - * import http from 'node:http'; - * const agent = new http.Agent({ keepAlive: true }); - * - * function retriableRequest() { - * const req = http - * .get('http://localhost:3000', { agent }, (res) => { - * // ... - * }) - * .on('error', (err) => { - * // Check if retry is needed - * if (req.reusedSocket && err.code === 'ECONNRESET') { - * retriableRequest(); - * } - * }); - * } - * - * retriableRequest(); - * ``` - * @since v13.0.0, v12.16.0 - */ - reusedSocket: boolean; - /** - * Limits maximum response headers count. If set to 0, no limit will be applied. - */ - maxHeadersCount: number; - constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); - /** - * The request method. - * @since v0.1.97 - */ - method: string; - /** - * The request path. - * @since v0.4.0 - */ - path: string; - /** - * Marks the request as aborting. Calling this will cause remaining data - * in the response to be dropped and the socket to be destroyed. - * @since v0.3.8 - * @deprecated Since v14.1.0,v13.14.0 - Use `destroy` instead. - */ - abort(): void; - onSocket(socket: Socket): void; - /** - * Once a socket is assigned to this request and is connected `socket.setTimeout()` will be called. - * @since v0.5.9 - * @param timeout Milliseconds before a request times out. - * @param callback Optional function to be called when a timeout occurs. Same as binding to the `'timeout'` event. - */ - setTimeout(timeout: number, callback?: () => void): this; - /** - * Once a socket is assigned to this request and is connected `socket.setNoDelay()` will be called. - * @since v0.5.9 - */ - setNoDelay(noDelay?: boolean): void; - /** - * Once a socket is assigned to this request and is connected `socket.setKeepAlive()` will be called. - * @since v0.5.9 - */ - setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; - /** - * Returns an array containing the unique names of the current outgoing raw - * headers. Header names are returned with their exact casing being set. - * - * ```js - * request.setHeader('Foo', 'bar'); - * request.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); - * - * const headerNames = request.getRawHeaderNames(); - * // headerNames === ['Foo', 'Set-Cookie'] - * ``` - * @since v15.13.0, v14.17.0 - */ - getRawHeaderNames(): string[]; - /** - * @deprecated - */ - addListener(event: "abort", listener: () => void): this; - addListener( - event: "connect", - listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, - ): this; - addListener(event: "continue", listener: () => void): this; - addListener(event: "information", listener: (info: InformationEvent) => void): this; - addListener(event: "response", listener: (response: IncomingMessage) => void): this; - addListener(event: "socket", listener: (socket: Socket) => void): this; - addListener(event: "timeout", listener: () => void): this; - addListener( - event: "upgrade", - listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, - ): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "drain", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "finish", listener: () => void): this; - addListener(event: "pipe", listener: (src: stream.Readable) => void): this; - addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - /** - * @deprecated - */ - on(event: "abort", listener: () => void): this; - on(event: "connect", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; - on(event: "continue", listener: () => void): this; - on(event: "information", listener: (info: InformationEvent) => void): this; - on(event: "response", listener: (response: IncomingMessage) => void): this; - on(event: "socket", listener: (socket: Socket) => void): this; - on(event: "timeout", listener: () => void): this; - on(event: "upgrade", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; - on(event: "close", listener: () => void): this; - on(event: "drain", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "finish", listener: () => void): this; - on(event: "pipe", listener: (src: stream.Readable) => void): this; - on(event: "unpipe", listener: (src: stream.Readable) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - /** - * @deprecated - */ - once(event: "abort", listener: () => void): this; - once(event: "connect", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; - once(event: "continue", listener: () => void): this; - once(event: "information", listener: (info: InformationEvent) => void): this; - once(event: "response", listener: (response: IncomingMessage) => void): this; - once(event: "socket", listener: (socket: Socket) => void): this; - once(event: "timeout", listener: () => void): this; - once(event: "upgrade", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; - once(event: "close", listener: () => void): this; - once(event: "drain", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "finish", listener: () => void): this; - once(event: "pipe", listener: (src: stream.Readable) => void): this; - once(event: "unpipe", listener: (src: stream.Readable) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - /** - * @deprecated - */ - prependListener(event: "abort", listener: () => void): this; - prependListener( - event: "connect", - listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, - ): this; - prependListener(event: "continue", listener: () => void): this; - prependListener(event: "information", listener: (info: InformationEvent) => void): this; - prependListener(event: "response", listener: (response: IncomingMessage) => void): this; - prependListener(event: "socket", listener: (socket: Socket) => void): this; - prependListener(event: "timeout", listener: () => void): this; - prependListener( - event: "upgrade", - listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, - ): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "drain", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "finish", listener: () => void): this; - prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; - prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - /** - * @deprecated - */ - prependOnceListener(event: "abort", listener: () => void): this; - prependOnceListener( - event: "connect", - listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, - ): this; - prependOnceListener(event: "continue", listener: () => void): this; - prependOnceListener(event: "information", listener: (info: InformationEvent) => void): this; - prependOnceListener(event: "response", listener: (response: IncomingMessage) => void): this; - prependOnceListener(event: "socket", listener: (socket: Socket) => void): this; - prependOnceListener(event: "timeout", listener: () => void): this; - prependOnceListener( - event: "upgrade", - listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, - ): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "drain", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "finish", listener: () => void): this; - prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; - prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - } - /** - * An `IncomingMessage` object is created by {@link Server} or {@link ClientRequest} and passed as the first argument to the `'request'` and `'response'` event respectively. It may be used to - * access response - * status, headers, and data. - * - * Different from its `socket` value which is a subclass of `stream.Duplex`, the`IncomingMessage` itself extends `stream.Readable` and is created separately to - * parse and emit the incoming HTTP headers and payload, as the underlying socket - * may be reused multiple times in case of keep-alive. - * @since v0.1.17 - */ - class IncomingMessage extends stream.Readable { - constructor(socket: Socket); - /** - * The `message.aborted` property will be `true` if the request has - * been aborted. - * @since v10.1.0 - * @deprecated Since v17.0.0,v16.12.0 - Check `message.destroyed` from stream.Readable. - */ - aborted: boolean; - /** - * In case of server request, the HTTP version sent by the client. In the case of - * client response, the HTTP version of the connected-to server. - * Probably either `'1.1'` or `'1.0'`. - * - * Also `message.httpVersionMajor` is the first integer and`message.httpVersionMinor` is the second. - * @since v0.1.1 - */ - httpVersion: string; - httpVersionMajor: number; - httpVersionMinor: number; - /** - * The `message.complete` property will be `true` if a complete HTTP message has - * been received and successfully parsed. - * - * This property is particularly useful as a means of determining if a client or - * server fully transmitted a message before a connection was terminated: - * - * ```js - * const req = http.request({ - * host: '127.0.0.1', - * port: 8080, - * method: 'POST', - * }, (res) => { - * res.resume(); - * res.on('end', () => { - * if (!res.complete) - * console.error( - * 'The connection was terminated while the message was still being sent'); - * }); - * }); - * ``` - * @since v0.3.0 - */ - complete: boolean; - /** - * Alias for `message.socket`. - * @since v0.1.90 - * @deprecated Since v16.0.0 - Use `socket`. - */ - connection: Socket; - /** - * The `net.Socket` object associated with the connection. - * - * With HTTPS support, use `request.socket.getPeerCertificate()` to obtain the - * client's authentication details. - * - * This property is guaranteed to be an instance of the `net.Socket` class, - * a subclass of `stream.Duplex`, unless the user specified a socket - * type other than `net.Socket` or internally nulled. - * @since v0.3.0 - */ - socket: Socket; - /** - * The request/response headers object. - * - * Key-value pairs of header names and values. Header names are lower-cased. - * - * ```js - * // Prints something like: - * // - * // { 'user-agent': 'curl/7.22.0', - * // host: '127.0.0.1:8000', - * // accept: '*' } - * console.log(request.headers); - * ``` - * - * Duplicates in raw headers are handled in the following ways, depending on the - * header name: - * - * * Duplicates of `age`, `authorization`, `content-length`, `content-type`,`etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`,`last-modified`, `location`, - * `max-forwards`, `proxy-authorization`, `referer`,`retry-after`, `server`, or `user-agent` are discarded. - * To allow duplicate values of the headers listed above to be joined, - * use the option `joinDuplicateHeaders` in {@link request} and {@link createServer}. See RFC 9110 Section 5.3 for more - * information. - * * `set-cookie` is always an array. Duplicates are added to the array. - * * For duplicate `cookie` headers, the values are joined together with `; `. - * * For all other headers, the values are joined together with `, `. - * @since v0.1.5 - */ - headers: IncomingHttpHeaders; - /** - * Similar to `message.headers`, but there is no join logic and the values are - * always arrays of strings, even for headers received just once. - * - * ```js - * // Prints something like: - * // - * // { 'user-agent': ['curl/7.22.0'], - * // host: ['127.0.0.1:8000'], - * // accept: ['*'] } - * console.log(request.headersDistinct); - * ``` - * @since v18.3.0, v16.17.0 - */ - headersDistinct: NodeJS.Dict; - /** - * The raw request/response headers list exactly as they were received. - * - * The keys and values are in the same list. It is _not_ a - * list of tuples. So, the even-numbered offsets are key values, and the - * odd-numbered offsets are the associated values. - * - * Header names are not lowercased, and duplicates are not merged. - * - * ```js - * // Prints something like: - * // - * // [ 'user-agent', - * // 'this is invalid because there can be only one', - * // 'User-Agent', - * // 'curl/7.22.0', - * // 'Host', - * // '127.0.0.1:8000', - * // 'ACCEPT', - * // '*' ] - * console.log(request.rawHeaders); - * ``` - * @since v0.11.6 - */ - rawHeaders: string[]; - /** - * The request/response trailers object. Only populated at the `'end'` event. - * @since v0.3.0 - */ - trailers: NodeJS.Dict; - /** - * Similar to `message.trailers`, but there is no join logic and the values are - * always arrays of strings, even for headers received just once. - * Only populated at the `'end'` event. - * @since v18.3.0, v16.17.0 - */ - trailersDistinct: NodeJS.Dict; - /** - * The raw request/response trailer keys and values exactly as they were - * received. Only populated at the `'end'` event. - * @since v0.11.6 - */ - rawTrailers: string[]; - /** - * Calls `message.socket.setTimeout(msecs, callback)`. - * @since v0.5.9 - */ - setTimeout(msecs: number, callback?: () => void): this; - /** - * **Only valid for request obtained from {@link Server}.** - * - * The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`. - * @since v0.1.1 - */ - method?: string | undefined; - /** - * **Only valid for request obtained from {@link Server}.** - * - * Request URL string. This contains only the URL that is present in the actual - * HTTP request. Take the following request: - * - * ```http - * GET /status?name=ryan HTTP/1.1 - * Accept: text/plain - * ``` - * - * To parse the URL into its parts: - * - * ```js - * new URL(request.url, `http://${request.headers.host}`); - * ``` - * - * When `request.url` is `'/status?name=ryan'` and `request.headers.host` is`'localhost:3000'`: - * - * ```console - * $ node - * > new URL(request.url, `http://${request.headers.host}`) - * URL { - * href: 'http://localhost:3000/status?name=ryan', - * origin: 'http://localhost:3000', - * protocol: 'http:', - * username: '', - * password: '', - * host: 'localhost:3000', - * hostname: 'localhost', - * port: '3000', - * pathname: '/status', - * search: '?name=ryan', - * searchParams: URLSearchParams { 'name' => 'ryan' }, - * hash: '' - * } - * ``` - * @since v0.1.90 - */ - url?: string | undefined; - /** - * **Only valid for response obtained from {@link ClientRequest}.** - * - * The 3-digit HTTP response status code. E.G. `404`. - * @since v0.1.1 - */ - statusCode?: number | undefined; - /** - * **Only valid for response obtained from {@link ClientRequest}.** - * - * The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`. - * @since v0.11.10 - */ - statusMessage?: string | undefined; - /** - * Calls `destroy()` on the socket that received the `IncomingMessage`. If `error`is provided, an `'error'` event is emitted on the socket and `error` is passed - * as an argument to any listeners on the event. - * @since v0.3.0 - */ - destroy(error?: Error): this; - } - interface AgentOptions extends Partial { - /** - * Keep sockets around in a pool to be used by other requests in the future. Default = false - */ - keepAlive?: boolean | undefined; - /** - * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. - * Only relevant if keepAlive is set to true. - */ - keepAliveMsecs?: number | undefined; - /** - * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity - */ - maxSockets?: number | undefined; - /** - * Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. Default: Infinity. - */ - maxTotalSockets?: number | undefined; - /** - * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. - */ - maxFreeSockets?: number | undefined; - /** - * Socket timeout in milliseconds. This will set the timeout after the socket is connected. - */ - timeout?: number | undefined; - /** - * Scheduling strategy to apply when picking the next free socket to use. - * @default `lifo` - */ - scheduling?: "fifo" | "lifo" | undefined; - } - /** - * An `Agent` is responsible for managing connection persistence - * and reuse for HTTP clients. It maintains a queue of pending requests - * for a given host and port, reusing a single socket connection for each - * until the queue is empty, at which time the socket is either destroyed - * or put into a pool where it is kept to be used again for requests to the - * same host and port. Whether it is destroyed or pooled depends on the`keepAlive` `option`. - * - * Pooled connections have TCP Keep-Alive enabled for them, but servers may - * still close idle connections, in which case they will be removed from the - * pool and a new connection will be made when a new HTTP request is made for - * that host and port. Servers may also refuse to allow multiple requests - * over the same connection, in which case the connection will have to be - * remade for every request and cannot be pooled. The `Agent` will still make - * the requests to that server, but each one will occur over a new connection. - * - * When a connection is closed by the client or the server, it is removed - * from the pool. Any unused sockets in the pool will be unrefed so as not - * to keep the Node.js process running when there are no outstanding requests. - * (see `socket.unref()`). - * - * It is good practice, to `destroy()` an `Agent` instance when it is no - * longer in use, because unused sockets consume OS resources. - * - * Sockets are removed from an agent when the socket emits either - * a `'close'` event or an `'agentRemove'` event. When intending to keep one - * HTTP request open for a long time without keeping it in the agent, something - * like the following may be done: - * - * ```js - * http.get(options, (res) => { - * // Do stuff - * }).on('socket', (socket) => { - * socket.emit('agentRemove'); - * }); - * ``` - * - * An agent may also be used for an individual request. By providing`{agent: false}` as an option to the `http.get()` or `http.request()`functions, a one-time use `Agent` with default options - * will be used - * for the client connection. - * - * `agent:false`: - * - * ```js - * http.get({ - * hostname: 'localhost', - * port: 80, - * path: '/', - * agent: false, // Create a new agent just for this one request - * }, (res) => { - * // Do stuff with response - * }); - * ``` - * @since v0.3.4 - */ - class Agent extends EventEmitter { - /** - * By default set to 256. For agents with `keepAlive` enabled, this - * sets the maximum number of sockets that will be left open in the free - * state. - * @since v0.11.7 - */ - maxFreeSockets: number; - /** - * By default set to `Infinity`. Determines how many concurrent sockets the agent - * can have open per origin. Origin is the returned value of `agent.getName()`. - * @since v0.3.6 - */ - maxSockets: number; - /** - * By default set to `Infinity`. Determines how many concurrent sockets the agent - * can have open. Unlike `maxSockets`, this parameter applies across all origins. - * @since v14.5.0, v12.19.0 - */ - maxTotalSockets: number; - /** - * An object which contains arrays of sockets currently awaiting use by - * the agent when `keepAlive` is enabled. Do not modify. - * - * Sockets in the `freeSockets` list will be automatically destroyed and - * removed from the array on `'timeout'`. - * @since v0.11.4 - */ - readonly freeSockets: NodeJS.ReadOnlyDict; - /** - * An object which contains arrays of sockets currently in use by the - * agent. Do not modify. - * @since v0.3.6 - */ - readonly sockets: NodeJS.ReadOnlyDict; - /** - * An object which contains queues of requests that have not yet been assigned to - * sockets. Do not modify. - * @since v0.5.9 - */ - readonly requests: NodeJS.ReadOnlyDict; - constructor(opts?: AgentOptions); - /** - * Destroy any sockets that are currently in use by the agent. - * - * It is usually not necessary to do this. However, if using an - * agent with `keepAlive` enabled, then it is best to explicitly shut down - * the agent when it is no longer needed. Otherwise, - * sockets might stay open for quite a long time before the server - * terminates them. - * @since v0.11.4 - */ - destroy(): void; - } - const METHODS: string[]; - const STATUS_CODES: { - [errorCode: number]: string | undefined; - [errorCode: string]: string | undefined; - }; - /** - * Returns a new instance of {@link Server}. - * - * The `requestListener` is a function which is automatically - * added to the `'request'` event. - * - * ```js - * import http from 'node:http'; - * - * // Create a local server to receive data from - * const server = http.createServer((req, res) => { - * res.writeHead(200, { 'Content-Type': 'application/json' }); - * res.end(JSON.stringify({ - * data: 'Hello World!', - * })); - * }); - * - * server.listen(8000); - * ``` - * - * ```js - * import http from 'node:http'; - * - * // Create a local server to receive data from - * const server = http.createServer(); - * - * // Listen to the request event - * server.on('request', (request, res) => { - * res.writeHead(200, { 'Content-Type': 'application/json' }); - * res.end(JSON.stringify({ - * data: 'Hello World!', - * })); - * }); - * - * server.listen(8000); - * ``` - * @since v0.1.13 - */ - function createServer< - Request extends typeof IncomingMessage = typeof IncomingMessage, - Response extends typeof ServerResponse = typeof ServerResponse, - >(requestListener?: RequestListener): Server; - function createServer< - Request extends typeof IncomingMessage = typeof IncomingMessage, - Response extends typeof ServerResponse = typeof ServerResponse, - >( - options: ServerOptions, - requestListener?: RequestListener, - ): Server; - // although RequestOptions are passed as ClientRequestArgs to ClientRequest directly, - // create interface RequestOptions would make the naming more clear to developers - interface RequestOptions extends ClientRequestArgs {} - /** - * `options` in `socket.connect()` are also supported. - * - * Node.js maintains several connections per server to make HTTP requests. - * This function allows one to transparently issue requests. - * - * `url` can be a string or a `URL` object. If `url` is a - * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. - * - * If both `url` and `options` are specified, the objects are merged, with the`options` properties taking precedence. - * - * The optional `callback` parameter will be added as a one-time listener for - * the `'response'` event. - * - * `http.request()` returns an instance of the {@link ClientRequest} class. The `ClientRequest` instance is a writable stream. If one needs to - * upload a file with a POST request, then write to the `ClientRequest` object. - * - * ```js - * import http from 'node:http'; - * import { Buffer } from 'node:buffer'; - * - * const postData = JSON.stringify({ - * 'msg': 'Hello World!', - * }); - * - * const options = { - * hostname: 'www.google.com', - * port: 80, - * path: '/upload', - * method: 'POST', - * headers: { - * 'Content-Type': 'application/json', - * 'Content-Length': Buffer.byteLength(postData), - * }, - * }; - * - * const req = http.request(options, (res) => { - * console.log(`STATUS: ${res.statusCode}`); - * console.log(`HEADERS: ${JSON.stringify(res.headers)}`); - * res.setEncoding('utf8'); - * res.on('data', (chunk) => { - * console.log(`BODY: ${chunk}`); - * }); - * res.on('end', () => { - * console.log('No more data in response.'); - * }); - * }); - * - * req.on('error', (e) => { - * console.error(`problem with request: ${e.message}`); - * }); - * - * // Write data to request body - * req.write(postData); - * req.end(); - * ``` - * - * In the example `req.end()` was called. With `http.request()` one - * must always call `req.end()` to signify the end of the request - - * even if there is no data being written to the request body. - * - * If any error is encountered during the request (be that with DNS resolution, - * TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted - * on the returned request object. As with all `'error'` events, if no listeners - * are registered the error will be thrown. - * - * There are a few special headers that should be noted. - * - * * Sending a 'Connection: keep-alive' will notify Node.js that the connection to - * the server should be persisted until the next request. - * * Sending a 'Content-Length' header will disable the default chunked encoding. - * * Sending an 'Expect' header will immediately send the request headers. - * Usually, when sending 'Expect: 100-continue', both a timeout and a listener - * for the `'continue'` event should be set. See RFC 2616 Section 8.2.3 for more - * information. - * * Sending an Authorization header will override using the `auth` option - * to compute basic authentication. - * - * Example using a `URL` as `options`: - * - * ```js - * const options = new URL('http://abc:xyz@example.com'); - * - * const req = http.request(options, (res) => { - * // ... - * }); - * ``` - * - * In a successful request, the following events will be emitted in the following - * order: - * - * * `'socket'` - * * `'response'` - * * `'data'` any number of times, on the `res` object - * (`'data'` will not be emitted at all if the response body is empty, for - * instance, in most redirects) - * * `'end'` on the `res` object - * * `'close'` - * - * In the case of a connection error, the following events will be emitted: - * - * * `'socket'` - * * `'error'` - * * `'close'` - * - * In the case of a premature connection close before the response is received, - * the following events will be emitted in the following order: - * - * * `'socket'` - * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` - * * `'close'` - * - * In the case of a premature connection close after the response is received, - * the following events will be emitted in the following order: - * - * * `'socket'` - * * `'response'` - * * `'data'` any number of times, on the `res` object - * * (connection closed here) - * * `'aborted'` on the `res` object - * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'` - * * `'close'` - * * `'close'` on the `res` object - * - * If `req.destroy()` is called before a socket is assigned, the following - * events will be emitted in the following order: - * - * * (`req.destroy()` called here) - * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'`, or the error with which `req.destroy()` was called - * * `'close'` - * - * If `req.destroy()` is called before the connection succeeds, the following - * events will be emitted in the following order: - * - * * `'socket'` - * * (`req.destroy()` called here) - * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'`, or the error with which `req.destroy()` was called - * * `'close'` - * - * If `req.destroy()` is called after the response is received, the following - * events will be emitted in the following order: - * - * * `'socket'` - * * `'response'` - * * `'data'` any number of times, on the `res` object - * * (`req.destroy()` called here) - * * `'aborted'` on the `res` object - * * `'error'` on the `res` object with an error with message `'Error: aborted'`and code `'ECONNRESET'`, or the error with which `req.destroy()` was called - * * `'close'` - * * `'close'` on the `res` object - * - * If `req.abort()` is called before a socket is assigned, the following - * events will be emitted in the following order: - * - * * (`req.abort()` called here) - * * `'abort'` - * * `'close'` - * - * If `req.abort()` is called before the connection succeeds, the following - * events will be emitted in the following order: - * - * * `'socket'` - * * (`req.abort()` called here) - * * `'abort'` - * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` - * * `'close'` - * - * If `req.abort()` is called after the response is received, the following - * events will be emitted in the following order: - * - * * `'socket'` - * * `'response'` - * * `'data'` any number of times, on the `res` object - * * (`req.abort()` called here) - * * `'abort'` - * * `'aborted'` on the `res` object - * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. - * * `'close'` - * * `'close'` on the `res` object - * - * Setting the `timeout` option or using the `setTimeout()` function will - * not abort the request or do anything besides add a `'timeout'` event. - * - * Passing an `AbortSignal` and then calling `abort()` on the corresponding`AbortController` will behave the same way as calling `.destroy()` on the - * request. Specifically, the `'error'` event will be emitted with an error with - * the message `'AbortError: The operation was aborted'`, the code `'ABORT_ERR'`and the `cause`, if one was provided. - * @since v0.3.6 - */ - function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; - function request( - url: string | URL, - options: RequestOptions, - callback?: (res: IncomingMessage) => void, - ): ClientRequest; - /** - * Since most requests are GET requests without bodies, Node.js provides this - * convenience method. The only difference between this method and {@link request} is that it sets the method to GET by default and calls `req.end()`automatically. The callback must take care to - * consume the response - * data for reasons stated in {@link ClientRequest} section. - * - * The `callback` is invoked with a single argument that is an instance of {@link IncomingMessage}. - * - * JSON fetching example: - * - * ```js - * http.get('http://localhost:8000/', (res) => { - * const { statusCode } = res; - * const contentType = res.headers['content-type']; - * - * let error; - * // Any 2xx status code signals a successful response but - * // here we're only checking for 200. - * if (statusCode !== 200) { - * error = new Error('Request Failed.\n' + - * `Status Code: ${statusCode}`); - * } else if (!/^application\/json/.test(contentType)) { - * error = new Error('Invalid content-type.\n' + - * `Expected application/json but received ${contentType}`); - * } - * if (error) { - * console.error(error.message); - * // Consume response data to free up memory - * res.resume(); - * return; - * } - * - * res.setEncoding('utf8'); - * let rawData = ''; - * res.on('data', (chunk) => { rawData += chunk; }); - * res.on('end', () => { - * try { - * const parsedData = JSON.parse(rawData); - * console.log(parsedData); - * } catch (e) { - * console.error(e.message); - * } - * }); - * }).on('error', (e) => { - * console.error(`Got error: ${e.message}`); - * }); - * - * // Create a local server to receive data from - * const server = http.createServer((req, res) => { - * res.writeHead(200, { 'Content-Type': 'application/json' }); - * res.end(JSON.stringify({ - * data: 'Hello World!', - * })); - * }); - * - * server.listen(8000); - * ``` - * @since v0.3.6 - * @param options Accepts the same `options` as {@link request}, with the method set to GET by default. - */ - function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; - function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; - /** - * Performs the low-level validations on the provided `name` that are done when`res.setHeader(name, value)` is called. - * - * Passing illegal value as `name` will result in a `TypeError` being thrown, - * identified by `code: 'ERR_INVALID_HTTP_TOKEN'`. - * - * It is not necessary to use this method before passing headers to an HTTP request - * or response. The HTTP module will automatically validate such headers. - * - * Example: - * - * ```js - * import { validateHeaderName } from 'node:http'; - * - * try { - * validateHeaderName(''); - * } catch (err) { - * console.error(err instanceof TypeError); // --> true - * console.error(err.code); // --> 'ERR_INVALID_HTTP_TOKEN' - * console.error(err.message); // --> 'Header name must be a valid HTTP token [""]' - * } - * ``` - * @since v14.3.0 - * @param [label='Header name'] Label for error message. - */ - function validateHeaderName(name: string): void; - /** - * Performs the low-level validations on the provided `value` that are done when`res.setHeader(name, value)` is called. - * - * Passing illegal value as `value` will result in a `TypeError` being thrown. - * - * * Undefined value error is identified by `code: 'ERR_HTTP_INVALID_HEADER_VALUE'`. - * * Invalid value character error is identified by `code: 'ERR_INVALID_CHAR'`. - * - * It is not necessary to use this method before passing headers to an HTTP request - * or response. The HTTP module will automatically validate such headers. - * - * Examples: - * - * ```js - * import { validateHeaderValue } from 'node:http'; - * - * try { - * validateHeaderValue('x-my-header', undefined); - * } catch (err) { - * console.error(err instanceof TypeError); // --> true - * console.error(err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'); // --> true - * console.error(err.message); // --> 'Invalid value "undefined" for header "x-my-header"' - * } - * - * try { - * validateHeaderValue('x-my-header', 'oʊmɪɡə'); - * } catch (err) { - * console.error(err instanceof TypeError); // --> true - * console.error(err.code === 'ERR_INVALID_CHAR'); // --> true - * console.error(err.message); // --> 'Invalid character in header content ["x-my-header"]' - * } - * ``` - * @since v14.3.0 - * @param name Header name - * @param value Header value - */ - function validateHeaderValue(name: string, value: string): void; - /** - * Set the maximum number of idle HTTP parsers. - * @since v18.8.0, v16.18.0 - * @param [max=1000] - */ - function setMaxIdleHTTPParsers(max: number): void; - let globalAgent: Agent; - /** - * Read-only property specifying the maximum allowed size of HTTP headers in bytes. - * Defaults to 16KB. Configurable using the `--max-http-header-size` CLI option. - */ - const maxHeaderSize: number; -} -declare module "node:http" { - export * from "http"; -} diff --git a/node_modules/@types/node/ts4.8/http2.d.ts b/node_modules/@types/node/ts4.8/http2.d.ts deleted file mode 100644 index c3b3e8ec4fe80a643325e3b37c287bcdb4c9e2f5..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/http2.d.ts +++ /dev/null @@ -1,2382 +0,0 @@ -/** - * The `node:http2` module provides an implementation of the [HTTP/2](https://tools.ietf.org/html/rfc7540) protocol. - * It can be accessed using: - * - * ```js - * const http2 = require('node:http2'); - * ``` - * @since v8.4.0 - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/http2.js) - */ -declare module "http2" { - import EventEmitter = require("node:events"); - import * as fs from "node:fs"; - import * as net from "node:net"; - import * as stream from "node:stream"; - import * as tls from "node:tls"; - import * as url from "node:url"; - import { - IncomingHttpHeaders as Http1IncomingHttpHeaders, - IncomingMessage, - OutgoingHttpHeaders, - ServerResponse, - } from "node:http"; - export { OutgoingHttpHeaders } from "node:http"; - export interface IncomingHttpStatusHeader { - ":status"?: number | undefined; - } - export interface IncomingHttpHeaders extends Http1IncomingHttpHeaders { - ":path"?: string | undefined; - ":method"?: string | undefined; - ":authority"?: string | undefined; - ":scheme"?: string | undefined; - } - // Http2Stream - export interface StreamPriorityOptions { - exclusive?: boolean | undefined; - parent?: number | undefined; - weight?: number | undefined; - silent?: boolean | undefined; - } - export interface StreamState { - localWindowSize?: number | undefined; - state?: number | undefined; - localClose?: number | undefined; - remoteClose?: number | undefined; - sumDependencyWeight?: number | undefined; - weight?: number | undefined; - } - export interface ServerStreamResponseOptions { - endStream?: boolean | undefined; - waitForTrailers?: boolean | undefined; - } - export interface StatOptions { - offset: number; - length: number; - } - export interface ServerStreamFileResponseOptions { - // eslint-disable-next-line @typescript-eslint/no-invalid-void-type - statCheck?(stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions): void | boolean; - waitForTrailers?: boolean | undefined; - offset?: number | undefined; - length?: number | undefined; - } - export interface ServerStreamFileResponseOptionsWithError extends ServerStreamFileResponseOptions { - onError?(err: NodeJS.ErrnoException): void; - } - export interface Http2Stream extends stream.Duplex { - /** - * Set to `true` if the `Http2Stream` instance was aborted abnormally. When set, - * the `'aborted'` event will have been emitted. - * @since v8.4.0 - */ - readonly aborted: boolean; - /** - * This property shows the number of characters currently buffered to be written. - * See `net.Socket.bufferSize` for details. - * @since v11.2.0, v10.16.0 - */ - readonly bufferSize: number; - /** - * Set to `true` if the `Http2Stream` instance has been closed. - * @since v9.4.0 - */ - readonly closed: boolean; - /** - * Set to `true` if the `Http2Stream` instance has been destroyed and is no longer - * usable. - * @since v8.4.0 - */ - readonly destroyed: boolean; - /** - * Set to `true` if the `END_STREAM` flag was set in the request or response - * HEADERS frame received, indicating that no additional data should be received - * and the readable side of the `Http2Stream` will be closed. - * @since v10.11.0 - */ - readonly endAfterHeaders: boolean; - /** - * The numeric stream identifier of this `Http2Stream` instance. Set to `undefined`if the stream identifier has not yet been assigned. - * @since v8.4.0 - */ - readonly id?: number | undefined; - /** - * Set to `true` if the `Http2Stream` instance has not yet been assigned a - * numeric stream identifier. - * @since v9.4.0 - */ - readonly pending: boolean; - /** - * Set to the `RST_STREAM` `error code` reported when the `Http2Stream` is - * destroyed after either receiving an `RST_STREAM` frame from the connected peer, - * calling `http2stream.close()`, or `http2stream.destroy()`. Will be`undefined` if the `Http2Stream` has not been closed. - * @since v8.4.0 - */ - readonly rstCode: number; - /** - * An object containing the outbound headers sent for this `Http2Stream`. - * @since v9.5.0 - */ - readonly sentHeaders: OutgoingHttpHeaders; - /** - * An array of objects containing the outbound informational (additional) headers - * sent for this `Http2Stream`. - * @since v9.5.0 - */ - readonly sentInfoHeaders?: OutgoingHttpHeaders[] | undefined; - /** - * An object containing the outbound trailers sent for this `HttpStream`. - * @since v9.5.0 - */ - readonly sentTrailers?: OutgoingHttpHeaders | undefined; - /** - * A reference to the `Http2Session` instance that owns this `Http2Stream`. The - * value will be `undefined` after the `Http2Stream` instance is destroyed. - * @since v8.4.0 - */ - readonly session: Http2Session | undefined; - /** - * Provides miscellaneous information about the current state of the`Http2Stream`. - * - * A current state of this `Http2Stream`. - * @since v8.4.0 - */ - readonly state: StreamState; - /** - * Closes the `Http2Stream` instance by sending an `RST_STREAM` frame to the - * connected HTTP/2 peer. - * @since v8.4.0 - * @param [code=http2.constants.NGHTTP2_NO_ERROR] Unsigned 32-bit integer identifying the error code. - * @param callback An optional function registered to listen for the `'close'` event. - */ - close(code?: number, callback?: () => void): void; - /** - * Updates the priority for this `Http2Stream` instance. - * @since v8.4.0 - */ - priority(options: StreamPriorityOptions): void; - /** - * ```js - * const http2 = require('node:http2'); - * const client = http2.connect('http://example.org:8000'); - * const { NGHTTP2_CANCEL } = http2.constants; - * const req = client.request({ ':path': '/' }); - * - * // Cancel the stream if there's no activity after 5 seconds - * req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL)); - * ``` - * @since v8.4.0 - */ - setTimeout(msecs: number, callback?: () => void): void; - /** - * Sends a trailing `HEADERS` frame to the connected HTTP/2 peer. This method - * will cause the `Http2Stream` to be immediately closed and must only be - * called after the `'wantTrailers'` event has been emitted. When sending a - * request or sending a response, the `options.waitForTrailers` option must be set - * in order to keep the `Http2Stream` open after the final `DATA` frame so that - * trailers can be sent. - * - * ```js - * const http2 = require('node:http2'); - * const server = http2.createServer(); - * server.on('stream', (stream) => { - * stream.respond(undefined, { waitForTrailers: true }); - * stream.on('wantTrailers', () => { - * stream.sendTrailers({ xyz: 'abc' }); - * }); - * stream.end('Hello World'); - * }); - * ``` - * - * The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header - * fields (e.g. `':method'`, `':path'`, etc). - * @since v10.0.0 - */ - sendTrailers(headers: OutgoingHttpHeaders): void; - addListener(event: "aborted", listener: () => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "data", listener: (chunk: Buffer | string) => void): this; - addListener(event: "drain", listener: () => void): this; - addListener(event: "end", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "finish", listener: () => void): this; - addListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; - addListener(event: "pipe", listener: (src: stream.Readable) => void): this; - addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - addListener(event: "streamClosed", listener: (code: number) => void): this; - addListener(event: "timeout", listener: () => void): this; - addListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; - addListener(event: "wantTrailers", listener: () => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - emit(event: "aborted"): boolean; - emit(event: "close"): boolean; - emit(event: "data", chunk: Buffer | string): boolean; - emit(event: "drain"): boolean; - emit(event: "end"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "finish"): boolean; - emit(event: "frameError", frameType: number, errorCode: number): boolean; - emit(event: "pipe", src: stream.Readable): boolean; - emit(event: "unpipe", src: stream.Readable): boolean; - emit(event: "streamClosed", code: number): boolean; - emit(event: "timeout"): boolean; - emit(event: "trailers", trailers: IncomingHttpHeaders, flags: number): boolean; - emit(event: "wantTrailers"): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - on(event: "aborted", listener: () => void): this; - on(event: "close", listener: () => void): this; - on(event: "data", listener: (chunk: Buffer | string) => void): this; - on(event: "drain", listener: () => void): this; - on(event: "end", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "finish", listener: () => void): this; - on(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; - on(event: "pipe", listener: (src: stream.Readable) => void): this; - on(event: "unpipe", listener: (src: stream.Readable) => void): this; - on(event: "streamClosed", listener: (code: number) => void): this; - on(event: "timeout", listener: () => void): this; - on(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; - on(event: "wantTrailers", listener: () => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: "aborted", listener: () => void): this; - once(event: "close", listener: () => void): this; - once(event: "data", listener: (chunk: Buffer | string) => void): this; - once(event: "drain", listener: () => void): this; - once(event: "end", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "finish", listener: () => void): this; - once(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; - once(event: "pipe", listener: (src: stream.Readable) => void): this; - once(event: "unpipe", listener: (src: stream.Readable) => void): this; - once(event: "streamClosed", listener: (code: number) => void): this; - once(event: "timeout", listener: () => void): this; - once(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; - once(event: "wantTrailers", listener: () => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener(event: "aborted", listener: () => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; - prependListener(event: "drain", listener: () => void): this; - prependListener(event: "end", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "finish", listener: () => void): this; - prependListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; - prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; - prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - prependListener(event: "streamClosed", listener: (code: number) => void): this; - prependListener(event: "timeout", listener: () => void): this; - prependListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; - prependListener(event: "wantTrailers", listener: () => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener(event: "aborted", listener: () => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; - prependOnceListener(event: "drain", listener: () => void): this; - prependOnceListener(event: "end", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "finish", listener: () => void): this; - prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; - prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; - prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - prependOnceListener(event: "streamClosed", listener: (code: number) => void): this; - prependOnceListener(event: "timeout", listener: () => void): this; - prependOnceListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; - prependOnceListener(event: "wantTrailers", listener: () => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - } - export interface ClientHttp2Stream extends Http2Stream { - addListener(event: "continue", listener: () => {}): this; - addListener( - event: "headers", - listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, - ): this; - addListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; - addListener( - event: "response", - listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, - ): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - emit(event: "continue"): boolean; - emit(event: "headers", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; - emit(event: "push", headers: IncomingHttpHeaders, flags: number): boolean; - emit(event: "response", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - on(event: "continue", listener: () => {}): this; - on( - event: "headers", - listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, - ): this; - on(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; - on( - event: "response", - listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, - ): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: "continue", listener: () => {}): this; - once( - event: "headers", - listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, - ): this; - once(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; - once( - event: "response", - listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, - ): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener(event: "continue", listener: () => {}): this; - prependListener( - event: "headers", - listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, - ): this; - prependListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; - prependListener( - event: "response", - listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, - ): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener(event: "continue", listener: () => {}): this; - prependOnceListener( - event: "headers", - listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, - ): this; - prependOnceListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; - prependOnceListener( - event: "response", - listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, - ): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - } - export interface ServerHttp2Stream extends Http2Stream { - /** - * True if headers were sent, false otherwise (read-only). - * @since v8.4.0 - */ - readonly headersSent: boolean; - /** - * Read-only property mapped to the `SETTINGS_ENABLE_PUSH` flag of the remote - * client's most recent `SETTINGS` frame. Will be `true` if the remote peer - * accepts push streams, `false` otherwise. Settings are the same for every`Http2Stream` in the same `Http2Session`. - * @since v8.4.0 - */ - readonly pushAllowed: boolean; - /** - * Sends an additional informational `HEADERS` frame to the connected HTTP/2 peer. - * @since v8.4.0 - */ - additionalHeaders(headers: OutgoingHttpHeaders): void; - /** - * Initiates a push stream. The callback is invoked with the new `Http2Stream`instance created for the push stream passed as the second argument, or an`Error` passed as the first argument. - * - * ```js - * const http2 = require('node:http2'); - * const server = http2.createServer(); - * server.on('stream', (stream) => { - * stream.respond({ ':status': 200 }); - * stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => { - * if (err) throw err; - * pushStream.respond({ ':status': 200 }); - * pushStream.end('some pushed data'); - * }); - * stream.end('some data'); - * }); - * ``` - * - * Setting the weight of a push stream is not allowed in the `HEADERS` frame. Pass - * a `weight` value to `http2stream.priority` with the `silent` option set to`true` to enable server-side bandwidth balancing between concurrent streams. - * - * Calling `http2stream.pushStream()` from within a pushed stream is not permitted - * and will throw an error. - * @since v8.4.0 - * @param callback Callback that is called once the push stream has been initiated. - */ - pushStream( - headers: OutgoingHttpHeaders, - callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void, - ): void; - pushStream( - headers: OutgoingHttpHeaders, - options?: StreamPriorityOptions, - callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void, - ): void; - /** - * ```js - * const http2 = require('node:http2'); - * const server = http2.createServer(); - * server.on('stream', (stream) => { - * stream.respond({ ':status': 200 }); - * stream.end('some data'); - * }); - * ``` - * - * Initiates a response. When the `options.waitForTrailers` option is set, the`'wantTrailers'` event will be emitted immediately after queuing the last chunk - * of payload data to be sent. The `http2stream.sendTrailers()` method can then be - * used to sent trailing header fields to the peer. - * - * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically - * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. - * - * ```js - * const http2 = require('node:http2'); - * const server = http2.createServer(); - * server.on('stream', (stream) => { - * stream.respond({ ':status': 200 }, { waitForTrailers: true }); - * stream.on('wantTrailers', () => { - * stream.sendTrailers({ ABC: 'some value to send' }); - * }); - * stream.end('some data'); - * }); - * ``` - * @since v8.4.0 - */ - respond(headers?: OutgoingHttpHeaders, options?: ServerStreamResponseOptions): void; - /** - * Initiates a response whose data is read from the given file descriptor. No - * validation is performed on the given file descriptor. If an error occurs while - * attempting to read data using the file descriptor, the `Http2Stream` will be - * closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR` code. - * - * When used, the `Http2Stream` object's `Duplex` interface will be closed - * automatically. - * - * ```js - * const http2 = require('node:http2'); - * const fs = require('node:fs'); - * - * const server = http2.createServer(); - * server.on('stream', (stream) => { - * const fd = fs.openSync('/some/file', 'r'); - * - * const stat = fs.fstatSync(fd); - * const headers = { - * 'content-length': stat.size, - * 'last-modified': stat.mtime.toUTCString(), - * 'content-type': 'text/plain; charset=utf-8', - * }; - * stream.respondWithFD(fd, headers); - * stream.on('close', () => fs.closeSync(fd)); - * }); - * ``` - * - * The optional `options.statCheck` function may be specified to give user code - * an opportunity to set additional content headers based on the `fs.Stat` details - * of the given fd. If the `statCheck` function is provided, the`http2stream.respondWithFD()` method will perform an `fs.fstat()` call to - * collect details on the provided file descriptor. - * - * The `offset` and `length` options may be used to limit the response to a - * specific range subset. This can be used, for instance, to support HTTP Range - * requests. - * - * The file descriptor or `FileHandle` is not closed when the stream is closed, - * so it will need to be closed manually once it is no longer needed. - * Using the same file descriptor concurrently for multiple streams - * is not supported and may result in data loss. Re-using a file descriptor - * after a stream has finished is supported. - * - * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event - * will be emitted immediately after queuing the last chunk of payload data to be - * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing - * header fields to the peer. - * - * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically - * close when the final `DATA` frame is transmitted. User code _must_ call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. - * - * ```js - * const http2 = require('node:http2'); - * const fs = require('node:fs'); - * - * const server = http2.createServer(); - * server.on('stream', (stream) => { - * const fd = fs.openSync('/some/file', 'r'); - * - * const stat = fs.fstatSync(fd); - * const headers = { - * 'content-length': stat.size, - * 'last-modified': stat.mtime.toUTCString(), - * 'content-type': 'text/plain; charset=utf-8', - * }; - * stream.respondWithFD(fd, headers, { waitForTrailers: true }); - * stream.on('wantTrailers', () => { - * stream.sendTrailers({ ABC: 'some value to send' }); - * }); - * - * stream.on('close', () => fs.closeSync(fd)); - * }); - * ``` - * @since v8.4.0 - * @param fd A readable file descriptor. - */ - respondWithFD( - fd: number | fs.promises.FileHandle, - headers?: OutgoingHttpHeaders, - options?: ServerStreamFileResponseOptions, - ): void; - /** - * Sends a regular file as the response. The `path` must specify a regular file - * or an `'error'` event will be emitted on the `Http2Stream` object. - * - * When used, the `Http2Stream` object's `Duplex` interface will be closed - * automatically. - * - * The optional `options.statCheck` function may be specified to give user code - * an opportunity to set additional content headers based on the `fs.Stat` details - * of the given file: - * - * If an error occurs while attempting to read the file data, the `Http2Stream`will be closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR`code. If the `onError` callback is - * defined, then it will be called. Otherwise - * the stream will be destroyed. - * - * Example using a file path: - * - * ```js - * const http2 = require('node:http2'); - * const server = http2.createServer(); - * server.on('stream', (stream) => { - * function statCheck(stat, headers) { - * headers['last-modified'] = stat.mtime.toUTCString(); - * } - * - * function onError(err) { - * // stream.respond() can throw if the stream has been destroyed by - * // the other side. - * try { - * if (err.code === 'ENOENT') { - * stream.respond({ ':status': 404 }); - * } else { - * stream.respond({ ':status': 500 }); - * } - * } catch (err) { - * // Perform actual error handling. - * console.error(err); - * } - * stream.end(); - * } - * - * stream.respondWithFile('/some/file', - * { 'content-type': 'text/plain; charset=utf-8' }, - * { statCheck, onError }); - * }); - * ``` - * - * The `options.statCheck` function may also be used to cancel the send operation - * by returning `false`. For instance, a conditional request may check the stat - * results to determine if the file has been modified to return an appropriate`304` response: - * - * ```js - * const http2 = require('node:http2'); - * const server = http2.createServer(); - * server.on('stream', (stream) => { - * function statCheck(stat, headers) { - * // Check the stat here... - * stream.respond({ ':status': 304 }); - * return false; // Cancel the send operation - * } - * stream.respondWithFile('/some/file', - * { 'content-type': 'text/plain; charset=utf-8' }, - * { statCheck }); - * }); - * ``` - * - * The `content-length` header field will be automatically set. - * - * The `offset` and `length` options may be used to limit the response to a - * specific range subset. This can be used, for instance, to support HTTP Range - * requests. - * - * The `options.onError` function may also be used to handle all the errors - * that could happen before the delivery of the file is initiated. The - * default behavior is to destroy the stream. - * - * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event - * will be emitted immediately after queuing the last chunk of payload data to be - * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing - * header fields to the peer. - * - * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically - * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. - * - * ```js - * const http2 = require('node:http2'); - * const server = http2.createServer(); - * server.on('stream', (stream) => { - * stream.respondWithFile('/some/file', - * { 'content-type': 'text/plain; charset=utf-8' }, - * { waitForTrailers: true }); - * stream.on('wantTrailers', () => { - * stream.sendTrailers({ ABC: 'some value to send' }); - * }); - * }); - * ``` - * @since v8.4.0 - */ - respondWithFile( - path: string, - headers?: OutgoingHttpHeaders, - options?: ServerStreamFileResponseOptionsWithError, - ): void; - } - // Http2Session - export interface Settings { - headerTableSize?: number | undefined; - enablePush?: boolean | undefined; - initialWindowSize?: number | undefined; - maxFrameSize?: number | undefined; - maxConcurrentStreams?: number | undefined; - maxHeaderListSize?: number | undefined; - enableConnectProtocol?: boolean | undefined; - } - export interface ClientSessionRequestOptions { - endStream?: boolean | undefined; - exclusive?: boolean | undefined; - parent?: number | undefined; - weight?: number | undefined; - waitForTrailers?: boolean | undefined; - signal?: AbortSignal | undefined; - } - export interface SessionState { - effectiveLocalWindowSize?: number | undefined; - effectiveRecvDataLength?: number | undefined; - nextStreamID?: number | undefined; - localWindowSize?: number | undefined; - lastProcStreamID?: number | undefined; - remoteWindowSize?: number | undefined; - outboundQueueSize?: number | undefined; - deflateDynamicTableSize?: number | undefined; - inflateDynamicTableSize?: number | undefined; - } - export interface Http2Session extends EventEmitter { - /** - * Value will be `undefined` if the `Http2Session` is not yet connected to a - * socket, `h2c` if the `Http2Session` is not connected to a `TLSSocket`, or - * will return the value of the connected `TLSSocket`'s own `alpnProtocol`property. - * @since v9.4.0 - */ - readonly alpnProtocol?: string | undefined; - /** - * Will be `true` if this `Http2Session` instance has been closed, otherwise`false`. - * @since v9.4.0 - */ - readonly closed: boolean; - /** - * Will be `true` if this `Http2Session` instance is still connecting, will be set - * to `false` before emitting `connect` event and/or calling the `http2.connect`callback. - * @since v10.0.0 - */ - readonly connecting: boolean; - /** - * Will be `true` if this `Http2Session` instance has been destroyed and must no - * longer be used, otherwise `false`. - * @since v8.4.0 - */ - readonly destroyed: boolean; - /** - * Value is `undefined` if the `Http2Session` session socket has not yet been - * connected, `true` if the `Http2Session` is connected with a `TLSSocket`, - * and `false` if the `Http2Session` is connected to any other kind of socket - * or stream. - * @since v9.4.0 - */ - readonly encrypted?: boolean | undefined; - /** - * A prototype-less object describing the current local settings of this`Http2Session`. The local settings are local to _this_`Http2Session` instance. - * @since v8.4.0 - */ - readonly localSettings: Settings; - /** - * If the `Http2Session` is connected to a `TLSSocket`, the `originSet` property - * will return an `Array` of origins for which the `Http2Session` may be - * considered authoritative. - * - * The `originSet` property is only available when using a secure TLS connection. - * @since v9.4.0 - */ - readonly originSet?: string[] | undefined; - /** - * Indicates whether the `Http2Session` is currently waiting for acknowledgment of - * a sent `SETTINGS` frame. Will be `true` after calling the`http2session.settings()` method. Will be `false` once all sent `SETTINGS`frames have been acknowledged. - * @since v8.4.0 - */ - readonly pendingSettingsAck: boolean; - /** - * A prototype-less object describing the current remote settings of this`Http2Session`. The remote settings are set by the _connected_ HTTP/2 peer. - * @since v8.4.0 - */ - readonly remoteSettings: Settings; - /** - * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but - * limits available methods to ones safe to use with HTTP/2. - * - * `destroy`, `emit`, `end`, `pause`, `read`, `resume`, and `write` will throw - * an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for more information. - * - * `setTimeout` method will be called on this `Http2Session`. - * - * All other interactions will be routed directly to the socket. - * @since v8.4.0 - */ - readonly socket: net.Socket | tls.TLSSocket; - /** - * Provides miscellaneous information about the current state of the`Http2Session`. - * - * An object describing the current status of this `Http2Session`. - * @since v8.4.0 - */ - readonly state: SessionState; - /** - * The `http2session.type` will be equal to`http2.constants.NGHTTP2_SESSION_SERVER` if this `Http2Session` instance is a - * server, and `http2.constants.NGHTTP2_SESSION_CLIENT` if the instance is a - * client. - * @since v8.4.0 - */ - readonly type: number; - /** - * Gracefully closes the `Http2Session`, allowing any existing streams to - * complete on their own and preventing new `Http2Stream` instances from being - * created. Once closed, `http2session.destroy()`_might_ be called if there - * are no open `Http2Stream` instances. - * - * If specified, the `callback` function is registered as a handler for the`'close'` event. - * @since v9.4.0 - */ - close(callback?: () => void): void; - /** - * Immediately terminates the `Http2Session` and the associated `net.Socket` or`tls.TLSSocket`. - * - * Once destroyed, the `Http2Session` will emit the `'close'` event. If `error`is not undefined, an `'error'` event will be emitted immediately before the`'close'` event. - * - * If there are any remaining open `Http2Streams` associated with the`Http2Session`, those will also be destroyed. - * @since v8.4.0 - * @param error An `Error` object if the `Http2Session` is being destroyed due to an error. - * @param code The HTTP/2 error code to send in the final `GOAWAY` frame. If unspecified, and `error` is not undefined, the default is `INTERNAL_ERROR`, otherwise defaults to `NO_ERROR`. - */ - destroy(error?: Error, code?: number): void; - /** - * Transmits a `GOAWAY` frame to the connected peer _without_ shutting down the`Http2Session`. - * @since v9.4.0 - * @param code An HTTP/2 error code - * @param lastStreamID The numeric ID of the last processed `Http2Stream` - * @param opaqueData A `TypedArray` or `DataView` instance containing additional data to be carried within the `GOAWAY` frame. - */ - goaway(code?: number, lastStreamID?: number, opaqueData?: NodeJS.ArrayBufferView): void; - /** - * Sends a `PING` frame to the connected HTTP/2 peer. A `callback` function must - * be provided. The method will return `true` if the `PING` was sent, `false`otherwise. - * - * The maximum number of outstanding (unacknowledged) pings is determined by the`maxOutstandingPings` configuration option. The default maximum is 10. - * - * If provided, the `payload` must be a `Buffer`, `TypedArray`, or `DataView`containing 8 bytes of data that will be transmitted with the `PING` and - * returned with the ping acknowledgment. - * - * The callback will be invoked with three arguments: an error argument that will - * be `null` if the `PING` was successfully acknowledged, a `duration` argument - * that reports the number of milliseconds elapsed since the ping was sent and the - * acknowledgment was received, and a `Buffer` containing the 8-byte `PING`payload. - * - * ```js - * session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => { - * if (!err) { - * console.log(`Ping acknowledged in ${duration} milliseconds`); - * console.log(`With payload '${payload.toString()}'`); - * } - * }); - * ``` - * - * If the `payload` argument is not specified, the default payload will be the - * 64-bit timestamp (little endian) marking the start of the `PING` duration. - * @since v8.9.3 - * @param payload Optional ping payload. - */ - ping(callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; - ping( - payload: NodeJS.ArrayBufferView, - callback: (err: Error | null, duration: number, payload: Buffer) => void, - ): boolean; - /** - * Calls `ref()` on this `Http2Session`instance's underlying `net.Socket`. - * @since v9.4.0 - */ - ref(): void; - /** - * Sets the local endpoint's window size. - * The `windowSize` is the total window size to set, not - * the delta. - * - * ```js - * const http2 = require('node:http2'); - * - * const server = http2.createServer(); - * const expectedWindowSize = 2 ** 20; - * server.on('connect', (session) => { - * - * // Set local window size to be 2 ** 20 - * session.setLocalWindowSize(expectedWindowSize); - * }); - * ``` - * @since v15.3.0, v14.18.0 - */ - setLocalWindowSize(windowSize: number): void; - /** - * Used to set a callback function that is called when there is no activity on - * the `Http2Session` after `msecs` milliseconds. The given `callback` is - * registered as a listener on the `'timeout'` event. - * @since v8.4.0 - */ - setTimeout(msecs: number, callback?: () => void): void; - /** - * Updates the current local settings for this `Http2Session` and sends a new`SETTINGS` frame to the connected HTTP/2 peer. - * - * Once called, the `http2session.pendingSettingsAck` property will be `true`while the session is waiting for the remote peer to acknowledge the new - * settings. - * - * The new settings will not become effective until the `SETTINGS` acknowledgment - * is received and the `'localSettings'` event is emitted. It is possible to send - * multiple `SETTINGS` frames while acknowledgment is still pending. - * @since v8.4.0 - * @param callback Callback that is called once the session is connected or right away if the session is already connected. - */ - settings( - settings: Settings, - callback?: (err: Error | null, settings: Settings, duration: number) => void, - ): void; - /** - * Calls `unref()` on this `Http2Session`instance's underlying `net.Socket`. - * @since v9.4.0 - */ - unref(): void; - addListener(event: "close", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener( - event: "frameError", - listener: (frameType: number, errorCode: number, streamID: number) => void, - ): this; - addListener( - event: "goaway", - listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void, - ): this; - addListener(event: "localSettings", listener: (settings: Settings) => void): this; - addListener(event: "ping", listener: () => void): this; - addListener(event: "remoteSettings", listener: (settings: Settings) => void): this; - addListener(event: "timeout", listener: () => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - emit(event: "close"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "frameError", frameType: number, errorCode: number, streamID: number): boolean; - emit(event: "goaway", errorCode: number, lastStreamID: number, opaqueData?: Buffer): boolean; - emit(event: "localSettings", settings: Settings): boolean; - emit(event: "ping"): boolean; - emit(event: "remoteSettings", settings: Settings): boolean; - emit(event: "timeout"): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - on(event: "close", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; - on(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void): this; - on(event: "localSettings", listener: (settings: Settings) => void): this; - on(event: "ping", listener: () => void): this; - on(event: "remoteSettings", listener: (settings: Settings) => void): this; - on(event: "timeout", listener: () => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: "close", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; - once(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void): this; - once(event: "localSettings", listener: (settings: Settings) => void): this; - once(event: "ping", listener: () => void): this; - once(event: "remoteSettings", listener: (settings: Settings) => void): this; - once(event: "timeout", listener: () => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener( - event: "frameError", - listener: (frameType: number, errorCode: number, streamID: number) => void, - ): this; - prependListener( - event: "goaway", - listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void, - ): this; - prependListener(event: "localSettings", listener: (settings: Settings) => void): this; - prependListener(event: "ping", listener: () => void): this; - prependListener(event: "remoteSettings", listener: (settings: Settings) => void): this; - prependListener(event: "timeout", listener: () => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener( - event: "frameError", - listener: (frameType: number, errorCode: number, streamID: number) => void, - ): this; - prependOnceListener( - event: "goaway", - listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void, - ): this; - prependOnceListener(event: "localSettings", listener: (settings: Settings) => void): this; - prependOnceListener(event: "ping", listener: () => void): this; - prependOnceListener(event: "remoteSettings", listener: (settings: Settings) => void): this; - prependOnceListener(event: "timeout", listener: () => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - } - export interface ClientHttp2Session extends Http2Session { - /** - * For HTTP/2 Client `Http2Session` instances only, the `http2session.request()`creates and returns an `Http2Stream` instance that can be used to send an - * HTTP/2 request to the connected server. - * - * When a `ClientHttp2Session` is first created, the socket may not yet be - * connected. if `clienthttp2session.request()` is called during this time, the - * actual request will be deferred until the socket is ready to go. - * If the `session` is closed before the actual request be executed, an`ERR_HTTP2_GOAWAY_SESSION` is thrown. - * - * This method is only available if `http2session.type` is equal to`http2.constants.NGHTTP2_SESSION_CLIENT`. - * - * ```js - * const http2 = require('node:http2'); - * const clientSession = http2.connect('https://localhost:1234'); - * const { - * HTTP2_HEADER_PATH, - * HTTP2_HEADER_STATUS, - * } = http2.constants; - * - * const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' }); - * req.on('response', (headers) => { - * console.log(headers[HTTP2_HEADER_STATUS]); - * req.on('data', (chunk) => { // .. }); - * req.on('end', () => { // .. }); - * }); - * ``` - * - * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event - * is emitted immediately after queuing the last chunk of payload data to be sent. - * The `http2stream.sendTrailers()` method can then be called to send trailing - * headers to the peer. - * - * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically - * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. - * - * When `options.signal` is set with an `AbortSignal` and then `abort` on the - * corresponding `AbortController` is called, the request will emit an `'error'`event with an `AbortError` error. - * - * The `:method` and `:path` pseudo-headers are not specified within `headers`, - * they respectively default to: - * - * * `:method` \= `'GET'` - * * `:path` \= `/` - * @since v8.4.0 - */ - request(headers?: OutgoingHttpHeaders, options?: ClientSessionRequestOptions): ClientHttp2Stream; - addListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; - addListener(event: "origin", listener: (origins: string[]) => void): this; - addListener( - event: "connect", - listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, - ): this; - addListener( - event: "stream", - listener: ( - stream: ClientHttp2Stream, - headers: IncomingHttpHeaders & IncomingHttpStatusHeader, - flags: number, - ) => void, - ): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - emit(event: "altsvc", alt: string, origin: string, stream: number): boolean; - emit(event: "origin", origins: readonly string[]): boolean; - emit(event: "connect", session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; - emit( - event: "stream", - stream: ClientHttp2Stream, - headers: IncomingHttpHeaders & IncomingHttpStatusHeader, - flags: number, - ): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - on(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; - on(event: "origin", listener: (origins: string[]) => void): this; - on(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - on( - event: "stream", - listener: ( - stream: ClientHttp2Stream, - headers: IncomingHttpHeaders & IncomingHttpStatusHeader, - flags: number, - ) => void, - ): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; - once(event: "origin", listener: (origins: string[]) => void): this; - once( - event: "connect", - listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, - ): this; - once( - event: "stream", - listener: ( - stream: ClientHttp2Stream, - headers: IncomingHttpHeaders & IncomingHttpStatusHeader, - flags: number, - ) => void, - ): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; - prependListener(event: "origin", listener: (origins: string[]) => void): this; - prependListener( - event: "connect", - listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, - ): this; - prependListener( - event: "stream", - listener: ( - stream: ClientHttp2Stream, - headers: IncomingHttpHeaders & IncomingHttpStatusHeader, - flags: number, - ) => void, - ): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; - prependOnceListener(event: "origin", listener: (origins: string[]) => void): this; - prependOnceListener( - event: "connect", - listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, - ): this; - prependOnceListener( - event: "stream", - listener: ( - stream: ClientHttp2Stream, - headers: IncomingHttpHeaders & IncomingHttpStatusHeader, - flags: number, - ) => void, - ): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - } - export interface AlternativeServiceOptions { - origin: number | string | url.URL; - } - export interface ServerHttp2Session extends Http2Session { - readonly server: Http2Server | Http2SecureServer; - /** - * Submits an `ALTSVC` frame (as defined by [RFC 7838](https://tools.ietf.org/html/rfc7838)) to the connected client. - * - * ```js - * const http2 = require('node:http2'); - * - * const server = http2.createServer(); - * server.on('session', (session) => { - * // Set altsvc for origin https://example.org:80 - * session.altsvc('h2=":8000"', 'https://example.org:80'); - * }); - * - * server.on('stream', (stream) => { - * // Set altsvc for a specific stream - * stream.session.altsvc('h2=":8000"', stream.id); - * }); - * ``` - * - * Sending an `ALTSVC` frame with a specific stream ID indicates that the alternate - * service is associated with the origin of the given `Http2Stream`. - * - * The `alt` and origin string _must_ contain only ASCII bytes and are - * strictly interpreted as a sequence of ASCII bytes. The special value `'clear'`may be passed to clear any previously set alternative service for a given - * domain. - * - * When a string is passed for the `originOrStream` argument, it will be parsed as - * a URL and the origin will be derived. For instance, the origin for the - * HTTP URL `'https://example.org/foo/bar'` is the ASCII string`'https://example.org'`. An error will be thrown if either the given string - * cannot be parsed as a URL or if a valid origin cannot be derived. - * - * A `URL` object, or any object with an `origin` property, may be passed as`originOrStream`, in which case the value of the `origin` property will be - * used. The value of the `origin` property _must_ be a properly serialized - * ASCII origin. - * @since v9.4.0 - * @param alt A description of the alternative service configuration as defined by `RFC 7838`. - * @param originOrStream Either a URL string specifying the origin (or an `Object` with an `origin` property) or the numeric identifier of an active `Http2Stream` as given by the - * `http2stream.id` property. - */ - altsvc(alt: string, originOrStream: number | string | url.URL | AlternativeServiceOptions): void; - /** - * Submits an `ORIGIN` frame (as defined by [RFC 8336](https://tools.ietf.org/html/rfc8336)) to the connected client - * to advertise the set of origins for which the server is capable of providing - * authoritative responses. - * - * ```js - * const http2 = require('node:http2'); - * const options = getSecureOptionsSomehow(); - * const server = http2.createSecureServer(options); - * server.on('stream', (stream) => { - * stream.respond(); - * stream.end('ok'); - * }); - * server.on('session', (session) => { - * session.origin('https://example.com', 'https://example.org'); - * }); - * ``` - * - * When a string is passed as an `origin`, it will be parsed as a URL and the - * origin will be derived. For instance, the origin for the HTTP URL`'https://example.org/foo/bar'` is the ASCII string`'https://example.org'`. An error will be thrown if either the given - * string - * cannot be parsed as a URL or if a valid origin cannot be derived. - * - * A `URL` object, or any object with an `origin` property, may be passed as - * an `origin`, in which case the value of the `origin` property will be - * used. The value of the `origin` property _must_ be a properly serialized - * ASCII origin. - * - * Alternatively, the `origins` option may be used when creating a new HTTP/2 - * server using the `http2.createSecureServer()` method: - * - * ```js - * const http2 = require('node:http2'); - * const options = getSecureOptionsSomehow(); - * options.origins = ['https://example.com', 'https://example.org']; - * const server = http2.createSecureServer(options); - * server.on('stream', (stream) => { - * stream.respond(); - * stream.end('ok'); - * }); - * ``` - * @since v10.12.0 - * @param origins One or more URL Strings passed as separate arguments. - */ - origin( - ...origins: Array< - | string - | url.URL - | { - origin: string; - } - > - ): void; - addListener( - event: "connect", - listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void, - ): this; - addListener( - event: "stream", - listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, - ): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - emit(event: "connect", session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; - emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - on(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - on( - event: "stream", - listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, - ): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - once( - event: "connect", - listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void, - ): this; - once( - event: "stream", - listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, - ): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener( - event: "connect", - listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void, - ): this; - prependListener( - event: "stream", - listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, - ): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener( - event: "connect", - listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void, - ): this; - prependOnceListener( - event: "stream", - listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, - ): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - } - // Http2Server - export interface SessionOptions { - maxDeflateDynamicTableSize?: number | undefined; - maxSessionMemory?: number | undefined; - maxHeaderListPairs?: number | undefined; - maxOutstandingPings?: number | undefined; - maxSendHeaderBlockLength?: number | undefined; - paddingStrategy?: number | undefined; - peerMaxConcurrentStreams?: number | undefined; - settings?: Settings | undefined; - /** - * Specifies a timeout in milliseconds that - * a server should wait when an [`'unknownProtocol'`][] is emitted. If the - * socket has not been destroyed by that time the server will destroy it. - * @default 100000 - */ - unknownProtocolTimeout?: number | undefined; - selectPadding?(frameLen: number, maxFrameLen: number): number; - } - export interface ClientSessionOptions extends SessionOptions { - maxReservedRemoteStreams?: number | undefined; - createConnection?: ((authority: url.URL, option: SessionOptions) => stream.Duplex) | undefined; - protocol?: "http:" | "https:" | undefined; - } - export interface ServerSessionOptions extends SessionOptions { - Http1IncomingMessage?: typeof IncomingMessage | undefined; - Http1ServerResponse?: typeof ServerResponse | undefined; - Http2ServerRequest?: typeof Http2ServerRequest | undefined; - Http2ServerResponse?: typeof Http2ServerResponse | undefined; - } - export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions {} - export interface SecureServerSessionOptions extends ServerSessionOptions, tls.TlsOptions {} - export interface ServerOptions extends ServerSessionOptions {} - export interface SecureServerOptions extends SecureServerSessionOptions { - allowHTTP1?: boolean | undefined; - origins?: string[] | undefined; - } - interface HTTP2ServerCommon { - setTimeout(msec?: number, callback?: () => void): this; - /** - * Throws ERR_HTTP2_INVALID_SETTING_VALUE for invalid settings values. - * Throws ERR_INVALID_ARG_TYPE for invalid settings argument. - */ - updateSettings(settings: Settings): void; - } - export interface Http2Server extends net.Server, HTTP2ServerCommon { - addListener( - event: "checkContinue", - listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, - ): this; - addListener( - event: "request", - listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, - ): this; - addListener(event: "session", listener: (session: ServerHttp2Session) => void): this; - addListener(event: "sessionError", listener: (err: Error) => void): this; - addListener( - event: "stream", - listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, - ): this; - addListener(event: "timeout", listener: () => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; - emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; - emit(event: "session", session: ServerHttp2Session): boolean; - emit(event: "sessionError", err: Error): boolean; - emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; - emit(event: "timeout"): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - on( - event: "checkContinue", - listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, - ): this; - on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - on(event: "session", listener: (session: ServerHttp2Session) => void): this; - on(event: "sessionError", listener: (err: Error) => void): this; - on( - event: "stream", - listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, - ): this; - on(event: "timeout", listener: () => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - once( - event: "checkContinue", - listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, - ): this; - once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - once(event: "session", listener: (session: ServerHttp2Session) => void): this; - once(event: "sessionError", listener: (err: Error) => void): this; - once( - event: "stream", - listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, - ): this; - once(event: "timeout", listener: () => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener( - event: "checkContinue", - listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, - ): this; - prependListener( - event: "request", - listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, - ): this; - prependListener(event: "session", listener: (session: ServerHttp2Session) => void): this; - prependListener(event: "sessionError", listener: (err: Error) => void): this; - prependListener( - event: "stream", - listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, - ): this; - prependListener(event: "timeout", listener: () => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener( - event: "checkContinue", - listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, - ): this; - prependOnceListener( - event: "request", - listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, - ): this; - prependOnceListener(event: "session", listener: (session: ServerHttp2Session) => void): this; - prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; - prependOnceListener( - event: "stream", - listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, - ): this; - prependOnceListener(event: "timeout", listener: () => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - } - export interface Http2SecureServer extends tls.Server, HTTP2ServerCommon { - addListener( - event: "checkContinue", - listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, - ): this; - addListener( - event: "request", - listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, - ): this; - addListener(event: "session", listener: (session: ServerHttp2Session) => void): this; - addListener(event: "sessionError", listener: (err: Error) => void): this; - addListener( - event: "stream", - listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, - ): this; - addListener(event: "timeout", listener: () => void): this; - addListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; - emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; - emit(event: "session", session: ServerHttp2Session): boolean; - emit(event: "sessionError", err: Error): boolean; - emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; - emit(event: "timeout"): boolean; - emit(event: "unknownProtocol", socket: tls.TLSSocket): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - on( - event: "checkContinue", - listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, - ): this; - on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - on(event: "session", listener: (session: ServerHttp2Session) => void): this; - on(event: "sessionError", listener: (err: Error) => void): this; - on( - event: "stream", - listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, - ): this; - on(event: "timeout", listener: () => void): this; - on(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - once( - event: "checkContinue", - listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, - ): this; - once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - once(event: "session", listener: (session: ServerHttp2Session) => void): this; - once(event: "sessionError", listener: (err: Error) => void): this; - once( - event: "stream", - listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, - ): this; - once(event: "timeout", listener: () => void): this; - once(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener( - event: "checkContinue", - listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, - ): this; - prependListener( - event: "request", - listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, - ): this; - prependListener(event: "session", listener: (session: ServerHttp2Session) => void): this; - prependListener(event: "sessionError", listener: (err: Error) => void): this; - prependListener( - event: "stream", - listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, - ): this; - prependListener(event: "timeout", listener: () => void): this; - prependListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener( - event: "checkContinue", - listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, - ): this; - prependOnceListener( - event: "request", - listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, - ): this; - prependOnceListener(event: "session", listener: (session: ServerHttp2Session) => void): this; - prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; - prependOnceListener( - event: "stream", - listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, - ): this; - prependOnceListener(event: "timeout", listener: () => void): this; - prependOnceListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - } - /** - * A `Http2ServerRequest` object is created by {@link Server} or {@link SecureServer} and passed as the first argument to the `'request'` event. It may be used to access a request status, - * headers, and - * data. - * @since v8.4.0 - */ - export class Http2ServerRequest extends stream.Readable { - constructor( - stream: ServerHttp2Stream, - headers: IncomingHttpHeaders, - options: stream.ReadableOptions, - rawHeaders: readonly string[], - ); - /** - * The `request.aborted` property will be `true` if the request has - * been aborted. - * @since v10.1.0 - */ - readonly aborted: boolean; - /** - * The request authority pseudo header field. Because HTTP/2 allows requests - * to set either `:authority` or `host`, this value is derived from`req.headers[':authority']` if present. Otherwise, it is derived from`req.headers['host']`. - * @since v8.4.0 - */ - readonly authority: string; - /** - * See `request.socket`. - * @since v8.4.0 - * @deprecated Since v13.0.0 - Use `socket`. - */ - readonly connection: net.Socket | tls.TLSSocket; - /** - * The `request.complete` property will be `true` if the request has - * been completed, aborted, or destroyed. - * @since v12.10.0 - */ - readonly complete: boolean; - /** - * The request/response headers object. - * - * Key-value pairs of header names and values. Header names are lower-cased. - * - * ```js - * // Prints something like: - * // - * // { 'user-agent': 'curl/7.22.0', - * // host: '127.0.0.1:8000', - * // accept: '*' } - * console.log(request.headers); - * ``` - * - * See `HTTP/2 Headers Object`. - * - * In HTTP/2, the request path, host name, protocol, and method are represented as - * special headers prefixed with the `:` character (e.g. `':path'`). These special - * headers will be included in the `request.headers` object. Care must be taken not - * to inadvertently modify these special headers or errors may occur. For instance, - * removing all headers from the request will cause errors to occur: - * - * ```js - * removeAllHeaders(request.headers); - * assert(request.url); // Fails because the :path header has been removed - * ``` - * @since v8.4.0 - */ - readonly headers: IncomingHttpHeaders; - /** - * In case of server request, the HTTP version sent by the client. In the case of - * client response, the HTTP version of the connected-to server. Returns`'2.0'`. - * - * Also `message.httpVersionMajor` is the first integer and`message.httpVersionMinor` is the second. - * @since v8.4.0 - */ - readonly httpVersion: string; - readonly httpVersionMinor: number; - readonly httpVersionMajor: number; - /** - * The request method as a string. Read-only. Examples: `'GET'`, `'DELETE'`. - * @since v8.4.0 - */ - readonly method: string; - /** - * The raw request/response headers list exactly as they were received. - * - * The keys and values are in the same list. It is _not_ a - * list of tuples. So, the even-numbered offsets are key values, and the - * odd-numbered offsets are the associated values. - * - * Header names are not lowercased, and duplicates are not merged. - * - * ```js - * // Prints something like: - * // - * // [ 'user-agent', - * // 'this is invalid because there can be only one', - * // 'User-Agent', - * // 'curl/7.22.0', - * // 'Host', - * // '127.0.0.1:8000', - * // 'ACCEPT', - * // '*' ] - * console.log(request.rawHeaders); - * ``` - * @since v8.4.0 - */ - readonly rawHeaders: string[]; - /** - * The raw request/response trailer keys and values exactly as they were - * received. Only populated at the `'end'` event. - * @since v8.4.0 - */ - readonly rawTrailers: string[]; - /** - * The request scheme pseudo header field indicating the scheme - * portion of the target URL. - * @since v8.4.0 - */ - readonly scheme: string; - /** - * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but - * applies getters, setters, and methods based on HTTP/2 logic. - * - * `destroyed`, `readable`, and `writable` properties will be retrieved from and - * set on `request.stream`. - * - * `destroy`, `emit`, `end`, `on` and `once` methods will be called on`request.stream`. - * - * `setTimeout` method will be called on `request.stream.session`. - * - * `pause`, `read`, `resume`, and `write` will throw an error with code`ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for - * more information. - * - * All other interactions will be routed directly to the socket. With TLS support, - * use `request.socket.getPeerCertificate()` to obtain the client's - * authentication details. - * @since v8.4.0 - */ - readonly socket: net.Socket | tls.TLSSocket; - /** - * The `Http2Stream` object backing the request. - * @since v8.4.0 - */ - readonly stream: ServerHttp2Stream; - /** - * The request/response trailers object. Only populated at the `'end'` event. - * @since v8.4.0 - */ - readonly trailers: IncomingHttpHeaders; - /** - * Request URL string. This contains only the URL that is present in the actual - * HTTP request. If the request is: - * - * ```http - * GET /status?name=ryan HTTP/1.1 - * Accept: text/plain - * ``` - * - * Then `request.url` will be: - * - * ```js - * '/status?name=ryan' - * ``` - * - * To parse the url into its parts, `new URL()` can be used: - * - * ```console - * $ node - * > new URL('/status?name=ryan', 'http://example.com') - * URL { - * href: 'http://example.com/status?name=ryan', - * origin: 'http://example.com', - * protocol: 'http:', - * username: '', - * password: '', - * host: 'example.com', - * hostname: 'example.com', - * port: '', - * pathname: '/status', - * search: '?name=ryan', - * searchParams: URLSearchParams { 'name' => 'ryan' }, - * hash: '' - * } - * ``` - * @since v8.4.0 - */ - url: string; - /** - * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is - * provided, then it is added as a listener on the `'timeout'` event on - * the response object. - * - * If no `'timeout'` listener is added to the request, the response, or - * the server, then `Http2Stream` s are destroyed when they time out. If a - * handler is assigned to the request, the response, or the server's `'timeout'`events, timed out sockets must be handled explicitly. - * @since v8.4.0 - */ - setTimeout(msecs: number, callback?: () => void): void; - read(size?: number): Buffer | string | null; - addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "data", listener: (chunk: Buffer | string) => void): this; - addListener(event: "end", listener: () => void): this; - addListener(event: "readable", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - emit(event: "aborted", hadError: boolean, code: number): boolean; - emit(event: "close"): boolean; - emit(event: "data", chunk: Buffer | string): boolean; - emit(event: "end"): boolean; - emit(event: "readable"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - on(event: "aborted", listener: (hadError: boolean, code: number) => void): this; - on(event: "close", listener: () => void): this; - on(event: "data", listener: (chunk: Buffer | string) => void): this; - on(event: "end", listener: () => void): this; - on(event: "readable", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: "aborted", listener: (hadError: boolean, code: number) => void): this; - once(event: "close", listener: () => void): this; - once(event: "data", listener: (chunk: Buffer | string) => void): this; - once(event: "end", listener: () => void): this; - once(event: "readable", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; - prependListener(event: "end", listener: () => void): this; - prependListener(event: "readable", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; - prependOnceListener(event: "end", listener: () => void): this; - prependOnceListener(event: "readable", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - } - /** - * This object is created internally by an HTTP server, not by the user. It is - * passed as the second parameter to the `'request'` event. - * @since v8.4.0 - */ - export class Http2ServerResponse extends stream.Writable { - constructor(stream: ServerHttp2Stream); - /** - * See `response.socket`. - * @since v8.4.0 - * @deprecated Since v13.0.0 - Use `socket`. - */ - readonly connection: net.Socket | tls.TLSSocket; - /** - * Boolean value that indicates whether the response has completed. Starts - * as `false`. After `response.end()` executes, the value will be `true`. - * @since v8.4.0 - * @deprecated Since v13.4.0,v12.16.0 - Use `writableEnded`. - */ - readonly finished: boolean; - /** - * True if headers were sent, false otherwise (read-only). - * @since v8.4.0 - */ - readonly headersSent: boolean; - /** - * A reference to the original HTTP2 `request` object. - * @since v15.7.0 - */ - readonly req: Http2ServerRequest; - /** - * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but - * applies getters, setters, and methods based on HTTP/2 logic. - * - * `destroyed`, `readable`, and `writable` properties will be retrieved from and - * set on `response.stream`. - * - * `destroy`, `emit`, `end`, `on` and `once` methods will be called on`response.stream`. - * - * `setTimeout` method will be called on `response.stream.session`. - * - * `pause`, `read`, `resume`, and `write` will throw an error with code`ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for - * more information. - * - * All other interactions will be routed directly to the socket. - * - * ```js - * const http2 = require('node:http2'); - * const server = http2.createServer((req, res) => { - * const ip = req.socket.remoteAddress; - * const port = req.socket.remotePort; - * res.end(`Your IP address is ${ip} and your source port is ${port}.`); - * }).listen(3000); - * ``` - * @since v8.4.0 - */ - readonly socket: net.Socket | tls.TLSSocket; - /** - * The `Http2Stream` object backing the response. - * @since v8.4.0 - */ - readonly stream: ServerHttp2Stream; - /** - * When true, the Date header will be automatically generated and sent in - * the response if it is not already present in the headers. Defaults to true. - * - * This should only be disabled for testing; HTTP requires the Date header - * in responses. - * @since v8.4.0 - */ - sendDate: boolean; - /** - * When using implicit headers (not calling `response.writeHead()` explicitly), - * this property controls the status code that will be sent to the client when - * the headers get flushed. - * - * ```js - * response.statusCode = 404; - * ``` - * - * After response header was sent to the client, this property indicates the - * status code which was sent out. - * @since v8.4.0 - */ - statusCode: number; - /** - * Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns - * an empty string. - * @since v8.4.0 - */ - statusMessage: ""; - /** - * This method adds HTTP trailing headers (a header but at the end of the - * message) to the response. - * - * Attempting to set a header field name or value that contains invalid characters - * will result in a `TypeError` being thrown. - * @since v8.4.0 - */ - addTrailers(trailers: OutgoingHttpHeaders): void; - /** - * This method signals to the server that all of the response headers and body - * have been sent; that server should consider this message complete. - * The method, `response.end()`, MUST be called on each response. - * - * If `data` is specified, it is equivalent to calling `response.write(data, encoding)` followed by `response.end(callback)`. - * - * If `callback` is specified, it will be called when the response stream - * is finished. - * @since v8.4.0 - */ - end(callback?: () => void): this; - end(data: string | Uint8Array, callback?: () => void): this; - end(data: string | Uint8Array, encoding: BufferEncoding, callback?: () => void): this; - /** - * Reads out a header that has already been queued but not sent to the client. - * The name is case-insensitive. - * - * ```js - * const contentType = response.getHeader('content-type'); - * ``` - * @since v8.4.0 - */ - getHeader(name: string): string; - /** - * Returns an array containing the unique names of the current outgoing headers. - * All header names are lowercase. - * - * ```js - * response.setHeader('Foo', 'bar'); - * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); - * - * const headerNames = response.getHeaderNames(); - * // headerNames === ['foo', 'set-cookie'] - * ``` - * @since v8.4.0 - */ - getHeaderNames(): string[]; - /** - * Returns a shallow copy of the current outgoing headers. Since a shallow copy - * is used, array values may be mutated without additional calls to various - * header-related http module methods. The keys of the returned object are the - * header names and the values are the respective header values. All header names - * are lowercase. - * - * The object returned by the `response.getHeaders()` method _does not_prototypically inherit from the JavaScript `Object`. This means that typical`Object` methods such as `obj.toString()`, - * `obj.hasOwnProperty()`, and others - * are not defined and _will not work_. - * - * ```js - * response.setHeader('Foo', 'bar'); - * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); - * - * const headers = response.getHeaders(); - * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } - * ``` - * @since v8.4.0 - */ - getHeaders(): OutgoingHttpHeaders; - /** - * Returns `true` if the header identified by `name` is currently set in the - * outgoing headers. The header name matching is case-insensitive. - * - * ```js - * const hasContentType = response.hasHeader('content-type'); - * ``` - * @since v8.4.0 - */ - hasHeader(name: string): boolean; - /** - * Removes a header that has been queued for implicit sending. - * - * ```js - * response.removeHeader('Content-Encoding'); - * ``` - * @since v8.4.0 - */ - removeHeader(name: string): void; - /** - * Sets a single header value for implicit headers. If this header already exists - * in the to-be-sent headers, its value will be replaced. Use an array of strings - * here to send multiple headers with the same name. - * - * ```js - * response.setHeader('Content-Type', 'text/html; charset=utf-8'); - * ``` - * - * or - * - * ```js - * response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); - * ``` - * - * Attempting to set a header field name or value that contains invalid characters - * will result in a `TypeError` being thrown. - * - * When headers have been set with `response.setHeader()`, they will be merged - * with any headers passed to `response.writeHead()`, with the headers passed - * to `response.writeHead()` given precedence. - * - * ```js - * // Returns content-type = text/plain - * const server = http2.createServer((req, res) => { - * res.setHeader('Content-Type', 'text/html; charset=utf-8'); - * res.setHeader('X-Foo', 'bar'); - * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); - * res.end('ok'); - * }); - * ``` - * @since v8.4.0 - */ - setHeader(name: string, value: number | string | readonly string[]): void; - /** - * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is - * provided, then it is added as a listener on the `'timeout'` event on - * the response object. - * - * If no `'timeout'` listener is added to the request, the response, or - * the server, then `Http2Stream` s are destroyed when they time out. If a - * handler is assigned to the request, the response, or the server's `'timeout'`events, timed out sockets must be handled explicitly. - * @since v8.4.0 - */ - setTimeout(msecs: number, callback?: () => void): void; - /** - * If this method is called and `response.writeHead()` has not been called, - * it will switch to implicit header mode and flush the implicit headers. - * - * This sends a chunk of the response body. This method may - * be called multiple times to provide successive parts of the body. - * - * In the `node:http` module, the response body is omitted when the - * request is a HEAD request. Similarly, the `204` and `304` responses _must not_ include a message body. - * - * `chunk` can be a string or a buffer. If `chunk` is a string, - * the second parameter specifies how to encode it into a byte stream. - * By default the `encoding` is `'utf8'`. `callback` will be called when this chunk - * of data is flushed. - * - * This is the raw HTTP body and has nothing to do with higher-level multi-part - * body encodings that may be used. - * - * The first time `response.write()` is called, it will send the buffered - * header information and the first chunk of the body to the client. The second - * time `response.write()` is called, Node.js assumes data will be streamed, - * and sends the new data separately. That is, the response is buffered up to the - * first chunk of the body. - * - * Returns `true` if the entire data was flushed successfully to the kernel - * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is free again. - * @since v8.4.0 - */ - write(chunk: string | Uint8Array, callback?: (err: Error) => void): boolean; - write(chunk: string | Uint8Array, encoding: BufferEncoding, callback?: (err: Error) => void): boolean; - /** - * Sends a status `100 Continue` to the client, indicating that the request body - * should be sent. See the `'checkContinue'` event on `Http2Server` and`Http2SecureServer`. - * @since v8.4.0 - */ - writeContinue(): void; - /** - * Sends a status `103 Early Hints` to the client with a Link header, - * indicating that the user agent can preload/preconnect the linked resources. - * The `hints` is an object containing the values of headers to be sent with - * early hints message. - * - * **Example** - * - * ```js - * const earlyHintsLink = '; rel=preload; as=style'; - * response.writeEarlyHints({ - * 'link': earlyHintsLink, - * }); - * - * const earlyHintsLinks = [ - * '; rel=preload; as=style', - * '; rel=preload; as=script', - * ]; - * response.writeEarlyHints({ - * 'link': earlyHintsLinks, - * }); - * ``` - * @since v18.11.0 - */ - writeEarlyHints(hints: Record): void; - /** - * Sends a response header to the request. The status code is a 3-digit HTTP - * status code, like `404`. The last argument, `headers`, are the response headers. - * - * Returns a reference to the `Http2ServerResponse`, so that calls can be chained. - * - * For compatibility with `HTTP/1`, a human-readable `statusMessage` may be - * passed as the second argument. However, because the `statusMessage` has no - * meaning within HTTP/2, the argument will have no effect and a process warning - * will be emitted. - * - * ```js - * const body = 'hello world'; - * response.writeHead(200, { - * 'Content-Length': Buffer.byteLength(body), - * 'Content-Type': 'text/plain; charset=utf-8', - * }); - * ``` - * - * `Content-Length` is given in bytes not characters. The`Buffer.byteLength()` API may be used to determine the number of bytes in a - * given encoding. On outbound messages, Node.js does not check if Content-Length - * and the length of the body being transmitted are equal or not. However, when - * receiving messages, Node.js will automatically reject messages when the`Content-Length` does not match the actual payload size. - * - * This method may be called at most one time on a message before `response.end()` is called. - * - * If `response.write()` or `response.end()` are called before calling - * this, the implicit/mutable headers will be calculated and call this function. - * - * When headers have been set with `response.setHeader()`, they will be merged - * with any headers passed to `response.writeHead()`, with the headers passed - * to `response.writeHead()` given precedence. - * - * ```js - * // Returns content-type = text/plain - * const server = http2.createServer((req, res) => { - * res.setHeader('Content-Type', 'text/html; charset=utf-8'); - * res.setHeader('X-Foo', 'bar'); - * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); - * res.end('ok'); - * }); - * ``` - * - * Attempting to set a header field name or value that contains invalid characters - * will result in a `TypeError` being thrown. - * @since v8.4.0 - */ - writeHead(statusCode: number, headers?: OutgoingHttpHeaders): this; - writeHead(statusCode: number, statusMessage: string, headers?: OutgoingHttpHeaders): this; - /** - * Call `http2stream.pushStream()` with the given headers, and wrap the - * given `Http2Stream` on a newly created `Http2ServerResponse` as the callback - * parameter if successful. When `Http2ServerRequest` is closed, the callback is - * called with an error `ERR_HTTP2_INVALID_STREAM`. - * @since v8.4.0 - * @param headers An object describing the headers - * @param callback Called once `http2stream.pushStream()` is finished, or either when the attempt to create the pushed `Http2Stream` has failed or has been rejected, or the state of - * `Http2ServerRequest` is closed prior to calling the `http2stream.pushStream()` method - */ - createPushResponse( - headers: OutgoingHttpHeaders, - callback: (err: Error | null, res: Http2ServerResponse) => void, - ): void; - addListener(event: "close", listener: () => void): this; - addListener(event: "drain", listener: () => void): this; - addListener(event: "error", listener: (error: Error) => void): this; - addListener(event: "finish", listener: () => void): this; - addListener(event: "pipe", listener: (src: stream.Readable) => void): this; - addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - emit(event: "close"): boolean; - emit(event: "drain"): boolean; - emit(event: "error", error: Error): boolean; - emit(event: "finish"): boolean; - emit(event: "pipe", src: stream.Readable): boolean; - emit(event: "unpipe", src: stream.Readable): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - on(event: "close", listener: () => void): this; - on(event: "drain", listener: () => void): this; - on(event: "error", listener: (error: Error) => void): this; - on(event: "finish", listener: () => void): this; - on(event: "pipe", listener: (src: stream.Readable) => void): this; - on(event: "unpipe", listener: (src: stream.Readable) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: "close", listener: () => void): this; - once(event: "drain", listener: () => void): this; - once(event: "error", listener: (error: Error) => void): this; - once(event: "finish", listener: () => void): this; - once(event: "pipe", listener: (src: stream.Readable) => void): this; - once(event: "unpipe", listener: (src: stream.Readable) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "drain", listener: () => void): this; - prependListener(event: "error", listener: (error: Error) => void): this; - prependListener(event: "finish", listener: () => void): this; - prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; - prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "drain", listener: () => void): this; - prependOnceListener(event: "error", listener: (error: Error) => void): this; - prependOnceListener(event: "finish", listener: () => void): this; - prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; - prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - } - export namespace constants { - const NGHTTP2_SESSION_SERVER: number; - const NGHTTP2_SESSION_CLIENT: number; - const NGHTTP2_STREAM_STATE_IDLE: number; - const NGHTTP2_STREAM_STATE_OPEN: number; - const NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number; - const NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number; - const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number; - const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number; - const NGHTTP2_STREAM_STATE_CLOSED: number; - const NGHTTP2_NO_ERROR: number; - const NGHTTP2_PROTOCOL_ERROR: number; - const NGHTTP2_INTERNAL_ERROR: number; - const NGHTTP2_FLOW_CONTROL_ERROR: number; - const NGHTTP2_SETTINGS_TIMEOUT: number; - const NGHTTP2_STREAM_CLOSED: number; - const NGHTTP2_FRAME_SIZE_ERROR: number; - const NGHTTP2_REFUSED_STREAM: number; - const NGHTTP2_CANCEL: number; - const NGHTTP2_COMPRESSION_ERROR: number; - const NGHTTP2_CONNECT_ERROR: number; - const NGHTTP2_ENHANCE_YOUR_CALM: number; - const NGHTTP2_INADEQUATE_SECURITY: number; - const NGHTTP2_HTTP_1_1_REQUIRED: number; - const NGHTTP2_ERR_FRAME_SIZE_ERROR: number; - const NGHTTP2_FLAG_NONE: number; - const NGHTTP2_FLAG_END_STREAM: number; - const NGHTTP2_FLAG_END_HEADERS: number; - const NGHTTP2_FLAG_ACK: number; - const NGHTTP2_FLAG_PADDED: number; - const NGHTTP2_FLAG_PRIORITY: number; - const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number; - const DEFAULT_SETTINGS_ENABLE_PUSH: number; - const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number; - const DEFAULT_SETTINGS_MAX_FRAME_SIZE: number; - const MAX_MAX_FRAME_SIZE: number; - const MIN_MAX_FRAME_SIZE: number; - const MAX_INITIAL_WINDOW_SIZE: number; - const NGHTTP2_DEFAULT_WEIGHT: number; - const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number; - const NGHTTP2_SETTINGS_ENABLE_PUSH: number; - const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number; - const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number; - const NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number; - const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number; - const PADDING_STRATEGY_NONE: number; - const PADDING_STRATEGY_MAX: number; - const PADDING_STRATEGY_CALLBACK: number; - const HTTP2_HEADER_STATUS: string; - const HTTP2_HEADER_METHOD: string; - const HTTP2_HEADER_AUTHORITY: string; - const HTTP2_HEADER_SCHEME: string; - const HTTP2_HEADER_PATH: string; - const HTTP2_HEADER_ACCEPT_CHARSET: string; - const HTTP2_HEADER_ACCEPT_ENCODING: string; - const HTTP2_HEADER_ACCEPT_LANGUAGE: string; - const HTTP2_HEADER_ACCEPT_RANGES: string; - const HTTP2_HEADER_ACCEPT: string; - const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string; - const HTTP2_HEADER_AGE: string; - const HTTP2_HEADER_ALLOW: string; - const HTTP2_HEADER_AUTHORIZATION: string; - const HTTP2_HEADER_CACHE_CONTROL: string; - const HTTP2_HEADER_CONNECTION: string; - const HTTP2_HEADER_CONTENT_DISPOSITION: string; - const HTTP2_HEADER_CONTENT_ENCODING: string; - const HTTP2_HEADER_CONTENT_LANGUAGE: string; - const HTTP2_HEADER_CONTENT_LENGTH: string; - const HTTP2_HEADER_CONTENT_LOCATION: string; - const HTTP2_HEADER_CONTENT_MD5: string; - const HTTP2_HEADER_CONTENT_RANGE: string; - const HTTP2_HEADER_CONTENT_TYPE: string; - const HTTP2_HEADER_COOKIE: string; - const HTTP2_HEADER_DATE: string; - const HTTP2_HEADER_ETAG: string; - const HTTP2_HEADER_EXPECT: string; - const HTTP2_HEADER_EXPIRES: string; - const HTTP2_HEADER_FROM: string; - const HTTP2_HEADER_HOST: string; - const HTTP2_HEADER_IF_MATCH: string; - const HTTP2_HEADER_IF_MODIFIED_SINCE: string; - const HTTP2_HEADER_IF_NONE_MATCH: string; - const HTTP2_HEADER_IF_RANGE: string; - const HTTP2_HEADER_IF_UNMODIFIED_SINCE: string; - const HTTP2_HEADER_LAST_MODIFIED: string; - const HTTP2_HEADER_LINK: string; - const HTTP2_HEADER_LOCATION: string; - const HTTP2_HEADER_MAX_FORWARDS: string; - const HTTP2_HEADER_PREFER: string; - const HTTP2_HEADER_PROXY_AUTHENTICATE: string; - const HTTP2_HEADER_PROXY_AUTHORIZATION: string; - const HTTP2_HEADER_RANGE: string; - const HTTP2_HEADER_REFERER: string; - const HTTP2_HEADER_REFRESH: string; - const HTTP2_HEADER_RETRY_AFTER: string; - const HTTP2_HEADER_SERVER: string; - const HTTP2_HEADER_SET_COOKIE: string; - const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string; - const HTTP2_HEADER_TRANSFER_ENCODING: string; - const HTTP2_HEADER_TE: string; - const HTTP2_HEADER_UPGRADE: string; - const HTTP2_HEADER_USER_AGENT: string; - const HTTP2_HEADER_VARY: string; - const HTTP2_HEADER_VIA: string; - const HTTP2_HEADER_WWW_AUTHENTICATE: string; - const HTTP2_HEADER_HTTP2_SETTINGS: string; - const HTTP2_HEADER_KEEP_ALIVE: string; - const HTTP2_HEADER_PROXY_CONNECTION: string; - const HTTP2_METHOD_ACL: string; - const HTTP2_METHOD_BASELINE_CONTROL: string; - const HTTP2_METHOD_BIND: string; - const HTTP2_METHOD_CHECKIN: string; - const HTTP2_METHOD_CHECKOUT: string; - const HTTP2_METHOD_CONNECT: string; - const HTTP2_METHOD_COPY: string; - const HTTP2_METHOD_DELETE: string; - const HTTP2_METHOD_GET: string; - const HTTP2_METHOD_HEAD: string; - const HTTP2_METHOD_LABEL: string; - const HTTP2_METHOD_LINK: string; - const HTTP2_METHOD_LOCK: string; - const HTTP2_METHOD_MERGE: string; - const HTTP2_METHOD_MKACTIVITY: string; - const HTTP2_METHOD_MKCALENDAR: string; - const HTTP2_METHOD_MKCOL: string; - const HTTP2_METHOD_MKREDIRECTREF: string; - const HTTP2_METHOD_MKWORKSPACE: string; - const HTTP2_METHOD_MOVE: string; - const HTTP2_METHOD_OPTIONS: string; - const HTTP2_METHOD_ORDERPATCH: string; - const HTTP2_METHOD_PATCH: string; - const HTTP2_METHOD_POST: string; - const HTTP2_METHOD_PRI: string; - const HTTP2_METHOD_PROPFIND: string; - const HTTP2_METHOD_PROPPATCH: string; - const HTTP2_METHOD_PUT: string; - const HTTP2_METHOD_REBIND: string; - const HTTP2_METHOD_REPORT: string; - const HTTP2_METHOD_SEARCH: string; - const HTTP2_METHOD_TRACE: string; - const HTTP2_METHOD_UNBIND: string; - const HTTP2_METHOD_UNCHECKOUT: string; - const HTTP2_METHOD_UNLINK: string; - const HTTP2_METHOD_UNLOCK: string; - const HTTP2_METHOD_UPDATE: string; - const HTTP2_METHOD_UPDATEREDIRECTREF: string; - const HTTP2_METHOD_VERSION_CONTROL: string; - const HTTP_STATUS_CONTINUE: number; - const HTTP_STATUS_SWITCHING_PROTOCOLS: number; - const HTTP_STATUS_PROCESSING: number; - const HTTP_STATUS_OK: number; - const HTTP_STATUS_CREATED: number; - const HTTP_STATUS_ACCEPTED: number; - const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number; - const HTTP_STATUS_NO_CONTENT: number; - const HTTP_STATUS_RESET_CONTENT: number; - const HTTP_STATUS_PARTIAL_CONTENT: number; - const HTTP_STATUS_MULTI_STATUS: number; - const HTTP_STATUS_ALREADY_REPORTED: number; - const HTTP_STATUS_IM_USED: number; - const HTTP_STATUS_MULTIPLE_CHOICES: number; - const HTTP_STATUS_MOVED_PERMANENTLY: number; - const HTTP_STATUS_FOUND: number; - const HTTP_STATUS_SEE_OTHER: number; - const HTTP_STATUS_NOT_MODIFIED: number; - const HTTP_STATUS_USE_PROXY: number; - const HTTP_STATUS_TEMPORARY_REDIRECT: number; - const HTTP_STATUS_PERMANENT_REDIRECT: number; - const HTTP_STATUS_BAD_REQUEST: number; - const HTTP_STATUS_UNAUTHORIZED: number; - const HTTP_STATUS_PAYMENT_REQUIRED: number; - const HTTP_STATUS_FORBIDDEN: number; - const HTTP_STATUS_NOT_FOUND: number; - const HTTP_STATUS_METHOD_NOT_ALLOWED: number; - const HTTP_STATUS_NOT_ACCEPTABLE: number; - const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number; - const HTTP_STATUS_REQUEST_TIMEOUT: number; - const HTTP_STATUS_CONFLICT: number; - const HTTP_STATUS_GONE: number; - const HTTP_STATUS_LENGTH_REQUIRED: number; - const HTTP_STATUS_PRECONDITION_FAILED: number; - const HTTP_STATUS_PAYLOAD_TOO_LARGE: number; - const HTTP_STATUS_URI_TOO_LONG: number; - const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number; - const HTTP_STATUS_RANGE_NOT_SATISFIABLE: number; - const HTTP_STATUS_EXPECTATION_FAILED: number; - const HTTP_STATUS_TEAPOT: number; - const HTTP_STATUS_MISDIRECTED_REQUEST: number; - const HTTP_STATUS_UNPROCESSABLE_ENTITY: number; - const HTTP_STATUS_LOCKED: number; - const HTTP_STATUS_FAILED_DEPENDENCY: number; - const HTTP_STATUS_UNORDERED_COLLECTION: number; - const HTTP_STATUS_UPGRADE_REQUIRED: number; - const HTTP_STATUS_PRECONDITION_REQUIRED: number; - const HTTP_STATUS_TOO_MANY_REQUESTS: number; - const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number; - const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number; - const HTTP_STATUS_INTERNAL_SERVER_ERROR: number; - const HTTP_STATUS_NOT_IMPLEMENTED: number; - const HTTP_STATUS_BAD_GATEWAY: number; - const HTTP_STATUS_SERVICE_UNAVAILABLE: number; - const HTTP_STATUS_GATEWAY_TIMEOUT: number; - const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number; - const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number; - const HTTP_STATUS_INSUFFICIENT_STORAGE: number; - const HTTP_STATUS_LOOP_DETECTED: number; - const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number; - const HTTP_STATUS_NOT_EXTENDED: number; - const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number; - } - /** - * This symbol can be set as a property on the HTTP/2 headers object with - * an array value in order to provide a list of headers considered sensitive. - */ - export const sensitiveHeaders: symbol; - /** - * Returns an object containing the default settings for an `Http2Session`instance. This method returns a new object instance every time it is called - * so instances returned may be safely modified for use. - * @since v8.4.0 - */ - export function getDefaultSettings(): Settings; - /** - * Returns a `Buffer` instance containing serialized representation of the given - * HTTP/2 settings as specified in the [HTTP/2](https://tools.ietf.org/html/rfc7540) specification. This is intended - * for use with the `HTTP2-Settings` header field. - * - * ```js - * const http2 = require('node:http2'); - * - * const packed = http2.getPackedSettings({ enablePush: false }); - * - * console.log(packed.toString('base64')); - * // Prints: AAIAAAAA - * ``` - * @since v8.4.0 - */ - export function getPackedSettings(settings: Settings): Buffer; - /** - * Returns a `HTTP/2 Settings Object` containing the deserialized settings from - * the given `Buffer` as generated by `http2.getPackedSettings()`. - * @since v8.4.0 - * @param buf The packed settings. - */ - export function getUnpackedSettings(buf: Uint8Array): Settings; - /** - * Returns a `net.Server` instance that creates and manages `Http2Session`instances. - * - * Since there are no browsers known that support [unencrypted HTTP/2](https://http2.github.io/faq/#does-http2-require-encryption), the use of {@link createSecureServer} is necessary when - * communicating - * with browser clients. - * - * ```js - * const http2 = require('node:http2'); - * - * // Create an unencrypted HTTP/2 server. - * // Since there are no browsers known that support - * // unencrypted HTTP/2, the use of `http2.createSecureServer()` - * // is necessary when communicating with browser clients. - * const server = http2.createServer(); - * - * server.on('stream', (stream, headers) => { - * stream.respond({ - * 'content-type': 'text/html; charset=utf-8', - * ':status': 200, - * }); - * stream.end('

Hello World

'); - * }); - * - * server.listen(8000); - * ``` - * @since v8.4.0 - * @param onRequestHandler See `Compatibility API` - */ - export function createServer( - onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, - ): Http2Server; - export function createServer( - options: ServerOptions, - onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, - ): Http2Server; - /** - * Returns a `tls.Server` instance that creates and manages `Http2Session`instances. - * - * ```js - * const http2 = require('node:http2'); - * const fs = require('node:fs'); - * - * const options = { - * key: fs.readFileSync('server-key.pem'), - * cert: fs.readFileSync('server-cert.pem'), - * }; - * - * // Create a secure HTTP/2 server - * const server = http2.createSecureServer(options); - * - * server.on('stream', (stream, headers) => { - * stream.respond({ - * 'content-type': 'text/html; charset=utf-8', - * ':status': 200, - * }); - * stream.end('

Hello World

'); - * }); - * - * server.listen(8443); - * ``` - * @since v8.4.0 - * @param onRequestHandler See `Compatibility API` - */ - export function createSecureServer( - onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, - ): Http2SecureServer; - export function createSecureServer( - options: SecureServerOptions, - onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, - ): Http2SecureServer; - /** - * Returns a `ClientHttp2Session` instance. - * - * ```js - * const http2 = require('node:http2'); - * const client = http2.connect('https://localhost:1234'); - * - * // Use the client - * - * client.close(); - * ``` - * @since v8.4.0 - * @param authority The remote HTTP/2 server to connect to. This must be in the form of a minimal, valid URL with the `http://` or `https://` prefix, host name, and IP port (if a non-default port - * is used). Userinfo (user ID and password), path, querystring, and fragment details in the URL will be ignored. - * @param listener Will be registered as a one-time listener of the {@link 'connect'} event. - */ - export function connect( - authority: string | url.URL, - listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, - ): ClientHttp2Session; - export function connect( - authority: string | url.URL, - options?: ClientSessionOptions | SecureClientSessionOptions, - listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, - ): ClientHttp2Session; -} -declare module "node:http2" { - export * from "http2"; -} diff --git a/node_modules/@types/node/ts4.8/https.d.ts b/node_modules/@types/node/ts4.8/https.d.ts deleted file mode 100644 index 36ae5b2f52eb9b643b32e59346df07b40758cd1f..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/https.d.ts +++ /dev/null @@ -1,550 +0,0 @@ -/** - * HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a - * separate module. - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/https.js) - */ -declare module "https" { - import { Duplex } from "node:stream"; - import * as tls from "node:tls"; - import * as http from "node:http"; - import { URL } from "node:url"; - type ServerOptions< - Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, - Response extends typeof http.ServerResponse = typeof http.ServerResponse, - > = tls.SecureContextOptions & tls.TlsOptions & http.ServerOptions; - type RequestOptions = - & http.RequestOptions - & tls.SecureContextOptions - & { - checkServerIdentity?: typeof tls.checkServerIdentity | undefined; - rejectUnauthorized?: boolean | undefined; // Defaults to true - servername?: string | undefined; // SNI TLS Extension - }; - interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { - rejectUnauthorized?: boolean | undefined; - maxCachedSessions?: number | undefined; - } - /** - * An `Agent` object for HTTPS similar to `http.Agent`. See {@link request} for more information. - * @since v0.4.5 - */ - class Agent extends http.Agent { - constructor(options?: AgentOptions); - options: AgentOptions; - } - interface Server< - Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, - Response extends typeof http.ServerResponse = typeof http.ServerResponse, - > extends http.Server {} - /** - * See `http.Server` for more information. - * @since v0.3.4 - */ - class Server< - Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, - Response extends typeof http.ServerResponse = typeof http.ServerResponse, - > extends tls.Server { - constructor(requestListener?: http.RequestListener); - constructor( - options: ServerOptions, - requestListener?: http.RequestListener, - ); - /** - * Closes all connections connected to this server. - * @since v18.2.0 - */ - closeAllConnections(): void; - /** - * Closes all connections connected to this server which are not sending a request or waiting for a response. - * @since v18.2.0 - */ - closeIdleConnections(): void; - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; - addListener( - event: "newSession", - listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, - ): this; - addListener( - event: "OCSPRequest", - listener: ( - certificate: Buffer, - issuer: Buffer, - callback: (err: Error | null, resp: Buffer) => void, - ) => void, - ): this; - addListener( - event: "resumeSession", - listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, - ): this; - addListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; - addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "connection", listener: (socket: Duplex) => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "listening", listener: () => void): this; - addListener(event: "checkContinue", listener: http.RequestListener): this; - addListener(event: "checkExpectation", listener: http.RequestListener): this; - addListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; - addListener( - event: "connect", - listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, - ): this; - addListener(event: "request", listener: http.RequestListener): this; - addListener( - event: "upgrade", - listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, - ): this; - emit(event: string, ...args: any[]): boolean; - emit(event: "keylog", line: Buffer, tlsSocket: tls.TLSSocket): boolean; - emit( - event: "newSession", - sessionId: Buffer, - sessionData: Buffer, - callback: (err: Error, resp: Buffer) => void, - ): boolean; - emit( - event: "OCSPRequest", - certificate: Buffer, - issuer: Buffer, - callback: (err: Error | null, resp: Buffer) => void, - ): boolean; - emit(event: "resumeSession", sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void): boolean; - emit(event: "secureConnection", tlsSocket: tls.TLSSocket): boolean; - emit(event: "tlsClientError", err: Error, tlsSocket: tls.TLSSocket): boolean; - emit(event: "close"): boolean; - emit(event: "connection", socket: Duplex): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "listening"): boolean; - emit( - event: "checkContinue", - req: InstanceType, - res: InstanceType & { - req: InstanceType; - }, - ): boolean; - emit( - event: "checkExpectation", - req: InstanceType, - res: InstanceType & { - req: InstanceType; - }, - ): boolean; - emit(event: "clientError", err: Error, socket: Duplex): boolean; - emit(event: "connect", req: InstanceType, socket: Duplex, head: Buffer): boolean; - emit( - event: "request", - req: InstanceType, - res: InstanceType & { - req: InstanceType; - }, - ): boolean; - emit(event: "upgrade", req: InstanceType, socket: Duplex, head: Buffer): boolean; - on(event: string, listener: (...args: any[]) => void): this; - on(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; - on( - event: "newSession", - listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, - ): this; - on( - event: "OCSPRequest", - listener: ( - certificate: Buffer, - issuer: Buffer, - callback: (err: Error | null, resp: Buffer) => void, - ) => void, - ): this; - on( - event: "resumeSession", - listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, - ): this; - on(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; - on(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; - on(event: "close", listener: () => void): this; - on(event: "connection", listener: (socket: Duplex) => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "listening", listener: () => void): this; - on(event: "checkContinue", listener: http.RequestListener): this; - on(event: "checkExpectation", listener: http.RequestListener): this; - on(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; - on(event: "connect", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; - on(event: "request", listener: http.RequestListener): this; - on(event: "upgrade", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; - once(event: string, listener: (...args: any[]) => void): this; - once(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; - once( - event: "newSession", - listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, - ): this; - once( - event: "OCSPRequest", - listener: ( - certificate: Buffer, - issuer: Buffer, - callback: (err: Error | null, resp: Buffer) => void, - ) => void, - ): this; - once( - event: "resumeSession", - listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, - ): this; - once(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; - once(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; - once(event: "close", listener: () => void): this; - once(event: "connection", listener: (socket: Duplex) => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "listening", listener: () => void): this; - once(event: "checkContinue", listener: http.RequestListener): this; - once(event: "checkExpectation", listener: http.RequestListener): this; - once(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; - once(event: "connect", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; - once(event: "request", listener: http.RequestListener): this; - once(event: "upgrade", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; - prependListener( - event: "newSession", - listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, - ): this; - prependListener( - event: "OCSPRequest", - listener: ( - certificate: Buffer, - issuer: Buffer, - callback: (err: Error | null, resp: Buffer) => void, - ) => void, - ): this; - prependListener( - event: "resumeSession", - listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, - ): this; - prependListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; - prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "connection", listener: (socket: Duplex) => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "listening", listener: () => void): this; - prependListener(event: "checkContinue", listener: http.RequestListener): this; - prependListener(event: "checkExpectation", listener: http.RequestListener): this; - prependListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; - prependListener( - event: "connect", - listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, - ): this; - prependListener(event: "request", listener: http.RequestListener): this; - prependListener( - event: "upgrade", - listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, - ): this; - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; - prependOnceListener( - event: "newSession", - listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, - ): this; - prependOnceListener( - event: "OCSPRequest", - listener: ( - certificate: Buffer, - issuer: Buffer, - callback: (err: Error | null, resp: Buffer) => void, - ) => void, - ): this; - prependOnceListener( - event: "resumeSession", - listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, - ): this; - prependOnceListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; - prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "connection", listener: (socket: Duplex) => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "listening", listener: () => void): this; - prependOnceListener(event: "checkContinue", listener: http.RequestListener): this; - prependOnceListener(event: "checkExpectation", listener: http.RequestListener): this; - prependOnceListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; - prependOnceListener( - event: "connect", - listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, - ): this; - prependOnceListener(event: "request", listener: http.RequestListener): this; - prependOnceListener( - event: "upgrade", - listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, - ): this; - } - /** - * ```js - * // curl -k https://localhost:8000/ - * const https = require('node:https'); - * const fs = require('node:fs'); - * - * const options = { - * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), - * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), - * }; - * - * https.createServer(options, (req, res) => { - * res.writeHead(200); - * res.end('hello world\n'); - * }).listen(8000); - * ``` - * - * Or - * - * ```js - * const https = require('node:https'); - * const fs = require('node:fs'); - * - * const options = { - * pfx: fs.readFileSync('test/fixtures/test_cert.pfx'), - * passphrase: 'sample', - * }; - * - * https.createServer(options, (req, res) => { - * res.writeHead(200); - * res.end('hello world\n'); - * }).listen(8000); - * ``` - * @since v0.3.4 - * @param options Accepts `options` from `createServer`, `createSecureContext` and `createServer`. - * @param requestListener A listener to be added to the `'request'` event. - */ - function createServer< - Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, - Response extends typeof http.ServerResponse = typeof http.ServerResponse, - >(requestListener?: http.RequestListener): Server; - function createServer< - Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, - Response extends typeof http.ServerResponse = typeof http.ServerResponse, - >( - options: ServerOptions, - requestListener?: http.RequestListener, - ): Server; - /** - * Makes a request to a secure web server. - * - * The following additional `options` from `tls.connect()` are also accepted:`ca`, `cert`, `ciphers`, `clientCertEngine`, `crl`, `dhparam`, `ecdhCurve`,`honorCipherOrder`, `key`, `passphrase`, - * `pfx`, `rejectUnauthorized`,`secureOptions`, `secureProtocol`, `servername`, `sessionIdContext`,`highWaterMark`. - * - * `options` can be an object, a string, or a `URL` object. If `options` is a - * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. - * - * `https.request()` returns an instance of the `http.ClientRequest` class. The `ClientRequest` instance is a writable stream. If one needs to - * upload a file with a POST request, then write to the `ClientRequest` object. - * - * ```js - * const https = require('node:https'); - * - * const options = { - * hostname: 'encrypted.google.com', - * port: 443, - * path: '/', - * method: 'GET', - * }; - * - * const req = https.request(options, (res) => { - * console.log('statusCode:', res.statusCode); - * console.log('headers:', res.headers); - * - * res.on('data', (d) => { - * process.stdout.write(d); - * }); - * }); - * - * req.on('error', (e) => { - * console.error(e); - * }); - * req.end(); - * ``` - * - * Example using options from `tls.connect()`: - * - * ```js - * const options = { - * hostname: 'encrypted.google.com', - * port: 443, - * path: '/', - * method: 'GET', - * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), - * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), - * }; - * options.agent = new https.Agent(options); - * - * const req = https.request(options, (res) => { - * // ... - * }); - * ``` - * - * Alternatively, opt out of connection pooling by not using an `Agent`. - * - * ```js - * const options = { - * hostname: 'encrypted.google.com', - * port: 443, - * path: '/', - * method: 'GET', - * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), - * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), - * agent: false, - * }; - * - * const req = https.request(options, (res) => { - * // ... - * }); - * ``` - * - * Example using a `URL` as `options`: - * - * ```js - * const options = new URL('https://abc:xyz@example.com'); - * - * const req = https.request(options, (res) => { - * // ... - * }); - * ``` - * - * Example pinning on certificate fingerprint, or the public key (similar to`pin-sha256`): - * - * ```js - * const tls = require('node:tls'); - * const https = require('node:https'); - * const crypto = require('node:crypto'); - * - * function sha256(s) { - * return crypto.createHash('sha256').update(s).digest('base64'); - * } - * const options = { - * hostname: 'github.com', - * port: 443, - * path: '/', - * method: 'GET', - * checkServerIdentity: function(host, cert) { - * // Make sure the certificate is issued to the host we are connected to - * const err = tls.checkServerIdentity(host, cert); - * if (err) { - * return err; - * } - * - * // Pin the public key, similar to HPKP pin-sha256 pinning - * const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU='; - * if (sha256(cert.pubkey) !== pubkey256) { - * const msg = 'Certificate verification error: ' + - * `The public key of '${cert.subject.CN}' ` + - * 'does not match our pinned fingerprint'; - * return new Error(msg); - * } - * - * // Pin the exact certificate, rather than the pub key - * const cert256 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' + - * 'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16'; - * if (cert.fingerprint256 !== cert256) { - * const msg = 'Certificate verification error: ' + - * `The certificate of '${cert.subject.CN}' ` + - * 'does not match our pinned fingerprint'; - * return new Error(msg); - * } - * - * // This loop is informational only. - * // Print the certificate and public key fingerprints of all certs in the - * // chain. Its common to pin the public key of the issuer on the public - * // internet, while pinning the public key of the service in sensitive - * // environments. - * do { - * console.log('Subject Common Name:', cert.subject.CN); - * console.log(' Certificate SHA256 fingerprint:', cert.fingerprint256); - * - * hash = crypto.createHash('sha256'); - * console.log(' Public key ping-sha256:', sha256(cert.pubkey)); - * - * lastprint256 = cert.fingerprint256; - * cert = cert.issuerCertificate; - * } while (cert.fingerprint256 !== lastprint256); - * - * }, - * }; - * - * options.agent = new https.Agent(options); - * const req = https.request(options, (res) => { - * console.log('All OK. Server matched our pinned cert or public key'); - * console.log('statusCode:', res.statusCode); - * // Print the HPKP values - * console.log('headers:', res.headers['public-key-pins']); - * - * res.on('data', (d) => {}); - * }); - * - * req.on('error', (e) => { - * console.error(e.message); - * }); - * req.end(); - * ``` - * - * Outputs for example: - * - * ```text - * Subject Common Name: github.com - * Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16 - * Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU= - * Subject Common Name: DigiCert SHA2 Extended Validation Server CA - * Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A - * Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho= - * Subject Common Name: DigiCert High Assurance EV Root CA - * Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF - * Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18= - * All OK. Server matched our pinned cert or public key - * statusCode: 200 - * headers: max-age=0; pin-sha256="WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18="; pin-sha256="RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho="; - * pin-sha256="k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws="; pin-sha256="K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q="; pin-sha256="IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4="; - * pin-sha256="iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0="; pin-sha256="LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A="; includeSubDomains - * ``` - * @since v0.3.6 - * @param options Accepts all `options` from `request`, with some differences in default values: - */ - function request( - options: RequestOptions | string | URL, - callback?: (res: http.IncomingMessage) => void, - ): http.ClientRequest; - function request( - url: string | URL, - options: RequestOptions, - callback?: (res: http.IncomingMessage) => void, - ): http.ClientRequest; - /** - * Like `http.get()` but for HTTPS. - * - * `options` can be an object, a string, or a `URL` object. If `options` is a - * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. - * - * ```js - * const https = require('node:https'); - * - * https.get('https://encrypted.google.com/', (res) => { - * console.log('statusCode:', res.statusCode); - * console.log('headers:', res.headers); - * - * res.on('data', (d) => { - * process.stdout.write(d); - * }); - * - * }).on('error', (e) => { - * console.error(e); - * }); - * ``` - * @since v0.3.6 - * @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`. - */ - function get( - options: RequestOptions | string | URL, - callback?: (res: http.IncomingMessage) => void, - ): http.ClientRequest; - function get( - url: string | URL, - options: RequestOptions, - callback?: (res: http.IncomingMessage) => void, - ): http.ClientRequest; - let globalAgent: Agent; -} -declare module "node:https" { - export * from "https"; -} diff --git a/node_modules/@types/node/ts4.8/index.d.ts b/node_modules/@types/node/ts4.8/index.d.ts deleted file mode 100644 index 7c8b38c6347655f38cc3d11fd9723f4bff9c790e..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/index.d.ts +++ /dev/null @@ -1,88 +0,0 @@ -/** - * License for programmatically and manually incorporated - * documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc - * - * Copyright Node.js contributors. All rights reserved. - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to - * deal in the Software without restriction, including without limitation the - * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or - * sell copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS - * IN THE SOFTWARE. - */ - -// NOTE: These definitions support NodeJS and TypeScript 4.8 and earlier. - -// Reference required types from the default lib: -/// -/// -/// -/// - -// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// - -/// diff --git a/node_modules/@types/node/ts4.8/inspector.d.ts b/node_modules/@types/node/ts4.8/inspector.d.ts deleted file mode 100644 index 3927b81603d1ed6b7185b943e8cef65102f8dfca..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/inspector.d.ts +++ /dev/null @@ -1,2747 +0,0 @@ -// Type definitions for inspector - -// These definitions are auto-generated. -// Please see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/19330 -// for more information. - - -/** - * The `node:inspector` module provides an API for interacting with the V8 - * inspector. - * - * It can be accessed using: - * - * ```js - * import * as inspector from 'node:inspector/promises'; - * ``` - * - * or - * - * ```js - * import * as inspector from 'node:inspector'; - * ``` - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/inspector.js) - */ -declare module 'inspector' { - import EventEmitter = require('node:events'); - interface InspectorNotification { - method: string; - params: T; - } - namespace Schema { - /** - * Description of the protocol domain. - */ - interface Domain { - /** - * Domain name. - */ - name: string; - /** - * Domain version. - */ - version: string; - } - interface GetDomainsReturnType { - /** - * List of supported domains. - */ - domains: Domain[]; - } - } - namespace Runtime { - /** - * Unique script identifier. - */ - type ScriptId = string; - /** - * Unique object identifier. - */ - type RemoteObjectId = string; - /** - * Primitive value which cannot be JSON-stringified. - */ - type UnserializableValue = string; - /** - * Mirror object referencing original JavaScript object. - */ - interface RemoteObject { - /** - * Object type. - */ - type: string; - /** - * Object subtype hint. Specified for object type values only. - */ - subtype?: string | undefined; - /** - * Object class (constructor) name. Specified for object type values only. - */ - className?: string | undefined; - /** - * Remote object value in case of primitive values or JSON values (if it was requested). - */ - value?: any; - /** - * Primitive value which can not be JSON-stringified does not have value, but gets this property. - */ - unserializableValue?: UnserializableValue | undefined; - /** - * String representation of the object. - */ - description?: string | undefined; - /** - * Unique object identifier (for non-primitive values). - */ - objectId?: RemoteObjectId | undefined; - /** - * Preview containing abbreviated property values. Specified for object type values only. - * @experimental - */ - preview?: ObjectPreview | undefined; - /** - * @experimental - */ - customPreview?: CustomPreview | undefined; - } - /** - * @experimental - */ - interface CustomPreview { - header: string; - hasBody: boolean; - formatterObjectId: RemoteObjectId; - bindRemoteObjectFunctionId: RemoteObjectId; - configObjectId?: RemoteObjectId | undefined; - } - /** - * Object containing abbreviated remote object value. - * @experimental - */ - interface ObjectPreview { - /** - * Object type. - */ - type: string; - /** - * Object subtype hint. Specified for object type values only. - */ - subtype?: string | undefined; - /** - * String representation of the object. - */ - description?: string | undefined; - /** - * True iff some of the properties or entries of the original object did not fit. - */ - overflow: boolean; - /** - * List of the properties. - */ - properties: PropertyPreview[]; - /** - * List of the entries. Specified for map and set subtype values only. - */ - entries?: EntryPreview[] | undefined; - } - /** - * @experimental - */ - interface PropertyPreview { - /** - * Property name. - */ - name: string; - /** - * Object type. Accessor means that the property itself is an accessor property. - */ - type: string; - /** - * User-friendly property value string. - */ - value?: string | undefined; - /** - * Nested value preview. - */ - valuePreview?: ObjectPreview | undefined; - /** - * Object subtype hint. Specified for object type values only. - */ - subtype?: string | undefined; - } - /** - * @experimental - */ - interface EntryPreview { - /** - * Preview of the key. Specified for map-like collection entries. - */ - key?: ObjectPreview | undefined; - /** - * Preview of the value. - */ - value: ObjectPreview; - } - /** - * Object property descriptor. - */ - interface PropertyDescriptor { - /** - * Property name or symbol description. - */ - name: string; - /** - * The value associated with the property. - */ - value?: RemoteObject | undefined; - /** - * True if the value associated with the property may be changed (data descriptors only). - */ - writable?: boolean | undefined; - /** - * A function which serves as a getter for the property, or undefined if there is no getter (accessor descriptors only). - */ - get?: RemoteObject | undefined; - /** - * A function which serves as a setter for the property, or undefined if there is no setter (accessor descriptors only). - */ - set?: RemoteObject | undefined; - /** - * True if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. - */ - configurable: boolean; - /** - * True if this property shows up during enumeration of the properties on the corresponding object. - */ - enumerable: boolean; - /** - * True if the result was thrown during the evaluation. - */ - wasThrown?: boolean | undefined; - /** - * True if the property is owned for the object. - */ - isOwn?: boolean | undefined; - /** - * Property symbol object, if the property is of the symbol type. - */ - symbol?: RemoteObject | undefined; - } - /** - * Object internal property descriptor. This property isn't normally visible in JavaScript code. - */ - interface InternalPropertyDescriptor { - /** - * Conventional property name. - */ - name: string; - /** - * The value associated with the property. - */ - value?: RemoteObject | undefined; - } - /** - * Represents function call argument. Either remote object id objectId, primitive value, unserializable primitive value or neither of (for undefined) them should be specified. - */ - interface CallArgument { - /** - * Primitive value or serializable javascript object. - */ - value?: any; - /** - * Primitive value which can not be JSON-stringified. - */ - unserializableValue?: UnserializableValue | undefined; - /** - * Remote object handle. - */ - objectId?: RemoteObjectId | undefined; - } - /** - * Id of an execution context. - */ - type ExecutionContextId = number; - /** - * Description of an isolated world. - */ - interface ExecutionContextDescription { - /** - * Unique id of the execution context. It can be used to specify in which execution context script evaluation should be performed. - */ - id: ExecutionContextId; - /** - * Execution context origin. - */ - origin: string; - /** - * Human readable name describing given context. - */ - name: string; - /** - * Embedder-specific auxiliary data. - */ - auxData?: {} | undefined; - } - /** - * Detailed information about exception (or error) that was thrown during script compilation or execution. - */ - interface ExceptionDetails { - /** - * Exception id. - */ - exceptionId: number; - /** - * Exception text, which should be used together with exception object when available. - */ - text: string; - /** - * Line number of the exception location (0-based). - */ - lineNumber: number; - /** - * Column number of the exception location (0-based). - */ - columnNumber: number; - /** - * Script ID of the exception location. - */ - scriptId?: ScriptId | undefined; - /** - * URL of the exception location, to be used when the script was not reported. - */ - url?: string | undefined; - /** - * JavaScript stack trace if available. - */ - stackTrace?: StackTrace | undefined; - /** - * Exception object if available. - */ - exception?: RemoteObject | undefined; - /** - * Identifier of the context where exception happened. - */ - executionContextId?: ExecutionContextId | undefined; - } - /** - * Number of milliseconds since epoch. - */ - type Timestamp = number; - /** - * Stack entry for runtime errors and assertions. - */ - interface CallFrame { - /** - * JavaScript function name. - */ - functionName: string; - /** - * JavaScript script id. - */ - scriptId: ScriptId; - /** - * JavaScript script name or url. - */ - url: string; - /** - * JavaScript script line number (0-based). - */ - lineNumber: number; - /** - * JavaScript script column number (0-based). - */ - columnNumber: number; - } - /** - * Call frames for assertions or error messages. - */ - interface StackTrace { - /** - * String label of this stack trace. For async traces this may be a name of the function that initiated the async call. - */ - description?: string | undefined; - /** - * JavaScript function name. - */ - callFrames: CallFrame[]; - /** - * Asynchronous JavaScript stack trace that preceded this stack, if available. - */ - parent?: StackTrace | undefined; - /** - * Asynchronous JavaScript stack trace that preceded this stack, if available. - * @experimental - */ - parentId?: StackTraceId | undefined; - } - /** - * Unique identifier of current debugger. - * @experimental - */ - type UniqueDebuggerId = string; - /** - * If debuggerId is set stack trace comes from another debugger and can be resolved there. This allows to track cross-debugger calls. See Runtime.StackTrace and Debugger.paused for usages. - * @experimental - */ - interface StackTraceId { - id: string; - debuggerId?: UniqueDebuggerId | undefined; - } - interface EvaluateParameterType { - /** - * Expression to evaluate. - */ - expression: string; - /** - * Symbolic group name that can be used to release multiple objects. - */ - objectGroup?: string | undefined; - /** - * Determines whether Command Line API should be available during the evaluation. - */ - includeCommandLineAPI?: boolean | undefined; - /** - * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. - */ - silent?: boolean | undefined; - /** - * Specifies in which execution context to perform evaluation. If the parameter is omitted the evaluation will be performed in the context of the inspected page. - */ - contextId?: ExecutionContextId | undefined; - /** - * Whether the result is expected to be a JSON object that should be sent by value. - */ - returnByValue?: boolean | undefined; - /** - * Whether preview should be generated for the result. - * @experimental - */ - generatePreview?: boolean | undefined; - /** - * Whether execution should be treated as initiated by user in the UI. - */ - userGesture?: boolean | undefined; - /** - * Whether execution should await for resulting value and return once awaited promise is resolved. - */ - awaitPromise?: boolean | undefined; - } - interface AwaitPromiseParameterType { - /** - * Identifier of the promise. - */ - promiseObjectId: RemoteObjectId; - /** - * Whether the result is expected to be a JSON object that should be sent by value. - */ - returnByValue?: boolean | undefined; - /** - * Whether preview should be generated for the result. - */ - generatePreview?: boolean | undefined; - } - interface CallFunctionOnParameterType { - /** - * Declaration of the function to call. - */ - functionDeclaration: string; - /** - * Identifier of the object to call function on. Either objectId or executionContextId should be specified. - */ - objectId?: RemoteObjectId | undefined; - /** - * Call arguments. All call arguments must belong to the same JavaScript world as the target object. - */ - arguments?: CallArgument[] | undefined; - /** - * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. - */ - silent?: boolean | undefined; - /** - * Whether the result is expected to be a JSON object which should be sent by value. - */ - returnByValue?: boolean | undefined; - /** - * Whether preview should be generated for the result. - * @experimental - */ - generatePreview?: boolean | undefined; - /** - * Whether execution should be treated as initiated by user in the UI. - */ - userGesture?: boolean | undefined; - /** - * Whether execution should await for resulting value and return once awaited promise is resolved. - */ - awaitPromise?: boolean | undefined; - /** - * Specifies execution context which global object will be used to call function on. Either executionContextId or objectId should be specified. - */ - executionContextId?: ExecutionContextId | undefined; - /** - * Symbolic group name that can be used to release multiple objects. If objectGroup is not specified and objectId is, objectGroup will be inherited from object. - */ - objectGroup?: string | undefined; - } - interface GetPropertiesParameterType { - /** - * Identifier of the object to return properties for. - */ - objectId: RemoteObjectId; - /** - * If true, returns properties belonging only to the element itself, not to its prototype chain. - */ - ownProperties?: boolean | undefined; - /** - * If true, returns accessor properties (with getter/setter) only; internal properties are not returned either. - * @experimental - */ - accessorPropertiesOnly?: boolean | undefined; - /** - * Whether preview should be generated for the results. - * @experimental - */ - generatePreview?: boolean | undefined; - } - interface ReleaseObjectParameterType { - /** - * Identifier of the object to release. - */ - objectId: RemoteObjectId; - } - interface ReleaseObjectGroupParameterType { - /** - * Symbolic object group name. - */ - objectGroup: string; - } - interface SetCustomObjectFormatterEnabledParameterType { - enabled: boolean; - } - interface CompileScriptParameterType { - /** - * Expression to compile. - */ - expression: string; - /** - * Source url to be set for the script. - */ - sourceURL: string; - /** - * Specifies whether the compiled script should be persisted. - */ - persistScript: boolean; - /** - * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. - */ - executionContextId?: ExecutionContextId | undefined; - } - interface RunScriptParameterType { - /** - * Id of the script to run. - */ - scriptId: ScriptId; - /** - * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. - */ - executionContextId?: ExecutionContextId | undefined; - /** - * Symbolic group name that can be used to release multiple objects. - */ - objectGroup?: string | undefined; - /** - * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. - */ - silent?: boolean | undefined; - /** - * Determines whether Command Line API should be available during the evaluation. - */ - includeCommandLineAPI?: boolean | undefined; - /** - * Whether the result is expected to be a JSON object which should be sent by value. - */ - returnByValue?: boolean | undefined; - /** - * Whether preview should be generated for the result. - */ - generatePreview?: boolean | undefined; - /** - * Whether execution should await for resulting value and return once awaited promise is resolved. - */ - awaitPromise?: boolean | undefined; - } - interface QueryObjectsParameterType { - /** - * Identifier of the prototype to return objects for. - */ - prototypeObjectId: RemoteObjectId; - } - interface GlobalLexicalScopeNamesParameterType { - /** - * Specifies in which execution context to lookup global scope variables. - */ - executionContextId?: ExecutionContextId | undefined; - } - interface EvaluateReturnType { - /** - * Evaluation result. - */ - result: RemoteObject; - /** - * Exception details. - */ - exceptionDetails?: ExceptionDetails | undefined; - } - interface AwaitPromiseReturnType { - /** - * Promise result. Will contain rejected value if promise was rejected. - */ - result: RemoteObject; - /** - * Exception details if stack strace is available. - */ - exceptionDetails?: ExceptionDetails | undefined; - } - interface CallFunctionOnReturnType { - /** - * Call result. - */ - result: RemoteObject; - /** - * Exception details. - */ - exceptionDetails?: ExceptionDetails | undefined; - } - interface GetPropertiesReturnType { - /** - * Object properties. - */ - result: PropertyDescriptor[]; - /** - * Internal object properties (only of the element itself). - */ - internalProperties?: InternalPropertyDescriptor[] | undefined; - /** - * Exception details. - */ - exceptionDetails?: ExceptionDetails | undefined; - } - interface CompileScriptReturnType { - /** - * Id of the script. - */ - scriptId?: ScriptId | undefined; - /** - * Exception details. - */ - exceptionDetails?: ExceptionDetails | undefined; - } - interface RunScriptReturnType { - /** - * Run result. - */ - result: RemoteObject; - /** - * Exception details. - */ - exceptionDetails?: ExceptionDetails | undefined; - } - interface QueryObjectsReturnType { - /** - * Array with objects. - */ - objects: RemoteObject; - } - interface GlobalLexicalScopeNamesReturnType { - names: string[]; - } - interface ExecutionContextCreatedEventDataType { - /** - * A newly created execution context. - */ - context: ExecutionContextDescription; - } - interface ExecutionContextDestroyedEventDataType { - /** - * Id of the destroyed context - */ - executionContextId: ExecutionContextId; - } - interface ExceptionThrownEventDataType { - /** - * Timestamp of the exception. - */ - timestamp: Timestamp; - exceptionDetails: ExceptionDetails; - } - interface ExceptionRevokedEventDataType { - /** - * Reason describing why exception was revoked. - */ - reason: string; - /** - * The id of revoked exception, as reported in exceptionThrown. - */ - exceptionId: number; - } - interface ConsoleAPICalledEventDataType { - /** - * Type of the call. - */ - type: string; - /** - * Call arguments. - */ - args: RemoteObject[]; - /** - * Identifier of the context where the call was made. - */ - executionContextId: ExecutionContextId; - /** - * Call timestamp. - */ - timestamp: Timestamp; - /** - * Stack trace captured when the call was made. - */ - stackTrace?: StackTrace | undefined; - /** - * Console context descriptor for calls on non-default console context (not console.*): 'anonymous#unique-logger-id' for call on unnamed context, 'name#unique-logger-id' for call on named context. - * @experimental - */ - context?: string | undefined; - } - interface InspectRequestedEventDataType { - object: RemoteObject; - hints: {}; - } - } - namespace Debugger { - /** - * Breakpoint identifier. - */ - type BreakpointId = string; - /** - * Call frame identifier. - */ - type CallFrameId = string; - /** - * Location in the source code. - */ - interface Location { - /** - * Script identifier as reported in the Debugger.scriptParsed. - */ - scriptId: Runtime.ScriptId; - /** - * Line number in the script (0-based). - */ - lineNumber: number; - /** - * Column number in the script (0-based). - */ - columnNumber?: number | undefined; - } - /** - * Location in the source code. - * @experimental - */ - interface ScriptPosition { - lineNumber: number; - columnNumber: number; - } - /** - * JavaScript call frame. Array of call frames form the call stack. - */ - interface CallFrame { - /** - * Call frame identifier. This identifier is only valid while the virtual machine is paused. - */ - callFrameId: CallFrameId; - /** - * Name of the JavaScript function called on this call frame. - */ - functionName: string; - /** - * Location in the source code. - */ - functionLocation?: Location | undefined; - /** - * Location in the source code. - */ - location: Location; - /** - * JavaScript script name or url. - */ - url: string; - /** - * Scope chain for this call frame. - */ - scopeChain: Scope[]; - /** - * this object for this call frame. - */ - this: Runtime.RemoteObject; - /** - * The value being returned, if the function is at return point. - */ - returnValue?: Runtime.RemoteObject | undefined; - } - /** - * Scope description. - */ - interface Scope { - /** - * Scope type. - */ - type: string; - /** - * Object representing the scope. For global and with scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties. - */ - object: Runtime.RemoteObject; - name?: string | undefined; - /** - * Location in the source code where scope starts - */ - startLocation?: Location | undefined; - /** - * Location in the source code where scope ends - */ - endLocation?: Location | undefined; - } - /** - * Search match for resource. - */ - interface SearchMatch { - /** - * Line number in resource content. - */ - lineNumber: number; - /** - * Line with match content. - */ - lineContent: string; - } - interface BreakLocation { - /** - * Script identifier as reported in the Debugger.scriptParsed. - */ - scriptId: Runtime.ScriptId; - /** - * Line number in the script (0-based). - */ - lineNumber: number; - /** - * Column number in the script (0-based). - */ - columnNumber?: number | undefined; - type?: string | undefined; - } - interface SetBreakpointsActiveParameterType { - /** - * New value for breakpoints active state. - */ - active: boolean; - } - interface SetSkipAllPausesParameterType { - /** - * New value for skip pauses state. - */ - skip: boolean; - } - interface SetBreakpointByUrlParameterType { - /** - * Line number to set breakpoint at. - */ - lineNumber: number; - /** - * URL of the resources to set breakpoint on. - */ - url?: string | undefined; - /** - * Regex pattern for the URLs of the resources to set breakpoints on. Either url or urlRegex must be specified. - */ - urlRegex?: string | undefined; - /** - * Script hash of the resources to set breakpoint on. - */ - scriptHash?: string | undefined; - /** - * Offset in the line to set breakpoint at. - */ - columnNumber?: number | undefined; - /** - * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. - */ - condition?: string | undefined; - } - interface SetBreakpointParameterType { - /** - * Location to set breakpoint in. - */ - location: Location; - /** - * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. - */ - condition?: string | undefined; - } - interface RemoveBreakpointParameterType { - breakpointId: BreakpointId; - } - interface GetPossibleBreakpointsParameterType { - /** - * Start of range to search possible breakpoint locations in. - */ - start: Location; - /** - * End of range to search possible breakpoint locations in (excluding). When not specified, end of scripts is used as end of range. - */ - end?: Location | undefined; - /** - * Only consider locations which are in the same (non-nested) function as start. - */ - restrictToFunction?: boolean | undefined; - } - interface ContinueToLocationParameterType { - /** - * Location to continue to. - */ - location: Location; - targetCallFrames?: string | undefined; - } - interface PauseOnAsyncCallParameterType { - /** - * Debugger will pause when async call with given stack trace is started. - */ - parentStackTraceId: Runtime.StackTraceId; - } - interface StepIntoParameterType { - /** - * Debugger will issue additional Debugger.paused notification if any async task is scheduled before next pause. - * @experimental - */ - breakOnAsyncCall?: boolean | undefined; - } - interface GetStackTraceParameterType { - stackTraceId: Runtime.StackTraceId; - } - interface SearchInContentParameterType { - /** - * Id of the script to search in. - */ - scriptId: Runtime.ScriptId; - /** - * String to search for. - */ - query: string; - /** - * If true, search is case sensitive. - */ - caseSensitive?: boolean | undefined; - /** - * If true, treats string parameter as regex. - */ - isRegex?: boolean | undefined; - } - interface SetScriptSourceParameterType { - /** - * Id of the script to edit. - */ - scriptId: Runtime.ScriptId; - /** - * New content of the script. - */ - scriptSource: string; - /** - * If true the change will not actually be applied. Dry run may be used to get result description without actually modifying the code. - */ - dryRun?: boolean | undefined; - } - interface RestartFrameParameterType { - /** - * Call frame identifier to evaluate on. - */ - callFrameId: CallFrameId; - } - interface GetScriptSourceParameterType { - /** - * Id of the script to get source for. - */ - scriptId: Runtime.ScriptId; - } - interface SetPauseOnExceptionsParameterType { - /** - * Pause on exceptions mode. - */ - state: string; - } - interface EvaluateOnCallFrameParameterType { - /** - * Call frame identifier to evaluate on. - */ - callFrameId: CallFrameId; - /** - * Expression to evaluate. - */ - expression: string; - /** - * String object group name to put result into (allows rapid releasing resulting object handles using releaseObjectGroup). - */ - objectGroup?: string | undefined; - /** - * Specifies whether command line API should be available to the evaluated expression, defaults to false. - */ - includeCommandLineAPI?: boolean | undefined; - /** - * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. - */ - silent?: boolean | undefined; - /** - * Whether the result is expected to be a JSON object that should be sent by value. - */ - returnByValue?: boolean | undefined; - /** - * Whether preview should be generated for the result. - * @experimental - */ - generatePreview?: boolean | undefined; - /** - * Whether to throw an exception if side effect cannot be ruled out during evaluation. - */ - throwOnSideEffect?: boolean | undefined; - } - interface SetVariableValueParameterType { - /** - * 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' scope types are allowed. Other scopes could be manipulated manually. - */ - scopeNumber: number; - /** - * Variable name. - */ - variableName: string; - /** - * New variable value. - */ - newValue: Runtime.CallArgument; - /** - * Id of callframe that holds variable. - */ - callFrameId: CallFrameId; - } - interface SetReturnValueParameterType { - /** - * New return value. - */ - newValue: Runtime.CallArgument; - } - interface SetAsyncCallStackDepthParameterType { - /** - * Maximum depth of async call stacks. Setting to 0 will effectively disable collecting async call stacks (default). - */ - maxDepth: number; - } - interface SetBlackboxPatternsParameterType { - /** - * Array of regexps that will be used to check script url for blackbox state. - */ - patterns: string[]; - } - interface SetBlackboxedRangesParameterType { - /** - * Id of the script. - */ - scriptId: Runtime.ScriptId; - positions: ScriptPosition[]; - } - interface EnableReturnType { - /** - * Unique identifier of the debugger. - * @experimental - */ - debuggerId: Runtime.UniqueDebuggerId; - } - interface SetBreakpointByUrlReturnType { - /** - * Id of the created breakpoint for further reference. - */ - breakpointId: BreakpointId; - /** - * List of the locations this breakpoint resolved into upon addition. - */ - locations: Location[]; - } - interface SetBreakpointReturnType { - /** - * Id of the created breakpoint for further reference. - */ - breakpointId: BreakpointId; - /** - * Location this breakpoint resolved into. - */ - actualLocation: Location; - } - interface GetPossibleBreakpointsReturnType { - /** - * List of the possible breakpoint locations. - */ - locations: BreakLocation[]; - } - interface GetStackTraceReturnType { - stackTrace: Runtime.StackTrace; - } - interface SearchInContentReturnType { - /** - * List of search matches. - */ - result: SearchMatch[]; - } - interface SetScriptSourceReturnType { - /** - * New stack trace in case editing has happened while VM was stopped. - */ - callFrames?: CallFrame[] | undefined; - /** - * Whether current call stack was modified after applying the changes. - */ - stackChanged?: boolean | undefined; - /** - * Async stack trace, if any. - */ - asyncStackTrace?: Runtime.StackTrace | undefined; - /** - * Async stack trace, if any. - * @experimental - */ - asyncStackTraceId?: Runtime.StackTraceId | undefined; - /** - * Exception details if any. - */ - exceptionDetails?: Runtime.ExceptionDetails | undefined; - } - interface RestartFrameReturnType { - /** - * New stack trace. - */ - callFrames: CallFrame[]; - /** - * Async stack trace, if any. - */ - asyncStackTrace?: Runtime.StackTrace | undefined; - /** - * Async stack trace, if any. - * @experimental - */ - asyncStackTraceId?: Runtime.StackTraceId | undefined; - } - interface GetScriptSourceReturnType { - /** - * Script source. - */ - scriptSource: string; - } - interface EvaluateOnCallFrameReturnType { - /** - * Object wrapper for the evaluation result. - */ - result: Runtime.RemoteObject; - /** - * Exception details. - */ - exceptionDetails?: Runtime.ExceptionDetails | undefined; - } - interface ScriptParsedEventDataType { - /** - * Identifier of the script parsed. - */ - scriptId: Runtime.ScriptId; - /** - * URL or name of the script parsed (if any). - */ - url: string; - /** - * Line offset of the script within the resource with given URL (for script tags). - */ - startLine: number; - /** - * Column offset of the script within the resource with given URL. - */ - startColumn: number; - /** - * Last line of the script. - */ - endLine: number; - /** - * Length of the last line of the script. - */ - endColumn: number; - /** - * Specifies script creation context. - */ - executionContextId: Runtime.ExecutionContextId; - /** - * Content hash of the script. - */ - hash: string; - /** - * Embedder-specific auxiliary data. - */ - executionContextAuxData?: {} | undefined; - /** - * True, if this script is generated as a result of the live edit operation. - * @experimental - */ - isLiveEdit?: boolean | undefined; - /** - * URL of source map associated with script (if any). - */ - sourceMapURL?: string | undefined; - /** - * True, if this script has sourceURL. - */ - hasSourceURL?: boolean | undefined; - /** - * True, if this script is ES6 module. - */ - isModule?: boolean | undefined; - /** - * This script length. - */ - length?: number | undefined; - /** - * JavaScript top stack frame of where the script parsed event was triggered if available. - * @experimental - */ - stackTrace?: Runtime.StackTrace | undefined; - } - interface ScriptFailedToParseEventDataType { - /** - * Identifier of the script parsed. - */ - scriptId: Runtime.ScriptId; - /** - * URL or name of the script parsed (if any). - */ - url: string; - /** - * Line offset of the script within the resource with given URL (for script tags). - */ - startLine: number; - /** - * Column offset of the script within the resource with given URL. - */ - startColumn: number; - /** - * Last line of the script. - */ - endLine: number; - /** - * Length of the last line of the script. - */ - endColumn: number; - /** - * Specifies script creation context. - */ - executionContextId: Runtime.ExecutionContextId; - /** - * Content hash of the script. - */ - hash: string; - /** - * Embedder-specific auxiliary data. - */ - executionContextAuxData?: {} | undefined; - /** - * URL of source map associated with script (if any). - */ - sourceMapURL?: string | undefined; - /** - * True, if this script has sourceURL. - */ - hasSourceURL?: boolean | undefined; - /** - * True, if this script is ES6 module. - */ - isModule?: boolean | undefined; - /** - * This script length. - */ - length?: number | undefined; - /** - * JavaScript top stack frame of where the script parsed event was triggered if available. - * @experimental - */ - stackTrace?: Runtime.StackTrace | undefined; - } - interface BreakpointResolvedEventDataType { - /** - * Breakpoint unique identifier. - */ - breakpointId: BreakpointId; - /** - * Actual breakpoint location. - */ - location: Location; - } - interface PausedEventDataType { - /** - * Call stack the virtual machine stopped on. - */ - callFrames: CallFrame[]; - /** - * Pause reason. - */ - reason: string; - /** - * Object containing break-specific auxiliary properties. - */ - data?: {} | undefined; - /** - * Hit breakpoints IDs - */ - hitBreakpoints?: string[] | undefined; - /** - * Async stack trace, if any. - */ - asyncStackTrace?: Runtime.StackTrace | undefined; - /** - * Async stack trace, if any. - * @experimental - */ - asyncStackTraceId?: Runtime.StackTraceId | undefined; - /** - * Just scheduled async call will have this stack trace as parent stack during async execution. This field is available only after Debugger.stepInto call with breakOnAsynCall flag. - * @experimental - */ - asyncCallStackTraceId?: Runtime.StackTraceId | undefined; - } - } - namespace Console { - /** - * Console message. - */ - interface ConsoleMessage { - /** - * Message source. - */ - source: string; - /** - * Message severity. - */ - level: string; - /** - * Message text. - */ - text: string; - /** - * URL of the message origin. - */ - url?: string | undefined; - /** - * Line number in the resource that generated this message (1-based). - */ - line?: number | undefined; - /** - * Column number in the resource that generated this message (1-based). - */ - column?: number | undefined; - } - interface MessageAddedEventDataType { - /** - * Console message that has been added. - */ - message: ConsoleMessage; - } - } - namespace Profiler { - /** - * Profile node. Holds callsite information, execution statistics and child nodes. - */ - interface ProfileNode { - /** - * Unique id of the node. - */ - id: number; - /** - * Function location. - */ - callFrame: Runtime.CallFrame; - /** - * Number of samples where this node was on top of the call stack. - */ - hitCount?: number | undefined; - /** - * Child node ids. - */ - children?: number[] | undefined; - /** - * The reason of being not optimized. The function may be deoptimized or marked as don't optimize. - */ - deoptReason?: string | undefined; - /** - * An array of source position ticks. - */ - positionTicks?: PositionTickInfo[] | undefined; - } - /** - * Profile. - */ - interface Profile { - /** - * The list of profile nodes. First item is the root node. - */ - nodes: ProfileNode[]; - /** - * Profiling start timestamp in microseconds. - */ - startTime: number; - /** - * Profiling end timestamp in microseconds. - */ - endTime: number; - /** - * Ids of samples top nodes. - */ - samples?: number[] | undefined; - /** - * Time intervals between adjacent samples in microseconds. The first delta is relative to the profile startTime. - */ - timeDeltas?: number[] | undefined; - } - /** - * Specifies a number of samples attributed to a certain source position. - */ - interface PositionTickInfo { - /** - * Source line number (1-based). - */ - line: number; - /** - * Number of samples attributed to the source line. - */ - ticks: number; - } - /** - * Coverage data for a source range. - */ - interface CoverageRange { - /** - * JavaScript script source offset for the range start. - */ - startOffset: number; - /** - * JavaScript script source offset for the range end. - */ - endOffset: number; - /** - * Collected execution count of the source range. - */ - count: number; - } - /** - * Coverage data for a JavaScript function. - */ - interface FunctionCoverage { - /** - * JavaScript function name. - */ - functionName: string; - /** - * Source ranges inside the function with coverage data. - */ - ranges: CoverageRange[]; - /** - * Whether coverage data for this function has block granularity. - */ - isBlockCoverage: boolean; - } - /** - * Coverage data for a JavaScript script. - */ - interface ScriptCoverage { - /** - * JavaScript script id. - */ - scriptId: Runtime.ScriptId; - /** - * JavaScript script name or url. - */ - url: string; - /** - * Functions contained in the script that has coverage data. - */ - functions: FunctionCoverage[]; - } - /** - * Describes a type collected during runtime. - * @experimental - */ - interface TypeObject { - /** - * Name of a type collected with type profiling. - */ - name: string; - } - /** - * Source offset and types for a parameter or return value. - * @experimental - */ - interface TypeProfileEntry { - /** - * Source offset of the parameter or end of function for return values. - */ - offset: number; - /** - * The types for this parameter or return value. - */ - types: TypeObject[]; - } - /** - * Type profile data collected during runtime for a JavaScript script. - * @experimental - */ - interface ScriptTypeProfile { - /** - * JavaScript script id. - */ - scriptId: Runtime.ScriptId; - /** - * JavaScript script name or url. - */ - url: string; - /** - * Type profile entries for parameters and return values of the functions in the script. - */ - entries: TypeProfileEntry[]; - } - interface SetSamplingIntervalParameterType { - /** - * New sampling interval in microseconds. - */ - interval: number; - } - interface StartPreciseCoverageParameterType { - /** - * Collect accurate call counts beyond simple 'covered' or 'not covered'. - */ - callCount?: boolean | undefined; - /** - * Collect block-based coverage. - */ - detailed?: boolean | undefined; - } - interface StopReturnType { - /** - * Recorded profile. - */ - profile: Profile; - } - interface TakePreciseCoverageReturnType { - /** - * Coverage data for the current isolate. - */ - result: ScriptCoverage[]; - } - interface GetBestEffortCoverageReturnType { - /** - * Coverage data for the current isolate. - */ - result: ScriptCoverage[]; - } - interface TakeTypeProfileReturnType { - /** - * Type profile for all scripts since startTypeProfile() was turned on. - */ - result: ScriptTypeProfile[]; - } - interface ConsoleProfileStartedEventDataType { - id: string; - /** - * Location of console.profile(). - */ - location: Debugger.Location; - /** - * Profile title passed as an argument to console.profile(). - */ - title?: string | undefined; - } - interface ConsoleProfileFinishedEventDataType { - id: string; - /** - * Location of console.profileEnd(). - */ - location: Debugger.Location; - profile: Profile; - /** - * Profile title passed as an argument to console.profile(). - */ - title?: string | undefined; - } - } - namespace HeapProfiler { - /** - * Heap snapshot object id. - */ - type HeapSnapshotObjectId = string; - /** - * Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes. - */ - interface SamplingHeapProfileNode { - /** - * Function location. - */ - callFrame: Runtime.CallFrame; - /** - * Allocations size in bytes for the node excluding children. - */ - selfSize: number; - /** - * Child nodes. - */ - children: SamplingHeapProfileNode[]; - } - /** - * Profile. - */ - interface SamplingHeapProfile { - head: SamplingHeapProfileNode; - } - interface StartTrackingHeapObjectsParameterType { - trackAllocations?: boolean | undefined; - } - interface StopTrackingHeapObjectsParameterType { - /** - * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken when the tracking is stopped. - */ - reportProgress?: boolean | undefined; - } - interface TakeHeapSnapshotParameterType { - /** - * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken. - */ - reportProgress?: boolean | undefined; - } - interface GetObjectByHeapObjectIdParameterType { - objectId: HeapSnapshotObjectId; - /** - * Symbolic group name that can be used to release multiple objects. - */ - objectGroup?: string | undefined; - } - interface AddInspectedHeapObjectParameterType { - /** - * Heap snapshot object id to be accessible by means of $x command line API. - */ - heapObjectId: HeapSnapshotObjectId; - } - interface GetHeapObjectIdParameterType { - /** - * Identifier of the object to get heap object id for. - */ - objectId: Runtime.RemoteObjectId; - } - interface StartSamplingParameterType { - /** - * Average sample interval in bytes. Poisson distribution is used for the intervals. The default value is 32768 bytes. - */ - samplingInterval?: number | undefined; - } - interface GetObjectByHeapObjectIdReturnType { - /** - * Evaluation result. - */ - result: Runtime.RemoteObject; - } - interface GetHeapObjectIdReturnType { - /** - * Id of the heap snapshot object corresponding to the passed remote object id. - */ - heapSnapshotObjectId: HeapSnapshotObjectId; - } - interface StopSamplingReturnType { - /** - * Recorded sampling heap profile. - */ - profile: SamplingHeapProfile; - } - interface GetSamplingProfileReturnType { - /** - * Return the sampling profile being collected. - */ - profile: SamplingHeapProfile; - } - interface AddHeapSnapshotChunkEventDataType { - chunk: string; - } - interface ReportHeapSnapshotProgressEventDataType { - done: number; - total: number; - finished?: boolean | undefined; - } - interface LastSeenObjectIdEventDataType { - lastSeenObjectId: number; - timestamp: number; - } - interface HeapStatsUpdateEventDataType { - /** - * An array of triplets. Each triplet describes a fragment. The first integer is the fragment index, the second integer is a total count of objects for the fragment, the third integer is a total size of the objects for the fragment. - */ - statsUpdate: number[]; - } - } - namespace NodeTracing { - interface TraceConfig { - /** - * Controls how the trace buffer stores data. - */ - recordMode?: string | undefined; - /** - * Included category filters. - */ - includedCategories: string[]; - } - interface StartParameterType { - traceConfig: TraceConfig; - } - interface GetCategoriesReturnType { - /** - * A list of supported tracing categories. - */ - categories: string[]; - } - interface DataCollectedEventDataType { - value: Array<{}>; - } - } - namespace NodeWorker { - type WorkerID = string; - /** - * Unique identifier of attached debugging session. - */ - type SessionID = string; - interface WorkerInfo { - workerId: WorkerID; - type: string; - title: string; - url: string; - } - interface SendMessageToWorkerParameterType { - message: string; - /** - * Identifier of the session. - */ - sessionId: SessionID; - } - interface EnableParameterType { - /** - * Whether to new workers should be paused until the frontend sends `Runtime.runIfWaitingForDebugger` - * message to run them. - */ - waitForDebuggerOnStart: boolean; - } - interface DetachParameterType { - sessionId: SessionID; - } - interface AttachedToWorkerEventDataType { - /** - * Identifier assigned to the session used to send/receive messages. - */ - sessionId: SessionID; - workerInfo: WorkerInfo; - waitingForDebugger: boolean; - } - interface DetachedFromWorkerEventDataType { - /** - * Detached session identifier. - */ - sessionId: SessionID; - } - interface ReceivedMessageFromWorkerEventDataType { - /** - * Identifier of a session which sends a message. - */ - sessionId: SessionID; - message: string; - } - } - namespace NodeRuntime { - interface NotifyWhenWaitingForDisconnectParameterType { - enabled: boolean; - } - } - /** - * The `inspector.Session` is used for dispatching messages to the V8 inspector - * back-end and receiving message responses and notifications. - */ - class Session extends EventEmitter { - /** - * Create a new instance of the inspector.Session class. - * The inspector session needs to be connected through session.connect() before the messages can be dispatched to the inspector backend. - */ - constructor(); - /** - * Connects a session to the inspector back-end. - * @since v8.0.0 - */ - connect(): void; - /** - * Immediately close the session. All pending message callbacks will be called - * with an error. `session.connect()` will need to be called to be able to send - * messages again. Reconnected session will lose all inspector state, such as - * enabled agents or configured breakpoints. - * @since v8.0.0 - */ - disconnect(): void; - /** - * Posts a message to the inspector back-end. `callback` will be notified when - * a response is received. `callback` is a function that accepts two optional - * arguments: error and message-specific result. - * - * ```js - * session.post('Runtime.evaluate', { expression: '2 + 2' }, - * (error, { result }) => console.log(result)); - * // Output: { type: 'number', value: 4, description: '4' } - * ``` - * - * The latest version of the V8 inspector protocol is published on the [Chrome DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/v8/). - * - * Node.js inspector supports all the Chrome DevTools Protocol domains declared - * by V8\. Chrome DevTools Protocol domain provides an interface for interacting - * with one of the runtime agents used to inspect the application state and listen - * to the run-time events. - * - * ## Example usage - * - * Apart from the debugger, various V8 Profilers are available through the DevTools - * protocol. - * @since v8.0.0 - */ - post(method: string, params?: {}, callback?: (err: Error | null, params?: {}) => void): void; - post(method: string, callback?: (err: Error | null, params?: {}) => void): void; - /** - * Returns supported domains. - */ - post(method: 'Schema.getDomains', callback?: (err: Error | null, params: Schema.GetDomainsReturnType) => void): void; - /** - * Evaluates expression on global object. - */ - post(method: 'Runtime.evaluate', params?: Runtime.EvaluateParameterType, callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; - post(method: 'Runtime.evaluate', callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; - /** - * Add handler to promise with given promise object id. - */ - post(method: 'Runtime.awaitPromise', params?: Runtime.AwaitPromiseParameterType, callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; - post(method: 'Runtime.awaitPromise', callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; - /** - * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. - */ - post(method: 'Runtime.callFunctionOn', params?: Runtime.CallFunctionOnParameterType, callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; - post(method: 'Runtime.callFunctionOn', callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; - /** - * Returns properties of a given object. Object group of the result is inherited from the target object. - */ - post(method: 'Runtime.getProperties', params?: Runtime.GetPropertiesParameterType, callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; - post(method: 'Runtime.getProperties', callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; - /** - * Releases remote object with given id. - */ - post(method: 'Runtime.releaseObject', params?: Runtime.ReleaseObjectParameterType, callback?: (err: Error | null) => void): void; - post(method: 'Runtime.releaseObject', callback?: (err: Error | null) => void): void; - /** - * Releases all remote objects that belong to a given group. - */ - post(method: 'Runtime.releaseObjectGroup', params?: Runtime.ReleaseObjectGroupParameterType, callback?: (err: Error | null) => void): void; - post(method: 'Runtime.releaseObjectGroup', callback?: (err: Error | null) => void): void; - /** - * Tells inspected instance to run if it was waiting for debugger to attach. - */ - post(method: 'Runtime.runIfWaitingForDebugger', callback?: (err: Error | null) => void): void; - /** - * Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context. - */ - post(method: 'Runtime.enable', callback?: (err: Error | null) => void): void; - /** - * Disables reporting of execution contexts creation. - */ - post(method: 'Runtime.disable', callback?: (err: Error | null) => void): void; - /** - * Discards collected exceptions and console API calls. - */ - post(method: 'Runtime.discardConsoleEntries', callback?: (err: Error | null) => void): void; - /** - * @experimental - */ - post(method: 'Runtime.setCustomObjectFormatterEnabled', params?: Runtime.SetCustomObjectFormatterEnabledParameterType, callback?: (err: Error | null) => void): void; - post(method: 'Runtime.setCustomObjectFormatterEnabled', callback?: (err: Error | null) => void): void; - /** - * Compiles expression. - */ - post(method: 'Runtime.compileScript', params?: Runtime.CompileScriptParameterType, callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; - post(method: 'Runtime.compileScript', callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; - /** - * Runs script with given id in a given context. - */ - post(method: 'Runtime.runScript', params?: Runtime.RunScriptParameterType, callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; - post(method: 'Runtime.runScript', callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; - post(method: 'Runtime.queryObjects', params?: Runtime.QueryObjectsParameterType, callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; - post(method: 'Runtime.queryObjects', callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; - /** - * Returns all let, const and class variables from global scope. - */ - post( - method: 'Runtime.globalLexicalScopeNames', - params?: Runtime.GlobalLexicalScopeNamesParameterType, - callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void - ): void; - post(method: 'Runtime.globalLexicalScopeNames', callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void): void; - /** - * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. - */ - post(method: 'Debugger.enable', callback?: (err: Error | null, params: Debugger.EnableReturnType) => void): void; - /** - * Disables debugger for given page. - */ - post(method: 'Debugger.disable', callback?: (err: Error | null) => void): void; - /** - * Activates / deactivates all breakpoints on the page. - */ - post(method: 'Debugger.setBreakpointsActive', params?: Debugger.SetBreakpointsActiveParameterType, callback?: (err: Error | null) => void): void; - post(method: 'Debugger.setBreakpointsActive', callback?: (err: Error | null) => void): void; - /** - * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). - */ - post(method: 'Debugger.setSkipAllPauses', params?: Debugger.SetSkipAllPausesParameterType, callback?: (err: Error | null) => void): void; - post(method: 'Debugger.setSkipAllPauses', callback?: (err: Error | null) => void): void; - /** - * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads. - */ - post(method: 'Debugger.setBreakpointByUrl', params?: Debugger.SetBreakpointByUrlParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; - post(method: 'Debugger.setBreakpointByUrl', callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; - /** - * Sets JavaScript breakpoint at a given location. - */ - post(method: 'Debugger.setBreakpoint', params?: Debugger.SetBreakpointParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; - post(method: 'Debugger.setBreakpoint', callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; - /** - * Removes JavaScript breakpoint. - */ - post(method: 'Debugger.removeBreakpoint', params?: Debugger.RemoveBreakpointParameterType, callback?: (err: Error | null) => void): void; - post(method: 'Debugger.removeBreakpoint', callback?: (err: Error | null) => void): void; - /** - * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. - */ - post( - method: 'Debugger.getPossibleBreakpoints', - params?: Debugger.GetPossibleBreakpointsParameterType, - callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void - ): void; - post(method: 'Debugger.getPossibleBreakpoints', callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void): void; - /** - * Continues execution until specific location is reached. - */ - post(method: 'Debugger.continueToLocation', params?: Debugger.ContinueToLocationParameterType, callback?: (err: Error | null) => void): void; - post(method: 'Debugger.continueToLocation', callback?: (err: Error | null) => void): void; - /** - * @experimental - */ - post(method: 'Debugger.pauseOnAsyncCall', params?: Debugger.PauseOnAsyncCallParameterType, callback?: (err: Error | null) => void): void; - post(method: 'Debugger.pauseOnAsyncCall', callback?: (err: Error | null) => void): void; - /** - * Steps over the statement. - */ - post(method: 'Debugger.stepOver', callback?: (err: Error | null) => void): void; - /** - * Steps into the function call. - */ - post(method: 'Debugger.stepInto', params?: Debugger.StepIntoParameterType, callback?: (err: Error | null) => void): void; - post(method: 'Debugger.stepInto', callback?: (err: Error | null) => void): void; - /** - * Steps out of the function call. - */ - post(method: 'Debugger.stepOut', callback?: (err: Error | null) => void): void; - /** - * Stops on the next JavaScript statement. - */ - post(method: 'Debugger.pause', callback?: (err: Error | null) => void): void; - /** - * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. - * @experimental - */ - post(method: 'Debugger.scheduleStepIntoAsync', callback?: (err: Error | null) => void): void; - /** - * Resumes JavaScript execution. - */ - post(method: 'Debugger.resume', callback?: (err: Error | null) => void): void; - /** - * Returns stack trace with given stackTraceId. - * @experimental - */ - post(method: 'Debugger.getStackTrace', params?: Debugger.GetStackTraceParameterType, callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; - post(method: 'Debugger.getStackTrace', callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; - /** - * Searches for given string in script content. - */ - post(method: 'Debugger.searchInContent', params?: Debugger.SearchInContentParameterType, callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; - post(method: 'Debugger.searchInContent', callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; - /** - * Edits JavaScript source live. - */ - post(method: 'Debugger.setScriptSource', params?: Debugger.SetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; - post(method: 'Debugger.setScriptSource', callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; - /** - * Restarts particular call frame from the beginning. - */ - post(method: 'Debugger.restartFrame', params?: Debugger.RestartFrameParameterType, callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; - post(method: 'Debugger.restartFrame', callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; - /** - * Returns source for the script with given id. - */ - post(method: 'Debugger.getScriptSource', params?: Debugger.GetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; - post(method: 'Debugger.getScriptSource', callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; - /** - * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none. - */ - post(method: 'Debugger.setPauseOnExceptions', params?: Debugger.SetPauseOnExceptionsParameterType, callback?: (err: Error | null) => void): void; - post(method: 'Debugger.setPauseOnExceptions', callback?: (err: Error | null) => void): void; - /** - * Evaluates expression on a given call frame. - */ - post(method: 'Debugger.evaluateOnCallFrame', params?: Debugger.EvaluateOnCallFrameParameterType, callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; - post(method: 'Debugger.evaluateOnCallFrame', callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; - /** - * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. - */ - post(method: 'Debugger.setVariableValue', params?: Debugger.SetVariableValueParameterType, callback?: (err: Error | null) => void): void; - post(method: 'Debugger.setVariableValue', callback?: (err: Error | null) => void): void; - /** - * Changes return value in top frame. Available only at return break position. - * @experimental - */ - post(method: 'Debugger.setReturnValue', params?: Debugger.SetReturnValueParameterType, callback?: (err: Error | null) => void): void; - post(method: 'Debugger.setReturnValue', callback?: (err: Error | null) => void): void; - /** - * Enables or disables async call stacks tracking. - */ - post(method: 'Debugger.setAsyncCallStackDepth', params?: Debugger.SetAsyncCallStackDepthParameterType, callback?: (err: Error | null) => void): void; - post(method: 'Debugger.setAsyncCallStackDepth', callback?: (err: Error | null) => void): void; - /** - * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. - * @experimental - */ - post(method: 'Debugger.setBlackboxPatterns', params?: Debugger.SetBlackboxPatternsParameterType, callback?: (err: Error | null) => void): void; - post(method: 'Debugger.setBlackboxPatterns', callback?: (err: Error | null) => void): void; - /** - * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. - * @experimental - */ - post(method: 'Debugger.setBlackboxedRanges', params?: Debugger.SetBlackboxedRangesParameterType, callback?: (err: Error | null) => void): void; - post(method: 'Debugger.setBlackboxedRanges', callback?: (err: Error | null) => void): void; - /** - * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. - */ - post(method: 'Console.enable', callback?: (err: Error | null) => void): void; - /** - * Disables console domain, prevents further console messages from being reported to the client. - */ - post(method: 'Console.disable', callback?: (err: Error | null) => void): void; - /** - * Does nothing. - */ - post(method: 'Console.clearMessages', callback?: (err: Error | null) => void): void; - post(method: 'Profiler.enable', callback?: (err: Error | null) => void): void; - post(method: 'Profiler.disable', callback?: (err: Error | null) => void): void; - /** - * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. - */ - post(method: 'Profiler.setSamplingInterval', params?: Profiler.SetSamplingIntervalParameterType, callback?: (err: Error | null) => void): void; - post(method: 'Profiler.setSamplingInterval', callback?: (err: Error | null) => void): void; - post(method: 'Profiler.start', callback?: (err: Error | null) => void): void; - post(method: 'Profiler.stop', callback?: (err: Error | null, params: Profiler.StopReturnType) => void): void; - /** - * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. - */ - post(method: 'Profiler.startPreciseCoverage', params?: Profiler.StartPreciseCoverageParameterType, callback?: (err: Error | null) => void): void; - post(method: 'Profiler.startPreciseCoverage', callback?: (err: Error | null) => void): void; - /** - * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. - */ - post(method: 'Profiler.stopPreciseCoverage', callback?: (err: Error | null) => void): void; - /** - * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. - */ - post(method: 'Profiler.takePreciseCoverage', callback?: (err: Error | null, params: Profiler.TakePreciseCoverageReturnType) => void): void; - /** - * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. - */ - post(method: 'Profiler.getBestEffortCoverage', callback?: (err: Error | null, params: Profiler.GetBestEffortCoverageReturnType) => void): void; - /** - * Enable type profile. - * @experimental - */ - post(method: 'Profiler.startTypeProfile', callback?: (err: Error | null) => void): void; - /** - * Disable type profile. Disabling releases type profile data collected so far. - * @experimental - */ - post(method: 'Profiler.stopTypeProfile', callback?: (err: Error | null) => void): void; - /** - * Collect type profile. - * @experimental - */ - post(method: 'Profiler.takeTypeProfile', callback?: (err: Error | null, params: Profiler.TakeTypeProfileReturnType) => void): void; - post(method: 'HeapProfiler.enable', callback?: (err: Error | null) => void): void; - post(method: 'HeapProfiler.disable', callback?: (err: Error | null) => void): void; - post(method: 'HeapProfiler.startTrackingHeapObjects', params?: HeapProfiler.StartTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; - post(method: 'HeapProfiler.startTrackingHeapObjects', callback?: (err: Error | null) => void): void; - post(method: 'HeapProfiler.stopTrackingHeapObjects', params?: HeapProfiler.StopTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; - post(method: 'HeapProfiler.stopTrackingHeapObjects', callback?: (err: Error | null) => void): void; - post(method: 'HeapProfiler.takeHeapSnapshot', params?: HeapProfiler.TakeHeapSnapshotParameterType, callback?: (err: Error | null) => void): void; - post(method: 'HeapProfiler.takeHeapSnapshot', callback?: (err: Error | null) => void): void; - post(method: 'HeapProfiler.collectGarbage', callback?: (err: Error | null) => void): void; - post( - method: 'HeapProfiler.getObjectByHeapObjectId', - params?: HeapProfiler.GetObjectByHeapObjectIdParameterType, - callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void - ): void; - post(method: 'HeapProfiler.getObjectByHeapObjectId', callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void): void; - /** - * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). - */ - post(method: 'HeapProfiler.addInspectedHeapObject', params?: HeapProfiler.AddInspectedHeapObjectParameterType, callback?: (err: Error | null) => void): void; - post(method: 'HeapProfiler.addInspectedHeapObject', callback?: (err: Error | null) => void): void; - post(method: 'HeapProfiler.getHeapObjectId', params?: HeapProfiler.GetHeapObjectIdParameterType, callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; - post(method: 'HeapProfiler.getHeapObjectId', callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; - post(method: 'HeapProfiler.startSampling', params?: HeapProfiler.StartSamplingParameterType, callback?: (err: Error | null) => void): void; - post(method: 'HeapProfiler.startSampling', callback?: (err: Error | null) => void): void; - post(method: 'HeapProfiler.stopSampling', callback?: (err: Error | null, params: HeapProfiler.StopSamplingReturnType) => void): void; - post(method: 'HeapProfiler.getSamplingProfile', callback?: (err: Error | null, params: HeapProfiler.GetSamplingProfileReturnType) => void): void; - /** - * Gets supported tracing categories. - */ - post(method: 'NodeTracing.getCategories', callback?: (err: Error | null, params: NodeTracing.GetCategoriesReturnType) => void): void; - /** - * Start trace events collection. - */ - post(method: 'NodeTracing.start', params?: NodeTracing.StartParameterType, callback?: (err: Error | null) => void): void; - post(method: 'NodeTracing.start', callback?: (err: Error | null) => void): void; - /** - * Stop trace events collection. Remaining collected events will be sent as a sequence of - * dataCollected events followed by tracingComplete event. - */ - post(method: 'NodeTracing.stop', callback?: (err: Error | null) => void): void; - /** - * Sends protocol message over session with given id. - */ - post(method: 'NodeWorker.sendMessageToWorker', params?: NodeWorker.SendMessageToWorkerParameterType, callback?: (err: Error | null) => void): void; - post(method: 'NodeWorker.sendMessageToWorker', callback?: (err: Error | null) => void): void; - /** - * Instructs the inspector to attach to running workers. Will also attach to new workers - * as they start - */ - post(method: 'NodeWorker.enable', params?: NodeWorker.EnableParameterType, callback?: (err: Error | null) => void): void; - post(method: 'NodeWorker.enable', callback?: (err: Error | null) => void): void; - /** - * Detaches from all running workers and disables attaching to new workers as they are started. - */ - post(method: 'NodeWorker.disable', callback?: (err: Error | null) => void): void; - /** - * Detached from the worker with given sessionId. - */ - post(method: 'NodeWorker.detach', params?: NodeWorker.DetachParameterType, callback?: (err: Error | null) => void): void; - post(method: 'NodeWorker.detach', callback?: (err: Error | null) => void): void; - /** - * Enable the `NodeRuntime.waitingForDisconnect`. - */ - post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', params?: NodeRuntime.NotifyWhenWaitingForDisconnectParameterType, callback?: (err: Error | null) => void): void; - post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', callback?: (err: Error | null) => void): void; - // Events - addListener(event: string, listener: (...args: any[]) => void): this; - /** - * Emitted when any notification from the V8 Inspector is received. - */ - addListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; - /** - * Issued when new execution context is created. - */ - addListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; - /** - * Issued when execution context is destroyed. - */ - addListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; - /** - * Issued when all executionContexts were cleared in browser - */ - addListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; - /** - * Issued when exception was thrown and unhandled. - */ - addListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; - /** - * Issued when unhandled exception was revoked. - */ - addListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; - /** - * Issued when console API was called. - */ - addListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; - /** - * Issued when object should be inspected (for example, as a result of inspect() command line API call). - */ - addListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; - /** - * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. - */ - addListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; - /** - * Fired when virtual machine fails to parse the script. - */ - addListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; - /** - * Fired when breakpoint is resolved to an actual script and location. - */ - addListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; - /** - * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. - */ - addListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; - /** - * Fired when the virtual machine resumed execution. - */ - addListener(event: 'Debugger.resumed', listener: () => void): this; - /** - * Issued when new console message is added. - */ - addListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; - /** - * Sent when new profile recording is started using console.profile() call. - */ - addListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; - addListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; - addListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; - addListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; - addListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; - /** - * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. - */ - addListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; - /** - * If heap objects tracking has been started then backend may send update for one or more fragments - */ - addListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; - /** - * Contains an bucket of collected trace events. - */ - addListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; - /** - * Signals that tracing is stopped and there is no trace buffers pending flush, all data were - * delivered via dataCollected events. - */ - addListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; - /** - * Issued when attached to a worker. - */ - addListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; - /** - * Issued when detached from the worker. - */ - addListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; - /** - * Notifies about a new protocol message received from the session - * (session ID is provided in attachedToWorker notification). - */ - addListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; - /** - * This event is fired instead of `Runtime.executionContextDestroyed` when - * enabled. - * It is fired when the Node process finished all code execution and is - * waiting for all frontends to disconnect. - */ - addListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: 'inspectorNotification', message: InspectorNotification<{}>): boolean; - emit(event: 'Runtime.executionContextCreated', message: InspectorNotification): boolean; - emit(event: 'Runtime.executionContextDestroyed', message: InspectorNotification): boolean; - emit(event: 'Runtime.executionContextsCleared'): boolean; - emit(event: 'Runtime.exceptionThrown', message: InspectorNotification): boolean; - emit(event: 'Runtime.exceptionRevoked', message: InspectorNotification): boolean; - emit(event: 'Runtime.consoleAPICalled', message: InspectorNotification): boolean; - emit(event: 'Runtime.inspectRequested', message: InspectorNotification): boolean; - emit(event: 'Debugger.scriptParsed', message: InspectorNotification): boolean; - emit(event: 'Debugger.scriptFailedToParse', message: InspectorNotification): boolean; - emit(event: 'Debugger.breakpointResolved', message: InspectorNotification): boolean; - emit(event: 'Debugger.paused', message: InspectorNotification): boolean; - emit(event: 'Debugger.resumed'): boolean; - emit(event: 'Console.messageAdded', message: InspectorNotification): boolean; - emit(event: 'Profiler.consoleProfileStarted', message: InspectorNotification): boolean; - emit(event: 'Profiler.consoleProfileFinished', message: InspectorNotification): boolean; - emit(event: 'HeapProfiler.addHeapSnapshotChunk', message: InspectorNotification): boolean; - emit(event: 'HeapProfiler.resetProfiles'): boolean; - emit(event: 'HeapProfiler.reportHeapSnapshotProgress', message: InspectorNotification): boolean; - emit(event: 'HeapProfiler.lastSeenObjectId', message: InspectorNotification): boolean; - emit(event: 'HeapProfiler.heapStatsUpdate', message: InspectorNotification): boolean; - emit(event: 'NodeTracing.dataCollected', message: InspectorNotification): boolean; - emit(event: 'NodeTracing.tracingComplete'): boolean; - emit(event: 'NodeWorker.attachedToWorker', message: InspectorNotification): boolean; - emit(event: 'NodeWorker.detachedFromWorker', message: InspectorNotification): boolean; - emit(event: 'NodeWorker.receivedMessageFromWorker', message: InspectorNotification): boolean; - emit(event: 'NodeRuntime.waitingForDisconnect'): boolean; - on(event: string, listener: (...args: any[]) => void): this; - /** - * Emitted when any notification from the V8 Inspector is received. - */ - on(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; - /** - * Issued when new execution context is created. - */ - on(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; - /** - * Issued when execution context is destroyed. - */ - on(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; - /** - * Issued when all executionContexts were cleared in browser - */ - on(event: 'Runtime.executionContextsCleared', listener: () => void): this; - /** - * Issued when exception was thrown and unhandled. - */ - on(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; - /** - * Issued when unhandled exception was revoked. - */ - on(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; - /** - * Issued when console API was called. - */ - on(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; - /** - * Issued when object should be inspected (for example, as a result of inspect() command line API call). - */ - on(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; - /** - * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. - */ - on(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; - /** - * Fired when virtual machine fails to parse the script. - */ - on(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; - /** - * Fired when breakpoint is resolved to an actual script and location. - */ - on(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; - /** - * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. - */ - on(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; - /** - * Fired when the virtual machine resumed execution. - */ - on(event: 'Debugger.resumed', listener: () => void): this; - /** - * Issued when new console message is added. - */ - on(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; - /** - * Sent when new profile recording is started using console.profile() call. - */ - on(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; - on(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; - on(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; - on(event: 'HeapProfiler.resetProfiles', listener: () => void): this; - on(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; - /** - * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. - */ - on(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; - /** - * If heap objects tracking has been started then backend may send update for one or more fragments - */ - on(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; - /** - * Contains an bucket of collected trace events. - */ - on(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; - /** - * Signals that tracing is stopped and there is no trace buffers pending flush, all data were - * delivered via dataCollected events. - */ - on(event: 'NodeTracing.tracingComplete', listener: () => void): this; - /** - * Issued when attached to a worker. - */ - on(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; - /** - * Issued when detached from the worker. - */ - on(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; - /** - * Notifies about a new protocol message received from the session - * (session ID is provided in attachedToWorker notification). - */ - on(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; - /** - * This event is fired instead of `Runtime.executionContextDestroyed` when - * enabled. - * It is fired when the Node process finished all code execution and is - * waiting for all frontends to disconnect. - */ - on(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; - once(event: string, listener: (...args: any[]) => void): this; - /** - * Emitted when any notification from the V8 Inspector is received. - */ - once(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; - /** - * Issued when new execution context is created. - */ - once(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; - /** - * Issued when execution context is destroyed. - */ - once(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; - /** - * Issued when all executionContexts were cleared in browser - */ - once(event: 'Runtime.executionContextsCleared', listener: () => void): this; - /** - * Issued when exception was thrown and unhandled. - */ - once(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; - /** - * Issued when unhandled exception was revoked. - */ - once(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; - /** - * Issued when console API was called. - */ - once(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; - /** - * Issued when object should be inspected (for example, as a result of inspect() command line API call). - */ - once(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; - /** - * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. - */ - once(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; - /** - * Fired when virtual machine fails to parse the script. - */ - once(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; - /** - * Fired when breakpoint is resolved to an actual script and location. - */ - once(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; - /** - * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. - */ - once(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; - /** - * Fired when the virtual machine resumed execution. - */ - once(event: 'Debugger.resumed', listener: () => void): this; - /** - * Issued when new console message is added. - */ - once(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; - /** - * Sent when new profile recording is started using console.profile() call. - */ - once(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; - once(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; - once(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; - once(event: 'HeapProfiler.resetProfiles', listener: () => void): this; - once(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; - /** - * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. - */ - once(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; - /** - * If heap objects tracking has been started then backend may send update for one or more fragments - */ - once(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; - /** - * Contains an bucket of collected trace events. - */ - once(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; - /** - * Signals that tracing is stopped and there is no trace buffers pending flush, all data were - * delivered via dataCollected events. - */ - once(event: 'NodeTracing.tracingComplete', listener: () => void): this; - /** - * Issued when attached to a worker. - */ - once(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; - /** - * Issued when detached from the worker. - */ - once(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; - /** - * Notifies about a new protocol message received from the session - * (session ID is provided in attachedToWorker notification). - */ - once(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; - /** - * This event is fired instead of `Runtime.executionContextDestroyed` when - * enabled. - * It is fired when the Node process finished all code execution and is - * waiting for all frontends to disconnect. - */ - once(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; - prependListener(event: string, listener: (...args: any[]) => void): this; - /** - * Emitted when any notification from the V8 Inspector is received. - */ - prependListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; - /** - * Issued when new execution context is created. - */ - prependListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; - /** - * Issued when execution context is destroyed. - */ - prependListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; - /** - * Issued when all executionContexts were cleared in browser - */ - prependListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; - /** - * Issued when exception was thrown and unhandled. - */ - prependListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; - /** - * Issued when unhandled exception was revoked. - */ - prependListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; - /** - * Issued when console API was called. - */ - prependListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; - /** - * Issued when object should be inspected (for example, as a result of inspect() command line API call). - */ - prependListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; - /** - * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. - */ - prependListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; - /** - * Fired when virtual machine fails to parse the script. - */ - prependListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; - /** - * Fired when breakpoint is resolved to an actual script and location. - */ - prependListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; - /** - * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. - */ - prependListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; - /** - * Fired when the virtual machine resumed execution. - */ - prependListener(event: 'Debugger.resumed', listener: () => void): this; - /** - * Issued when new console message is added. - */ - prependListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; - /** - * Sent when new profile recording is started using console.profile() call. - */ - prependListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; - prependListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; - prependListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; - prependListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; - prependListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; - /** - * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. - */ - prependListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; - /** - * If heap objects tracking has been started then backend may send update for one or more fragments - */ - prependListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; - /** - * Contains an bucket of collected trace events. - */ - prependListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; - /** - * Signals that tracing is stopped and there is no trace buffers pending flush, all data were - * delivered via dataCollected events. - */ - prependListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; - /** - * Issued when attached to a worker. - */ - prependListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; - /** - * Issued when detached from the worker. - */ - prependListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; - /** - * Notifies about a new protocol message received from the session - * (session ID is provided in attachedToWorker notification). - */ - prependListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; - /** - * This event is fired instead of `Runtime.executionContextDestroyed` when - * enabled. - * It is fired when the Node process finished all code execution and is - * waiting for all frontends to disconnect. - */ - prependListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - /** - * Emitted when any notification from the V8 Inspector is received. - */ - prependOnceListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; - /** - * Issued when new execution context is created. - */ - prependOnceListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; - /** - * Issued when execution context is destroyed. - */ - prependOnceListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; - /** - * Issued when all executionContexts were cleared in browser - */ - prependOnceListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; - /** - * Issued when exception was thrown and unhandled. - */ - prependOnceListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; - /** - * Issued when unhandled exception was revoked. - */ - prependOnceListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; - /** - * Issued when console API was called. - */ - prependOnceListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; - /** - * Issued when object should be inspected (for example, as a result of inspect() command line API call). - */ - prependOnceListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; - /** - * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. - */ - prependOnceListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; - /** - * Fired when virtual machine fails to parse the script. - */ - prependOnceListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; - /** - * Fired when breakpoint is resolved to an actual script and location. - */ - prependOnceListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; - /** - * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. - */ - prependOnceListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; - /** - * Fired when the virtual machine resumed execution. - */ - prependOnceListener(event: 'Debugger.resumed', listener: () => void): this; - /** - * Issued when new console message is added. - */ - prependOnceListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; - /** - * Sent when new profile recording is started using console.profile() call. - */ - prependOnceListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; - prependOnceListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; - prependOnceListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; - prependOnceListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; - prependOnceListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; - /** - * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. - */ - prependOnceListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; - /** - * If heap objects tracking has been started then backend may send update for one or more fragments - */ - prependOnceListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; - /** - * Contains an bucket of collected trace events. - */ - prependOnceListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; - /** - * Signals that tracing is stopped and there is no trace buffers pending flush, all data were - * delivered via dataCollected events. - */ - prependOnceListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; - /** - * Issued when attached to a worker. - */ - prependOnceListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; - /** - * Issued when detached from the worker. - */ - prependOnceListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; - /** - * Notifies about a new protocol message received from the session - * (session ID is provided in attachedToWorker notification). - */ - prependOnceListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; - /** - * This event is fired instead of `Runtime.executionContextDestroyed` when - * enabled. - * It is fired when the Node process finished all code execution and is - * waiting for all frontends to disconnect. - */ - prependOnceListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; - } - /** - * Activate inspector on host and port. Equivalent to`node --inspect=[[host:]port]`, but can be done programmatically after node has - * started. - * - * If wait is `true`, will block until a client has connected to the inspect port - * and flow control has been passed to the debugger client. - * - * See the `security warning` regarding the `host`parameter usage. - * @param [port='what was specified on the CLI'] Port to listen on for inspector connections. Optional. - * @param [host='what was specified on the CLI'] Host to listen on for inspector connections. Optional. - * @param [wait=false] Block until a client has connected. Optional. - * @returns Disposable that calls `inspector.close()`. - */ - function open(port?: number, host?: string, wait?: boolean): Disposable; - /** - * Deactivate the inspector. Blocks until there are no active connections. - */ - function close(): void; - /** - * Return the URL of the active inspector, or `undefined` if there is none. - * - * ```console - * $ node --inspect -p 'inspector.url()' - * Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 - * For help, see: https://nodejs.org/en/docs/inspector - * ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 - * - * $ node --inspect=localhost:3000 -p 'inspector.url()' - * Debugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a - * For help, see: https://nodejs.org/en/docs/inspector - * ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a - * - * $ node -p 'inspector.url()' - * undefined - * ``` - */ - function url(): string | undefined; - /** - * Blocks until a client (existing or connected later) has sent`Runtime.runIfWaitingForDebugger` command. - * - * An exception will be thrown if there is no active inspector. - * @since v12.7.0 - */ - function waitForDebugger(): void; -} -/** - * The inspector module provides an API for interacting with the V8 inspector. - */ -declare module 'node:inspector' { - import inspector = require('inspector'); - export = inspector; -} diff --git a/node_modules/@types/node/ts4.8/module.d.ts b/node_modules/@types/node/ts4.8/module.d.ts deleted file mode 100644 index c38a9b800639d85000119845eec842dd57deaf80..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/module.d.ts +++ /dev/null @@ -1,315 +0,0 @@ -/** - * @since v0.3.7 - * @experimental - */ -declare module "module" { - import { URL } from "node:url"; - import { MessagePort } from "node:worker_threads"; - namespace Module { - /** - * The `module.syncBuiltinESMExports()` method updates all the live bindings for - * builtin `ES Modules` to match the properties of the `CommonJS` exports. It - * does not add or remove exported names from the `ES Modules`. - * - * ```js - * const fs = require('node:fs'); - * const assert = require('node:assert'); - * const { syncBuiltinESMExports } = require('node:module'); - * - * fs.readFile = newAPI; - * - * delete fs.readFileSync; - * - * function newAPI() { - * // ... - * } - * - * fs.newAPI = newAPI; - * - * syncBuiltinESMExports(); - * - * import('node:fs').then((esmFS) => { - * // It syncs the existing readFile property with the new value - * assert.strictEqual(esmFS.readFile, newAPI); - * // readFileSync has been deleted from the required fs - * assert.strictEqual('readFileSync' in fs, false); - * // syncBuiltinESMExports() does not remove readFileSync from esmFS - * assert.strictEqual('readFileSync' in esmFS, true); - * // syncBuiltinESMExports() does not add names - * assert.strictEqual(esmFS.newAPI, undefined); - * }); - * ``` - * @since v12.12.0 - */ - function syncBuiltinESMExports(): void; - /** - * `path` is the resolved path for the file for which a corresponding source map - * should be fetched. - * @since v13.7.0, v12.17.0 - * @return Returns `module.SourceMap` if a source map is found, `undefined` otherwise. - */ - function findSourceMap(path: string, error?: Error): SourceMap; - interface SourceMapPayload { - file: string; - version: number; - sources: string[]; - sourcesContent: string[]; - names: string[]; - mappings: string; - sourceRoot: string; - } - interface SourceMapping { - generatedLine: number; - generatedColumn: number; - originalSource: string; - originalLine: number; - originalColumn: number; - } - interface SourceOrigin { - /** - * The name of the range in the source map, if one was provided - */ - name?: string; - /** - * The file name of the original source, as reported in the SourceMap - */ - fileName: string; - /** - * The 1-indexed lineNumber of the corresponding call site in the original source - */ - lineNumber: number; - /** - * The 1-indexed columnNumber of the corresponding call site in the original source - */ - columnNumber: number; - } - /** - * @since v13.7.0, v12.17.0 - */ - class SourceMap { - /** - * Getter for the payload used to construct the `SourceMap` instance. - */ - readonly payload: SourceMapPayload; - constructor(payload: SourceMapPayload); - /** - * Given a line offset and column offset in the generated source - * file, returns an object representing the SourceMap range in the - * original file if found, or an empty object if not. - * - * The object returned contains the following keys: - * - * The returned value represents the raw range as it appears in the - * SourceMap, based on zero-indexed offsets, _not_ 1-indexed line and - * column numbers as they appear in Error messages and CallSite - * objects. - * - * To get the corresponding 1-indexed line and column numbers from a - * lineNumber and columnNumber as they are reported by Error stacks - * and CallSite objects, use `sourceMap.findOrigin(lineNumber, columnNumber)` - * @param lineOffset The zero-indexed line number offset in the generated source - * @param columnOffset The zero-indexed column number offset in the generated source - */ - findEntry(lineOffset: number, columnOffset: number): SourceMapping; - /** - * Given a 1-indexed `lineNumber` and `columnNumber` from a call site in the generated source, - * find the corresponding call site location in the original source. - * - * If the `lineNumber` and `columnNumber` provided are not found in any source map, - * then an empty object is returned. - * @param lineNumber The 1-indexed line number of the call site in the generated source - * @param columnNumber The 1-indexed column number of the call site in the generated source - */ - findOrigin(lineNumber: number, columnNumber: number): SourceOrigin | {}; - } - /** @deprecated Use `ImportAttributes` instead */ - interface ImportAssertions extends ImportAttributes {} - interface ImportAttributes extends NodeJS.Dict { - type?: string | undefined; - } - type ModuleFormat = "builtin" | "commonjs" | "json" | "module" | "wasm"; - type ModuleSource = string | ArrayBuffer | NodeJS.TypedArray; - interface GlobalPreloadContext { - port: MessagePort; - } - /** - * @deprecated This hook will be removed in a future version. - * Use `initialize` instead. When a loader has an `initialize` export, `globalPreload` will be ignored. - * - * Sometimes it might be necessary to run some code inside of the same global scope that the application runs in. - * This hook allows the return of a string that is run as a sloppy-mode script on startup. - * - * @param context Information to assist the preload code - * @return Code to run before application startup - */ - type GlobalPreloadHook = (context: GlobalPreloadContext) => string; - /** - * The `initialize` hook provides a way to define a custom function that runs in the hooks thread - * when the hooks module is initialized. Initialization happens when the hooks module is registered via `register`. - * - * This hook can receive data from a `register` invocation, including ports and other transferrable objects. - * The return value of `initialize` can be a `Promise`, in which case it will be awaited before the main application thread execution resumes. - */ - type InitializeHook = (data: Data) => void | Promise; - interface ResolveHookContext { - /** - * Export conditions of the relevant `package.json` - */ - conditions: string[]; - /** - * @deprecated Use `importAttributes` instead - */ - importAssertions: ImportAttributes; - /** - * An object whose key-value pairs represent the assertions for the module to import - */ - importAttributes: ImportAttributes; - /** - * The module importing this one, or undefined if this is the Node.js entry point - */ - parentURL: string | undefined; - } - interface ResolveFnOutput { - /** - * A hint to the load hook (it might be ignored) - */ - format?: ModuleFormat | null | undefined; - /** - * @deprecated Use `importAttributes` instead - */ - importAssertions?: ImportAttributes | undefined; - /** - * The import attributes to use when caching the module (optional; if excluded the input will be used) - */ - importAttributes?: ImportAttributes | undefined; - /** - * A signal that this hook intends to terminate the chain of `resolve` hooks. - * @default false - */ - shortCircuit?: boolean | undefined; - /** - * The absolute URL to which this input resolves - */ - url: string; - } - /** - * The `resolve` hook chain is responsible for resolving file URL for a given module specifier and parent URL, and optionally its format (such as `'module'`) as a hint to the `load` hook. - * If a format is specified, the load hook is ultimately responsible for providing the final `format` value (and it is free to ignore the hint provided by `resolve`); - * if `resolve` provides a format, a custom `load` hook is required even if only to pass the value to the Node.js default `load` hook. - * - * @param specifier The specified URL path of the module to be resolved - * @param context - * @param nextResolve The subsequent `resolve` hook in the chain, or the Node.js default `resolve` hook after the last user-supplied resolve hook - */ - type ResolveHook = ( - specifier: string, - context: ResolveHookContext, - nextResolve: ( - specifier: string, - context?: ResolveHookContext, - ) => ResolveFnOutput | Promise, - ) => ResolveFnOutput | Promise; - interface LoadHookContext { - /** - * Export conditions of the relevant `package.json` - */ - conditions: string[]; - /** - * The format optionally supplied by the `resolve` hook chain - */ - format: ModuleFormat; - /** - * @deprecated Use `importAttributes` instead - */ - importAssertions: ImportAttributes; - /** - * An object whose key-value pairs represent the assertions for the module to import - */ - importAttributes: ImportAttributes; - } - interface LoadFnOutput { - format: ModuleFormat; - /** - * A signal that this hook intends to terminate the chain of `resolve` hooks. - * @default false - */ - shortCircuit?: boolean | undefined; - /** - * The source for Node.js to evaluate - */ - source?: ModuleSource; - } - /** - * The `load` hook provides a way to define a custom method of determining how a URL should be interpreted, retrieved, and parsed. - * It is also in charge of validating the import assertion. - * - * @param url The URL/path of the module to be loaded - * @param context Metadata about the module - * @param nextLoad The subsequent `load` hook in the chain, or the Node.js default `load` hook after the last user-supplied `load` hook - */ - type LoadHook = ( - url: string, - context: LoadHookContext, - nextLoad: (url: string, context?: LoadHookContext) => LoadFnOutput | Promise, - ) => LoadFnOutput | Promise; - } - interface RegisterOptions { - parentURL: string | URL; - data?: Data | undefined; - transferList?: any[] | undefined; - } - interface Module extends NodeModule {} - class Module { - static runMain(): void; - static wrap(code: string): string; - static createRequire(path: string | URL): NodeRequire; - static builtinModules: string[]; - static isBuiltin(moduleName: string): boolean; - static Module: typeof Module; - static register( - specifier: string | URL, - parentURL?: string | URL, - options?: RegisterOptions, - ): void; - static register(specifier: string | URL, options?: RegisterOptions): void; - constructor(id: string, parent?: Module); - } - global { - interface ImportMeta { - /** - * The directory name of the current module. This is the same as the `path.dirname()` of the `import.meta.filename`. - * **Caveat:** only present on `file:` modules. - */ - dirname: string; - /** - * The full absolute path and filename of the current module, with symlinks resolved. - * This is the same as the `url.fileURLToPath()` of the `import.meta.url`. - * **Caveat:** only local modules support this property. Modules not using the `file:` protocol will not provide it. - */ - filename: string; - /** - * The absolute `file:` URL of the module. - */ - url: string; - /** - * Provides a module-relative resolution function scoped to each module, returning - * the URL string. - * - * Second `parent` parameter is only used when the `--experimental-import-meta-resolve` - * command flag enabled. - * - * @since v20.6.0 - * - * @param specifier The module specifier to resolve relative to `parent`. - * @param parent The absolute parent module URL to resolve from. - * @returns The absolute (`file:`) URL string for the resolved module. - */ - resolve(specifier: string, parent?: string | URL | undefined): string; - } - } - export = Module; -} -declare module "node:module" { - import module = require("module"); - export = module; -} diff --git a/node_modules/@types/node/ts4.8/net.d.ts b/node_modules/@types/node/ts4.8/net.d.ts deleted file mode 100644 index 70789e1ba1c71d917006acfa4cca7769ea1c705e..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/net.d.ts +++ /dev/null @@ -1,949 +0,0 @@ -/** - * > Stability: 2 - Stable - * - * The `node:net` module provides an asynchronous network API for creating stream-based - * TCP or `IPC` servers ({@link createServer}) and clients - * ({@link createConnection}). - * - * It can be accessed using: - * - * ```js - * const net = require('node:net'); - * ``` - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/net.js) - */ -declare module "net" { - import * as stream from "node:stream"; - import { Abortable, EventEmitter } from "node:events"; - import * as dns from "node:dns"; - type LookupFunction = ( - hostname: string, - options: dns.LookupAllOptions, - callback: (err: NodeJS.ErrnoException | null, addresses: dns.LookupAddress[]) => void, - ) => void; - interface AddressInfo { - address: string; - family: string; - port: number; - } - interface SocketConstructorOpts { - fd?: number | undefined; - allowHalfOpen?: boolean | undefined; - readable?: boolean | undefined; - writable?: boolean | undefined; - signal?: AbortSignal; - } - interface OnReadOpts { - buffer: Uint8Array | (() => Uint8Array); - /** - * This function is called for every chunk of incoming data. - * Two arguments are passed to it: the number of bytes written to buffer and a reference to buffer. - * Return false from this function to implicitly pause() the socket. - */ - callback(bytesWritten: number, buf: Uint8Array): boolean; - } - interface ConnectOpts { - /** - * If specified, incoming data is stored in a single buffer and passed to the supplied callback when data arrives on the socket. - * Note: this will cause the streaming functionality to not provide any data, however events like 'error', 'end', and 'close' will - * still be emitted as normal and methods like pause() and resume() will also behave as expected. - */ - onread?: OnReadOpts | undefined; - } - interface TcpSocketConnectOpts extends ConnectOpts { - port: number; - host?: string | undefined; - localAddress?: string | undefined; - localPort?: number | undefined; - hints?: number | undefined; - family?: number | undefined; - lookup?: LookupFunction | undefined; - noDelay?: boolean | undefined; - keepAlive?: boolean | undefined; - keepAliveInitialDelay?: number | undefined; - /** - * @since v18.13.0 - */ - autoSelectFamily?: boolean | undefined; - /** - * @since v18.13.0 - */ - autoSelectFamilyAttemptTimeout?: number | undefined; - } - interface IpcSocketConnectOpts extends ConnectOpts { - path: string; - } - type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts; - type SocketReadyState = "opening" | "open" | "readOnly" | "writeOnly" | "closed"; - /** - * This class is an abstraction of a TCP socket or a streaming `IPC` endpoint - * (uses named pipes on Windows, and Unix domain sockets otherwise). It is also - * an `EventEmitter`. - * - * A `net.Socket` can be created by the user and used directly to interact with - * a server. For example, it is returned by {@link createConnection}, - * so the user can use it to talk to the server. - * - * It can also be created by Node.js and passed to the user when a connection - * is received. For example, it is passed to the listeners of a `'connection'` event emitted on a {@link Server}, so the user can use - * it to interact with the client. - * @since v0.3.4 - */ - class Socket extends stream.Duplex { - constructor(options?: SocketConstructorOpts); - /** - * Destroys the socket after all data is written. If the `finish` event was already emitted the socket is destroyed immediately. - * If the socket is still writable it implicitly calls `socket.end()`. - * @since v0.3.4 - */ - destroySoon(): void; - /** - * Sends data on the socket. The second parameter specifies the encoding in the - * case of a string. It defaults to UTF8 encoding. - * - * Returns `true` if the entire data was flushed successfully to the kernel - * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is again free. - * - * The optional `callback` parameter will be executed when the data is finally - * written out, which may not be immediately. - * - * See `Writable` stream `write()` method for more - * information. - * @since v0.1.90 - * @param [encoding='utf8'] Only used when data is `string`. - */ - write(buffer: Uint8Array | string, cb?: (err?: Error) => void): boolean; - write(str: Uint8Array | string, encoding?: BufferEncoding, cb?: (err?: Error) => void): boolean; - /** - * Initiate a connection on a given socket. - * - * Possible signatures: - * - * * `socket.connect(options[, connectListener])` - * * `socket.connect(path[, connectListener])` for `IPC` connections. - * * `socket.connect(port[, host][, connectListener])` for TCP connections. - * * Returns: `net.Socket` The socket itself. - * - * This function is asynchronous. When the connection is established, the `'connect'` event will be emitted. If there is a problem connecting, - * instead of a `'connect'` event, an `'error'` event will be emitted with - * the error passed to the `'error'` listener. - * The last parameter `connectListener`, if supplied, will be added as a listener - * for the `'connect'` event **once**. - * - * This function should only be used for reconnecting a socket after`'close'` has been emitted or otherwise it may lead to undefined - * behavior. - */ - connect(options: SocketConnectOpts, connectionListener?: () => void): this; - connect(port: number, host: string, connectionListener?: () => void): this; - connect(port: number, connectionListener?: () => void): this; - connect(path: string, connectionListener?: () => void): this; - /** - * Set the encoding for the socket as a `Readable Stream`. See `readable.setEncoding()` for more information. - * @since v0.1.90 - * @return The socket itself. - */ - setEncoding(encoding?: BufferEncoding): this; - /** - * Pauses the reading of data. That is, `'data'` events will not be emitted. - * Useful to throttle back an upload. - * @return The socket itself. - */ - pause(): this; - /** - * Close the TCP connection by sending an RST packet and destroy the stream. - * If this TCP socket is in connecting status, it will send an RST packet and destroy this TCP socket once it is connected. - * Otherwise, it will call `socket.destroy` with an `ERR_SOCKET_CLOSED` Error. - * If this is not a TCP socket (for example, a pipe), calling this method will immediately throw an `ERR_INVALID_HANDLE_TYPE` Error. - * @since v18.3.0, v16.17.0 - */ - resetAndDestroy(): this; - /** - * Resumes reading after a call to `socket.pause()`. - * @return The socket itself. - */ - resume(): this; - /** - * Sets the socket to timeout after `timeout` milliseconds of inactivity on - * the socket. By default `net.Socket` do not have a timeout. - * - * When an idle timeout is triggered the socket will receive a `'timeout'` event but the connection will not be severed. The user must manually call `socket.end()` or `socket.destroy()` to - * end the connection. - * - * ```js - * socket.setTimeout(3000); - * socket.on('timeout', () => { - * console.log('socket timeout'); - * socket.end(); - * }); - * ``` - * - * If `timeout` is 0, then the existing idle timeout is disabled. - * - * The optional `callback` parameter will be added as a one-time listener for the `'timeout'` event. - * @since v0.1.90 - * @return The socket itself. - */ - setTimeout(timeout: number, callback?: () => void): this; - /** - * Enable/disable the use of Nagle's algorithm. - * - * When a TCP connection is created, it will have Nagle's algorithm enabled. - * - * Nagle's algorithm delays data before it is sent via the network. It attempts - * to optimize throughput at the expense of latency. - * - * Passing `true` for `noDelay` or not passing an argument will disable Nagle's - * algorithm for the socket. Passing `false` for `noDelay` will enable Nagle's - * algorithm. - * @since v0.1.90 - * @param [noDelay=true] - * @return The socket itself. - */ - setNoDelay(noDelay?: boolean): this; - /** - * Enable/disable keep-alive functionality, and optionally set the initial - * delay before the first keepalive probe is sent on an idle socket. - * - * Set `initialDelay` (in milliseconds) to set the delay between the last - * data packet received and the first keepalive probe. Setting `0` for`initialDelay` will leave the value unchanged from the default - * (or previous) setting. - * - * Enabling the keep-alive functionality will set the following socket options: - * - * * `SO_KEEPALIVE=1` - * * `TCP_KEEPIDLE=initialDelay` - * * `TCP_KEEPCNT=10` - * * `TCP_KEEPINTVL=1` - * @since v0.1.92 - * @param [enable=false] - * @param [initialDelay=0] - * @return The socket itself. - */ - setKeepAlive(enable?: boolean, initialDelay?: number): this; - /** - * Returns the bound `address`, the address `family` name and `port` of the - * socket as reported by the operating system:`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` - * @since v0.1.90 - */ - address(): AddressInfo | {}; - /** - * Calling `unref()` on a socket will allow the program to exit if this is the only - * active socket in the event system. If the socket is already `unref`ed calling`unref()` again will have no effect. - * @since v0.9.1 - * @return The socket itself. - */ - unref(): this; - /** - * Opposite of `unref()`, calling `ref()` on a previously `unref`ed socket will _not_ let the program exit if it's the only socket left (the default behavior). - * If the socket is `ref`ed calling `ref` again will have no effect. - * @since v0.9.1 - * @return The socket itself. - */ - ref(): this; - /** - * This property is only present if the family autoselection algorithm is enabled in `socket.connect(options)` - * and it is an array of the addresses that have been attempted. - * - * Each address is a string in the form of `$IP:$PORT`. - * If the connection was successful, then the last address is the one that the socket is currently connected to. - * @since v19.4.0 - */ - readonly autoSelectFamilyAttemptedAddresses: string[]; - /** - * This property shows the number of characters buffered for writing. The buffer - * may contain strings whose length after encoding is not yet known. So this number - * is only an approximation of the number of bytes in the buffer. - * - * `net.Socket` has the property that `socket.write()` always works. This is to - * help users get up and running quickly. The computer cannot always keep up - * with the amount of data that is written to a socket. The network connection - * simply might be too slow. Node.js will internally queue up the data written to a - * socket and send it out over the wire when it is possible. - * - * The consequence of this internal buffering is that memory may grow. - * Users who experience large or growing `bufferSize` should attempt to - * "throttle" the data flows in their program with `socket.pause()` and `socket.resume()`. - * @since v0.3.8 - * @deprecated Since v14.6.0 - Use `writableLength` instead. - */ - readonly bufferSize: number; - /** - * The amount of received bytes. - * @since v0.5.3 - */ - readonly bytesRead: number; - /** - * The amount of bytes sent. - * @since v0.5.3 - */ - readonly bytesWritten: number; - /** - * If `true`,`socket.connect(options[, connectListener])` was - * called and has not yet finished. It will stay `true` until the socket becomes - * connected, then it is set to `false` and the `'connect'` event is emitted. Note - * that the `socket.connect(options[, connectListener])` callback is a listener for the `'connect'` event. - * @since v6.1.0 - */ - readonly connecting: boolean; - /** - * This is `true` if the socket is not connected yet, either because `.connect()`has not yet been called or because it is still in the process of connecting - * (see `socket.connecting`). - * @since v11.2.0, v10.16.0 - */ - readonly pending: boolean; - /** - * See `writable.destroyed` for further details. - */ - readonly destroyed: boolean; - /** - * The string representation of the local IP address the remote client is - * connecting on. For example, in a server listening on `'0.0.0.0'`, if a client - * connects on `'192.168.1.1'`, the value of `socket.localAddress` would be`'192.168.1.1'`. - * @since v0.9.6 - */ - readonly localAddress?: string; - /** - * The numeric representation of the local port. For example, `80` or `21`. - * @since v0.9.6 - */ - readonly localPort?: number; - /** - * The string representation of the local IP family. `'IPv4'` or `'IPv6'`. - * @since v18.8.0, v16.18.0 - */ - readonly localFamily?: string; - /** - * This property represents the state of the connection as a string. - * - * * If the stream is connecting `socket.readyState` is `opening`. - * * If the stream is readable and writable, it is `open`. - * * If the stream is readable and not writable, it is `readOnly`. - * * If the stream is not readable and writable, it is `writeOnly`. - * @since v0.5.0 - */ - readonly readyState: SocketReadyState; - /** - * The string representation of the remote IP address. For example,`'74.125.127.100'` or `'2001:4860:a005::68'`. Value may be `undefined` if - * the socket is destroyed (for example, if the client disconnected). - * @since v0.5.10 - */ - readonly remoteAddress?: string | undefined; - /** - * The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. Value may be `undefined` if - * the socket is destroyed (for example, if the client disconnected). - * @since v0.11.14 - */ - readonly remoteFamily?: string | undefined; - /** - * The numeric representation of the remote port. For example, `80` or `21`. Value may be `undefined` if - * the socket is destroyed (for example, if the client disconnected). - * @since v0.5.10 - */ - readonly remotePort?: number | undefined; - /** - * The socket timeout in milliseconds as set by `socket.setTimeout()`. - * It is `undefined` if a timeout has not been set. - * @since v10.7.0 - */ - readonly timeout?: number | undefined; - /** - * Half-closes the socket. i.e., it sends a FIN packet. It is possible the - * server will still send some data. - * - * See `writable.end()` for further details. - * @since v0.1.90 - * @param [encoding='utf8'] Only used when data is `string`. - * @param callback Optional callback for when the socket is finished. - * @return The socket itself. - */ - end(callback?: () => void): this; - end(buffer: Uint8Array | string, callback?: () => void): this; - end(str: Uint8Array | string, encoding?: BufferEncoding, callback?: () => void): this; - /** - * events.EventEmitter - * 1. close - * 2. connect - * 3. data - * 4. drain - * 5. end - * 6. error - * 7. lookup - * 8. ready - * 9. timeout - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "close", listener: (hadError: boolean) => void): this; - addListener(event: "connect", listener: () => void): this; - addListener(event: "data", listener: (data: Buffer) => void): this; - addListener(event: "drain", listener: () => void): this; - addListener(event: "end", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener( - event: "lookup", - listener: (err: Error, address: string, family: string | number, host: string) => void, - ): this; - addListener(event: "ready", listener: () => void): this; - addListener(event: "timeout", listener: () => void): this; - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "close", hadError: boolean): boolean; - emit(event: "connect"): boolean; - emit(event: "data", data: Buffer): boolean; - emit(event: "drain"): boolean; - emit(event: "end"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean; - emit(event: "ready"): boolean; - emit(event: "timeout"): boolean; - on(event: string, listener: (...args: any[]) => void): this; - on(event: "close", listener: (hadError: boolean) => void): this; - on(event: "connect", listener: () => void): this; - on(event: "data", listener: (data: Buffer) => void): this; - on(event: "drain", listener: () => void): this; - on(event: "end", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on( - event: "lookup", - listener: (err: Error, address: string, family: string | number, host: string) => void, - ): this; - on(event: "ready", listener: () => void): this; - on(event: "timeout", listener: () => void): this; - once(event: string, listener: (...args: any[]) => void): this; - once(event: "close", listener: (hadError: boolean) => void): this; - once(event: "connect", listener: () => void): this; - once(event: "data", listener: (data: Buffer) => void): this; - once(event: "drain", listener: () => void): this; - once(event: "end", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once( - event: "lookup", - listener: (err: Error, address: string, family: string | number, host: string) => void, - ): this; - once(event: "ready", listener: () => void): this; - once(event: "timeout", listener: () => void): this; - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: (hadError: boolean) => void): this; - prependListener(event: "connect", listener: () => void): this; - prependListener(event: "data", listener: (data: Buffer) => void): this; - prependListener(event: "drain", listener: () => void): this; - prependListener(event: "end", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener( - event: "lookup", - listener: (err: Error, address: string, family: string | number, host: string) => void, - ): this; - prependListener(event: "ready", listener: () => void): this; - prependListener(event: "timeout", listener: () => void): this; - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: (hadError: boolean) => void): this; - prependOnceListener(event: "connect", listener: () => void): this; - prependOnceListener(event: "data", listener: (data: Buffer) => void): this; - prependOnceListener(event: "drain", listener: () => void): this; - prependOnceListener(event: "end", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener( - event: "lookup", - listener: (err: Error, address: string, family: string | number, host: string) => void, - ): this; - prependOnceListener(event: "ready", listener: () => void): this; - prependOnceListener(event: "timeout", listener: () => void): this; - } - interface ListenOptions extends Abortable { - port?: number | undefined; - host?: string | undefined; - backlog?: number | undefined; - path?: string | undefined; - exclusive?: boolean | undefined; - readableAll?: boolean | undefined; - writableAll?: boolean | undefined; - /** - * @default false - */ - ipv6Only?: boolean | undefined; - } - interface ServerOpts { - /** - * Indicates whether half-opened TCP connections are allowed. - * @default false - */ - allowHalfOpen?: boolean | undefined; - /** - * Indicates whether the socket should be paused on incoming connections. - * @default false - */ - pauseOnConnect?: boolean | undefined; - /** - * If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. - * @default false - * @since v16.5.0 - */ - noDelay?: boolean | undefined; - /** - * If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, - * similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`. - * @default false - * @since v16.5.0 - */ - keepAlive?: boolean | undefined; - /** - * If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. - * @default 0 - * @since v16.5.0 - */ - keepAliveInitialDelay?: number | undefined; - } - interface DropArgument { - localAddress?: string; - localPort?: number; - localFamily?: string; - remoteAddress?: string; - remotePort?: number; - remoteFamily?: string; - } - /** - * This class is used to create a TCP or `IPC` server. - * @since v0.1.90 - */ - class Server extends EventEmitter { - constructor(connectionListener?: (socket: Socket) => void); - constructor(options?: ServerOpts, connectionListener?: (socket: Socket) => void); - /** - * Start a server listening for connections. A `net.Server` can be a TCP or - * an `IPC` server depending on what it listens to. - * - * Possible signatures: - * - * * `server.listen(handle[, backlog][, callback])` - * * `server.listen(options[, callback])` - * * `server.listen(path[, backlog][, callback])` for `IPC` servers - * * `server.listen([port[, host[, backlog]]][, callback])` for TCP servers - * - * This function is asynchronous. When the server starts listening, the `'listening'` event will be emitted. The last parameter `callback`will be added as a listener for the `'listening'` - * event. - * - * All `listen()` methods can take a `backlog` parameter to specify the maximum - * length of the queue of pending connections. The actual length will be determined - * by the OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn`on Linux. The default value of this parameter is 511 (not 512). - * - * All {@link Socket} are set to `SO_REUSEADDR` (see [`socket(7)`](https://man7.org/linux/man-pages/man7/socket.7.html) for - * details). - * - * The `server.listen()` method can be called again if and only if there was an - * error during the first `server.listen()` call or `server.close()` has been - * called. Otherwise, an `ERR_SERVER_ALREADY_LISTEN` error will be thrown. - * - * One of the most common errors raised when listening is `EADDRINUSE`. - * This happens when another server is already listening on the requested`port`/`path`/`handle`. One way to handle this would be to retry - * after a certain amount of time: - * - * ```js - * server.on('error', (e) => { - * if (e.code === 'EADDRINUSE') { - * console.error('Address in use, retrying...'); - * setTimeout(() => { - * server.close(); - * server.listen(PORT, HOST); - * }, 1000); - * } - * }); - * ``` - */ - listen(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): this; - listen(port?: number, hostname?: string, listeningListener?: () => void): this; - listen(port?: number, backlog?: number, listeningListener?: () => void): this; - listen(port?: number, listeningListener?: () => void): this; - listen(path: string, backlog?: number, listeningListener?: () => void): this; - listen(path: string, listeningListener?: () => void): this; - listen(options: ListenOptions, listeningListener?: () => void): this; - listen(handle: any, backlog?: number, listeningListener?: () => void): this; - listen(handle: any, listeningListener?: () => void): this; - /** - * Stops the server from accepting new connections and keeps existing - * connections. This function is asynchronous, the server is finally closed - * when all connections are ended and the server emits a `'close'` event. - * The optional `callback` will be called once the `'close'` event occurs. Unlike - * that event, it will be called with an `Error` as its only argument if the server - * was not open when it was closed. - * @since v0.1.90 - * @param callback Called when the server is closed. - */ - close(callback?: (err?: Error) => void): this; - /** - * Returns the bound `address`, the address `family` name, and `port` of the server - * as reported by the operating system if listening on an IP socket - * (useful to find which port was assigned when getting an OS-assigned address):`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`. - * - * For a server listening on a pipe or Unix domain socket, the name is returned - * as a string. - * - * ```js - * const server = net.createServer((socket) => { - * socket.end('goodbye\n'); - * }).on('error', (err) => { - * // Handle errors here. - * throw err; - * }); - * - * // Grab an arbitrary unused port. - * server.listen(() => { - * console.log('opened server on', server.address()); - * }); - * ``` - * - * `server.address()` returns `null` before the `'listening'` event has been - * emitted or after calling `server.close()`. - * @since v0.1.90 - */ - address(): AddressInfo | string | null; - /** - * Asynchronously get the number of concurrent connections on the server. Works - * when sockets were sent to forks. - * - * Callback should take two arguments `err` and `count`. - * @since v0.9.7 - */ - getConnections(cb: (error: Error | null, count: number) => void): void; - /** - * Opposite of `unref()`, calling `ref()` on a previously `unref`ed server will _not_ let the program exit if it's the only server left (the default behavior). - * If the server is `ref`ed calling `ref()` again will have no effect. - * @since v0.9.1 - */ - ref(): this; - /** - * Calling `unref()` on a server will allow the program to exit if this is the only - * active server in the event system. If the server is already `unref`ed calling`unref()` again will have no effect. - * @since v0.9.1 - */ - unref(): this; - /** - * Set this property to reject connections when the server's connection count gets - * high. - * - * It is not recommended to use this option once a socket has been sent to a child - * with `child_process.fork()`. - * @since v0.2.0 - */ - maxConnections: number; - connections: number; - /** - * Indicates whether or not the server is listening for connections. - * @since v5.7.0 - */ - listening: boolean; - /** - * events.EventEmitter - * 1. close - * 2. connection - * 3. error - * 4. listening - * 5. drop - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "connection", listener: (socket: Socket) => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "listening", listener: () => void): this; - addListener(event: "drop", listener: (data?: DropArgument) => void): this; - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "connection", socket: Socket): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "listening"): boolean; - emit(event: "drop", data?: DropArgument): boolean; - on(event: string, listener: (...args: any[]) => void): this; - on(event: "close", listener: () => void): this; - on(event: "connection", listener: (socket: Socket) => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "listening", listener: () => void): this; - on(event: "drop", listener: (data?: DropArgument) => void): this; - once(event: string, listener: (...args: any[]) => void): this; - once(event: "close", listener: () => void): this; - once(event: "connection", listener: (socket: Socket) => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "listening", listener: () => void): this; - once(event: "drop", listener: (data?: DropArgument) => void): this; - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "connection", listener: (socket: Socket) => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "listening", listener: () => void): this; - prependListener(event: "drop", listener: (data?: DropArgument) => void): this; - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "listening", listener: () => void): this; - prependOnceListener(event: "drop", listener: (data?: DropArgument) => void): this; - /** - * Calls {@link Server.close()} and returns a promise that fulfills when the server has closed. - * @since v20.5.0 - */ - [Symbol.asyncDispose](): Promise; - } - type IPVersion = "ipv4" | "ipv6"; - /** - * The `BlockList` object can be used with some network APIs to specify rules for - * disabling inbound or outbound access to specific IP addresses, IP ranges, or - * IP subnets. - * @since v15.0.0, v14.18.0 - */ - class BlockList { - /** - * Adds a rule to block the given IP address. - * @since v15.0.0, v14.18.0 - * @param address An IPv4 or IPv6 address. - * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. - */ - addAddress(address: string, type?: IPVersion): void; - addAddress(address: SocketAddress): void; - /** - * Adds a rule to block a range of IP addresses from `start` (inclusive) to`end` (inclusive). - * @since v15.0.0, v14.18.0 - * @param start The starting IPv4 or IPv6 address in the range. - * @param end The ending IPv4 or IPv6 address in the range. - * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. - */ - addRange(start: string, end: string, type?: IPVersion): void; - addRange(start: SocketAddress, end: SocketAddress): void; - /** - * Adds a rule to block a range of IP addresses specified as a subnet mask. - * @since v15.0.0, v14.18.0 - * @param net The network IPv4 or IPv6 address. - * @param prefix The number of CIDR prefix bits. For IPv4, this must be a value between `0` and `32`. For IPv6, this must be between `0` and `128`. - * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. - */ - addSubnet(net: SocketAddress, prefix: number): void; - addSubnet(net: string, prefix: number, type?: IPVersion): void; - /** - * Returns `true` if the given IP address matches any of the rules added to the`BlockList`. - * - * ```js - * const blockList = new net.BlockList(); - * blockList.addAddress('123.123.123.123'); - * blockList.addRange('10.0.0.1', '10.0.0.10'); - * blockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6'); - * - * console.log(blockList.check('123.123.123.123')); // Prints: true - * console.log(blockList.check('10.0.0.3')); // Prints: true - * console.log(blockList.check('222.111.111.222')); // Prints: false - * - * // IPv6 notation for IPv4 addresses works: - * console.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true - * console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true - * ``` - * @since v15.0.0, v14.18.0 - * @param address The IP address to check - * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. - */ - check(address: SocketAddress): boolean; - check(address: string, type?: IPVersion): boolean; - } - interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts { - timeout?: number | undefined; - } - interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts { - timeout?: number | undefined; - } - type NetConnectOpts = TcpNetConnectOpts | IpcNetConnectOpts; - /** - * Creates a new TCP or `IPC` server. - * - * If `allowHalfOpen` is set to `true`, when the other end of the socket - * signals the end of transmission, the server will only send back the end of - * transmission when `socket.end()` is explicitly called. For example, in the - * context of TCP, when a FIN packed is received, a FIN packed is sent - * back only when `socket.end()` is explicitly called. Until then the - * connection is half-closed (non-readable but still writable). See `'end'` event and [RFC 1122](https://tools.ietf.org/html/rfc1122) (section 4.2.2.13) for more information. - * - * If `pauseOnConnect` is set to `true`, then the socket associated with each - * incoming connection will be paused, and no data will be read from its handle. - * This allows connections to be passed between processes without any data being - * read by the original process. To begin reading data from a paused socket, call `socket.resume()`. - * - * The server can be a TCP server or an `IPC` server, depending on what it `listen()` to. - * - * Here is an example of a TCP echo server which listens for connections - * on port 8124: - * - * ```js - * const net = require('node:net'); - * const server = net.createServer((c) => { - * // 'connection' listener. - * console.log('client connected'); - * c.on('end', () => { - * console.log('client disconnected'); - * }); - * c.write('hello\r\n'); - * c.pipe(c); - * }); - * server.on('error', (err) => { - * throw err; - * }); - * server.listen(8124, () => { - * console.log('server bound'); - * }); - * ``` - * - * Test this by using `telnet`: - * - * ```bash - * telnet localhost 8124 - * ``` - * - * To listen on the socket `/tmp/echo.sock`: - * - * ```js - * server.listen('/tmp/echo.sock', () => { - * console.log('server bound'); - * }); - * ``` - * - * Use `nc` to connect to a Unix domain socket server: - * - * ```bash - * nc -U /tmp/echo.sock - * ``` - * @since v0.5.0 - * @param connectionListener Automatically set as a listener for the {@link 'connection'} event. - */ - function createServer(connectionListener?: (socket: Socket) => void): Server; - function createServer(options?: ServerOpts, connectionListener?: (socket: Socket) => void): Server; - /** - * Aliases to {@link createConnection}. - * - * Possible signatures: - * - * * {@link connect} - * * {@link connect} for `IPC` connections. - * * {@link connect} for TCP connections. - */ - function connect(options: NetConnectOpts, connectionListener?: () => void): Socket; - function connect(port: number, host?: string, connectionListener?: () => void): Socket; - function connect(path: string, connectionListener?: () => void): Socket; - /** - * A factory function, which creates a new {@link Socket}, - * immediately initiates connection with `socket.connect()`, - * then returns the `net.Socket` that starts the connection. - * - * When the connection is established, a `'connect'` event will be emitted - * on the returned socket. The last parameter `connectListener`, if supplied, - * will be added as a listener for the `'connect'` event **once**. - * - * Possible signatures: - * - * * {@link createConnection} - * * {@link createConnection} for `IPC` connections. - * * {@link createConnection} for TCP connections. - * - * The {@link connect} function is an alias to this function. - */ - function createConnection(options: NetConnectOpts, connectionListener?: () => void): Socket; - function createConnection(port: number, host?: string, connectionListener?: () => void): Socket; - function createConnection(path: string, connectionListener?: () => void): Socket; - /** - * Gets the current default value of the `autoSelectFamily` option of `socket.connect(options)`. - * The initial default value is `true`, unless the command line option`--no-network-family-autoselection` is provided. - * @since v19.4.0 - */ - function getDefaultAutoSelectFamily(): boolean; - /** - * Sets the default value of the `autoSelectFamily` option of `socket.connect(options)`. - * @since v19.4.0 - */ - function setDefaultAutoSelectFamily(value: boolean): void; - /** - * Gets the current default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`. - * The initial default value is `250`. - * @since v19.8.0 - */ - function getDefaultAutoSelectFamilyAttemptTimeout(): number; - /** - * Sets the default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`. - * @since v19.8.0 - */ - function setDefaultAutoSelectFamilyAttemptTimeout(value: number): void; - /** - * Returns `6` if `input` is an IPv6 address. Returns `4` if `input` is an IPv4 - * address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no leading zeroes. Otherwise, returns`0`. - * - * ```js - * net.isIP('::1'); // returns 6 - * net.isIP('127.0.0.1'); // returns 4 - * net.isIP('127.000.000.001'); // returns 0 - * net.isIP('127.0.0.1/24'); // returns 0 - * net.isIP('fhqwhgads'); // returns 0 - * ``` - * @since v0.3.0 - */ - function isIP(input: string): number; - /** - * Returns `true` if `input` is an IPv4 address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no - * leading zeroes. Otherwise, returns `false`. - * - * ```js - * net.isIPv4('127.0.0.1'); // returns true - * net.isIPv4('127.000.000.001'); // returns false - * net.isIPv4('127.0.0.1/24'); // returns false - * net.isIPv4('fhqwhgads'); // returns false - * ``` - * @since v0.3.0 - */ - function isIPv4(input: string): boolean; - /** - * Returns `true` if `input` is an IPv6 address. Otherwise, returns `false`. - * - * ```js - * net.isIPv6('::1'); // returns true - * net.isIPv6('fhqwhgads'); // returns false - * ``` - * @since v0.3.0 - */ - function isIPv6(input: string): boolean; - interface SocketAddressInitOptions { - /** - * The network address as either an IPv4 or IPv6 string. - * @default 127.0.0.1 - */ - address?: string | undefined; - /** - * @default `'ipv4'` - */ - family?: IPVersion | undefined; - /** - * An IPv6 flow-label used only if `family` is `'ipv6'`. - * @default 0 - */ - flowlabel?: number | undefined; - /** - * An IP port. - * @default 0 - */ - port?: number | undefined; - } - /** - * @since v15.14.0, v14.18.0 - */ - class SocketAddress { - constructor(options: SocketAddressInitOptions); - /** - * Either \`'ipv4'\` or \`'ipv6'\`. - * @since v15.14.0, v14.18.0 - */ - readonly address: string; - /** - * Either \`'ipv4'\` or \`'ipv6'\`. - * @since v15.14.0, v14.18.0 - */ - readonly family: IPVersion; - /** - * @since v15.14.0, v14.18.0 - */ - readonly port: number; - /** - * @since v15.14.0, v14.18.0 - */ - readonly flowlabel: number; - } -} -declare module "node:net" { - export * from "net"; -} diff --git a/node_modules/@types/node/ts4.8/os.d.ts b/node_modules/@types/node/ts4.8/os.d.ts deleted file mode 100644 index 39a33f7fd5b960970c3eb3946ceea8766eb1989d..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/os.d.ts +++ /dev/null @@ -1,478 +0,0 @@ -/** - * The `node:os` module provides operating system-related utility methods and - * properties. It can be accessed using: - * - * ```js - * const os = require('node:os'); - * ``` - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/os.js) - */ -declare module "os" { - interface CpuInfo { - model: string; - speed: number; - times: { - user: number; - nice: number; - sys: number; - idle: number; - irq: number; - }; - } - interface NetworkInterfaceBase { - address: string; - netmask: string; - mac: string; - internal: boolean; - cidr: string | null; - } - interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { - family: "IPv4"; - scopeid?: undefined; - } - interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { - family: "IPv6"; - scopeid: number; - } - interface UserInfo { - username: T; - uid: number; - gid: number; - shell: T | null; - homedir: T; - } - type NetworkInterfaceInfo = NetworkInterfaceInfoIPv4 | NetworkInterfaceInfoIPv6; - /** - * Returns the host name of the operating system as a string. - * @since v0.3.3 - */ - function hostname(): string; - /** - * Returns an array containing the 1, 5, and 15 minute load averages. - * - * The load average is a measure of system activity calculated by the operating - * system and expressed as a fractional number. - * - * The load average is a Unix-specific concept. On Windows, the return value is - * always `[0, 0, 0]`. - * @since v0.3.3 - */ - function loadavg(): number[]; - /** - * Returns the system uptime in number of seconds. - * @since v0.3.3 - */ - function uptime(): number; - /** - * Returns the amount of free system memory in bytes as an integer. - * @since v0.3.3 - */ - function freemem(): number; - /** - * Returns the total amount of system memory in bytes as an integer. - * @since v0.3.3 - */ - function totalmem(): number; - /** - * Returns an array of objects containing information about each logical CPU core. - * The array will be empty if no CPU information is available, such as if the`/proc` file system is unavailable. - * - * The properties included on each object include: - * - * ```js - * [ - * { - * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', - * speed: 2926, - * times: { - * user: 252020, - * nice: 0, - * sys: 30340, - * idle: 1070356870, - * irq: 0, - * }, - * }, - * { - * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', - * speed: 2926, - * times: { - * user: 306960, - * nice: 0, - * sys: 26980, - * idle: 1071569080, - * irq: 0, - * }, - * }, - * { - * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', - * speed: 2926, - * times: { - * user: 248450, - * nice: 0, - * sys: 21750, - * idle: 1070919370, - * irq: 0, - * }, - * }, - * { - * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', - * speed: 2926, - * times: { - * user: 256880, - * nice: 0, - * sys: 19430, - * idle: 1070905480, - * irq: 20, - * }, - * }, - * ] - * ``` - * - * `nice` values are POSIX-only. On Windows, the `nice` values of all processors - * are always 0. - * - * `os.cpus().length` should not be used to calculate the amount of parallelism - * available to an application. Use {@link availableParallelism} for this purpose. - * @since v0.3.3 - */ - function cpus(): CpuInfo[]; - /** - * Returns an estimate of the default amount of parallelism a program should use. - * Always returns a value greater than zero. - * - * This function is a small wrapper about libuv's [`uv_available_parallelism()`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_available_parallelism). - * @since v19.4.0, v18.14.0 - */ - function availableParallelism(): number; - /** - * Returns the operating system name as returned by [`uname(3)`](https://linux.die.net/man/3/uname). For example, it - * returns `'Linux'` on Linux, `'Darwin'` on macOS, and `'Windows_NT'` on Windows. - * - * See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for additional information - * about the output of running [`uname(3)`](https://linux.die.net/man/3/uname) on various operating systems. - * @since v0.3.3 - */ - function type(): string; - /** - * Returns the operating system as a string. - * - * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `GetVersionExW()` is used. See - * [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. - * @since v0.3.3 - */ - function release(): string; - /** - * Returns an object containing network interfaces that have been assigned a - * network address. - * - * Each key on the returned object identifies a network interface. The associated - * value is an array of objects that each describe an assigned network address. - * - * The properties available on the assigned network address object include: - * - * ```js - * { - * lo: [ - * { - * address: '127.0.0.1', - * netmask: '255.0.0.0', - * family: 'IPv4', - * mac: '00:00:00:00:00:00', - * internal: true, - * cidr: '127.0.0.1/8' - * }, - * { - * address: '::1', - * netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', - * family: 'IPv6', - * mac: '00:00:00:00:00:00', - * scopeid: 0, - * internal: true, - * cidr: '::1/128' - * } - * ], - * eth0: [ - * { - * address: '192.168.1.108', - * netmask: '255.255.255.0', - * family: 'IPv4', - * mac: '01:02:03:0a:0b:0c', - * internal: false, - * cidr: '192.168.1.108/24' - * }, - * { - * address: 'fe80::a00:27ff:fe4e:66a1', - * netmask: 'ffff:ffff:ffff:ffff::', - * family: 'IPv6', - * mac: '01:02:03:0a:0b:0c', - * scopeid: 1, - * internal: false, - * cidr: 'fe80::a00:27ff:fe4e:66a1/64' - * } - * ] - * } - * ``` - * @since v0.6.0 - */ - function networkInterfaces(): NodeJS.Dict; - /** - * Returns the string path of the current user's home directory. - * - * On POSIX, it uses the `$HOME` environment variable if defined. Otherwise it - * uses the [effective UID](https://en.wikipedia.org/wiki/User_identifier#Effective_user_ID) to look up the user's home directory. - * - * On Windows, it uses the `USERPROFILE` environment variable if defined. - * Otherwise it uses the path to the profile directory of the current user. - * @since v2.3.0 - */ - function homedir(): string; - /** - * Returns information about the currently effective user. On POSIX platforms, - * this is typically a subset of the password file. The returned object includes - * the `username`, `uid`, `gid`, `shell`, and `homedir`. On Windows, the `uid` and`gid` fields are `-1`, and `shell` is `null`. - * - * The value of `homedir` returned by `os.userInfo()` is provided by the operating - * system. This differs from the result of `os.homedir()`, which queries - * environment variables for the home directory before falling back to the - * operating system response. - * - * Throws a `SystemError` if a user has no `username` or `homedir`. - * @since v6.0.0 - */ - function userInfo(options: { encoding: "buffer" }): UserInfo; - function userInfo(options?: { encoding: BufferEncoding }): UserInfo; - type SignalConstants = { - [key in NodeJS.Signals]: number; - }; - namespace constants { - const UV_UDP_REUSEADDR: number; - namespace signals {} - const signals: SignalConstants; - namespace errno { - const E2BIG: number; - const EACCES: number; - const EADDRINUSE: number; - const EADDRNOTAVAIL: number; - const EAFNOSUPPORT: number; - const EAGAIN: number; - const EALREADY: number; - const EBADF: number; - const EBADMSG: number; - const EBUSY: number; - const ECANCELED: number; - const ECHILD: number; - const ECONNABORTED: number; - const ECONNREFUSED: number; - const ECONNRESET: number; - const EDEADLK: number; - const EDESTADDRREQ: number; - const EDOM: number; - const EDQUOT: number; - const EEXIST: number; - const EFAULT: number; - const EFBIG: number; - const EHOSTUNREACH: number; - const EIDRM: number; - const EILSEQ: number; - const EINPROGRESS: number; - const EINTR: number; - const EINVAL: number; - const EIO: number; - const EISCONN: number; - const EISDIR: number; - const ELOOP: number; - const EMFILE: number; - const EMLINK: number; - const EMSGSIZE: number; - const EMULTIHOP: number; - const ENAMETOOLONG: number; - const ENETDOWN: number; - const ENETRESET: number; - const ENETUNREACH: number; - const ENFILE: number; - const ENOBUFS: number; - const ENODATA: number; - const ENODEV: number; - const ENOENT: number; - const ENOEXEC: number; - const ENOLCK: number; - const ENOLINK: number; - const ENOMEM: number; - const ENOMSG: number; - const ENOPROTOOPT: number; - const ENOSPC: number; - const ENOSR: number; - const ENOSTR: number; - const ENOSYS: number; - const ENOTCONN: number; - const ENOTDIR: number; - const ENOTEMPTY: number; - const ENOTSOCK: number; - const ENOTSUP: number; - const ENOTTY: number; - const ENXIO: number; - const EOPNOTSUPP: number; - const EOVERFLOW: number; - const EPERM: number; - const EPIPE: number; - const EPROTO: number; - const EPROTONOSUPPORT: number; - const EPROTOTYPE: number; - const ERANGE: number; - const EROFS: number; - const ESPIPE: number; - const ESRCH: number; - const ESTALE: number; - const ETIME: number; - const ETIMEDOUT: number; - const ETXTBSY: number; - const EWOULDBLOCK: number; - const EXDEV: number; - const WSAEINTR: number; - const WSAEBADF: number; - const WSAEACCES: number; - const WSAEFAULT: number; - const WSAEINVAL: number; - const WSAEMFILE: number; - const WSAEWOULDBLOCK: number; - const WSAEINPROGRESS: number; - const WSAEALREADY: number; - const WSAENOTSOCK: number; - const WSAEDESTADDRREQ: number; - const WSAEMSGSIZE: number; - const WSAEPROTOTYPE: number; - const WSAENOPROTOOPT: number; - const WSAEPROTONOSUPPORT: number; - const WSAESOCKTNOSUPPORT: number; - const WSAEOPNOTSUPP: number; - const WSAEPFNOSUPPORT: number; - const WSAEAFNOSUPPORT: number; - const WSAEADDRINUSE: number; - const WSAEADDRNOTAVAIL: number; - const WSAENETDOWN: number; - const WSAENETUNREACH: number; - const WSAENETRESET: number; - const WSAECONNABORTED: number; - const WSAECONNRESET: number; - const WSAENOBUFS: number; - const WSAEISCONN: number; - const WSAENOTCONN: number; - const WSAESHUTDOWN: number; - const WSAETOOMANYREFS: number; - const WSAETIMEDOUT: number; - const WSAECONNREFUSED: number; - const WSAELOOP: number; - const WSAENAMETOOLONG: number; - const WSAEHOSTDOWN: number; - const WSAEHOSTUNREACH: number; - const WSAENOTEMPTY: number; - const WSAEPROCLIM: number; - const WSAEUSERS: number; - const WSAEDQUOT: number; - const WSAESTALE: number; - const WSAEREMOTE: number; - const WSASYSNOTREADY: number; - const WSAVERNOTSUPPORTED: number; - const WSANOTINITIALISED: number; - const WSAEDISCON: number; - const WSAENOMORE: number; - const WSAECANCELLED: number; - const WSAEINVALIDPROCTABLE: number; - const WSAEINVALIDPROVIDER: number; - const WSAEPROVIDERFAILEDINIT: number; - const WSASYSCALLFAILURE: number; - const WSASERVICE_NOT_FOUND: number; - const WSATYPE_NOT_FOUND: number; - const WSA_E_NO_MORE: number; - const WSA_E_CANCELLED: number; - const WSAEREFUSED: number; - } - namespace priority { - const PRIORITY_LOW: number; - const PRIORITY_BELOW_NORMAL: number; - const PRIORITY_NORMAL: number; - const PRIORITY_ABOVE_NORMAL: number; - const PRIORITY_HIGH: number; - const PRIORITY_HIGHEST: number; - } - } - const devNull: string; - const EOL: string; - /** - * Returns the operating system CPU architecture for which the Node.js binary was - * compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`,`'mips'`, `'mipsel'`, `'ppc'`, `'ppc64'`, `'riscv64'`, `'s390'`, `'s390x'`, - * and `'x64'`. - * - * The return value is equivalent to `process.arch`. - * @since v0.5.0 - */ - function arch(): string; - /** - * Returns a string identifying the kernel version. - * - * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not - * available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. - * @since v13.11.0, v12.17.0 - */ - function version(): string; - /** - * Returns a string identifying the operating system platform for which - * the Node.js binary was compiled. The value is set at compile time. - * Possible values are `'aix'`, `'darwin'`, `'freebsd'`,`'linux'`,`'openbsd'`, `'sunos'`, and `'win32'`. - * - * The return value is equivalent to `process.platform`. - * - * The value `'android'` may also be returned if Node.js is built on the Android - * operating system. [Android support is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). - * @since v0.5.0 - */ - function platform(): NodeJS.Platform; - /** - * Returns the machine type as a string, such as `arm`, `arm64`, `aarch64`,`mips`, `mips64`, `ppc64`, `ppc64le`, `s390`, `s390x`, `i386`, `i686`, `x86_64`. - * - * On POSIX systems, the machine type is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not - * available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. - * @since v18.9.0, v16.18.0 - */ - function machine(): string; - /** - * Returns the operating system's default directory for temporary files as a - * string. - * @since v0.9.9 - */ - function tmpdir(): string; - /** - * Returns a string identifying the endianness of the CPU for which the Node.js - * binary was compiled. - * - * Possible values are `'BE'` for big endian and `'LE'` for little endian. - * @since v0.9.4 - */ - function endianness(): "BE" | "LE"; - /** - * Returns the scheduling priority for the process specified by `pid`. If `pid` is - * not provided or is `0`, the priority of the current process is returned. - * @since v10.10.0 - * @param [pid=0] The process ID to retrieve scheduling priority for. - */ - function getPriority(pid?: number): number; - /** - * Attempts to set the scheduling priority for the process specified by `pid`. If`pid` is not provided or is `0`, the process ID of the current process is used. - * - * The `priority` input must be an integer between `-20` (high priority) and `19`(low priority). Due to differences between Unix priority levels and Windows - * priority classes, `priority` is mapped to one of six priority constants in`os.constants.priority`. When retrieving a process priority level, this range - * mapping may cause the return value to be slightly different on Windows. To avoid - * confusion, set `priority` to one of the priority constants. - * - * On Windows, setting priority to `PRIORITY_HIGHEST` requires elevated user - * privileges. Otherwise the set priority will be silently reduced to`PRIORITY_HIGH`. - * @since v10.10.0 - * @param [pid=0] The process ID to set scheduling priority for. - * @param priority The scheduling priority to assign to the process. - */ - function setPriority(priority: number): void; - function setPriority(pid: number, priority: number): void; -} -declare module "node:os" { - export * from "os"; -} diff --git a/node_modules/@types/node/ts4.8/path.d.ts b/node_modules/@types/node/ts4.8/path.d.ts deleted file mode 100644 index 6f07681ac6460e05a2b23515d13d45e1a0714b6c..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/path.d.ts +++ /dev/null @@ -1,191 +0,0 @@ -declare module "path/posix" { - import path = require("path"); - export = path; -} -declare module "path/win32" { - import path = require("path"); - export = path; -} -/** - * The `node:path` module provides utilities for working with file and directory - * paths. It can be accessed using: - * - * ```js - * const path = require('node:path'); - * ``` - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/path.js) - */ -declare module "path" { - namespace path { - /** - * A parsed path object generated by path.parse() or consumed by path.format(). - */ - interface ParsedPath { - /** - * The root of the path such as '/' or 'c:\' - */ - root: string; - /** - * The full directory path such as '/home/user/dir' or 'c:\path\dir' - */ - dir: string; - /** - * The file name including extension (if any) such as 'index.html' - */ - base: string; - /** - * The file extension (if any) such as '.html' - */ - ext: string; - /** - * The file name without extension (if any) such as 'index' - */ - name: string; - } - interface FormatInputPathObject { - /** - * The root of the path such as '/' or 'c:\' - */ - root?: string | undefined; - /** - * The full directory path such as '/home/user/dir' or 'c:\path\dir' - */ - dir?: string | undefined; - /** - * The file name including extension (if any) such as 'index.html' - */ - base?: string | undefined; - /** - * The file extension (if any) such as '.html' - */ - ext?: string | undefined; - /** - * The file name without extension (if any) such as 'index' - */ - name?: string | undefined; - } - interface PlatformPath { - /** - * Normalize a string path, reducing '..' and '.' parts. - * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. - * - * @param path string path to normalize. - * @throws {TypeError} if `path` is not a string. - */ - normalize(path: string): string; - /** - * Join all arguments together and normalize the resulting path. - * - * @param paths paths to join. - * @throws {TypeError} if any of the path segments is not a string. - */ - join(...paths: string[]): string; - /** - * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. - * - * Starting from leftmost {from} parameter, resolves {to} to an absolute path. - * - * If {to} isn't already absolute, {from} arguments are prepended in right to left order, - * until an absolute path is found. If after using all {from} paths still no absolute path is found, - * the current working directory is used as well. The resulting path is normalized, - * and trailing slashes are removed unless the path gets resolved to the root directory. - * - * @param paths A sequence of paths or path segments. - * @throws {TypeError} if any of the arguments is not a string. - */ - resolve(...paths: string[]): string; - /** - * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. - * - * If the given {path} is a zero-length string, `false` will be returned. - * - * @param path path to test. - * @throws {TypeError} if `path` is not a string. - */ - isAbsolute(path: string): boolean; - /** - * Solve the relative path from {from} to {to} based on the current working directory. - * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. - * - * @throws {TypeError} if either `from` or `to` is not a string. - */ - relative(from: string, to: string): string; - /** - * Return the directory name of a path. Similar to the Unix dirname command. - * - * @param path the path to evaluate. - * @throws {TypeError} if `path` is not a string. - */ - dirname(path: string): string; - /** - * Return the last portion of a path. Similar to the Unix basename command. - * Often used to extract the file name from a fully qualified path. - * - * @param path the path to evaluate. - * @param suffix optionally, an extension to remove from the result. - * @throws {TypeError} if `path` is not a string or if `ext` is given and is not a string. - */ - basename(path: string, suffix?: string): string; - /** - * Return the extension of the path, from the last '.' to end of string in the last portion of the path. - * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string. - * - * @param path the path to evaluate. - * @throws {TypeError} if `path` is not a string. - */ - extname(path: string): string; - /** - * The platform-specific file separator. '\\' or '/'. - */ - readonly sep: "\\" | "/"; - /** - * The platform-specific file delimiter. ';' or ':'. - */ - readonly delimiter: ";" | ":"; - /** - * Returns an object from a path string - the opposite of format(). - * - * @param path path to evaluate. - * @throws {TypeError} if `path` is not a string. - */ - parse(path: string): ParsedPath; - /** - * Returns a path string from an object - the opposite of parse(). - * - * @param pathObject path to evaluate. - */ - format(pathObject: FormatInputPathObject): string; - /** - * On Windows systems only, returns an equivalent namespace-prefixed path for the given path. - * If path is not a string, path will be returned without modifications. - * This method is meaningful only on Windows system. - * On POSIX systems, the method is non-operational and always returns path without modifications. - */ - toNamespacedPath(path: string): string; - /** - * Posix specific pathing. - * Same as parent object on posix. - */ - readonly posix: PlatformPath; - /** - * Windows specific pathing. - * Same as parent object on windows - */ - readonly win32: PlatformPath; - } - } - const path: path.PlatformPath; - export = path; -} -declare module "node:path" { - import path = require("path"); - export = path; -} -declare module "node:path/posix" { - import path = require("path/posix"); - export = path; -} -declare module "node:path/win32" { - import path = require("path/win32"); - export = path; -} diff --git a/node_modules/@types/node/ts4.8/perf_hooks.d.ts b/node_modules/@types/node/ts4.8/perf_hooks.d.ts deleted file mode 100644 index c0ce852a97b28560a5f8e4643a793b5c904deb56..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/perf_hooks.d.ts +++ /dev/null @@ -1,645 +0,0 @@ -/** - * This module provides an implementation of a subset of the W3C [Web Performance APIs](https://w3c.github.io/perf-timing-primer/) as well as additional APIs for - * Node.js-specific performance measurements. - * - * Node.js supports the following [Web Performance APIs](https://w3c.github.io/perf-timing-primer/): - * - * * [High Resolution Time](https://www.w3.org/TR/hr-time-2) - * * [Performance Timeline](https://w3c.github.io/performance-timeline/) - * * [User Timing](https://www.w3.org/TR/user-timing/) - * * [Resource Timing](https://www.w3.org/TR/resource-timing-2/) - * - * ```js - * const { PerformanceObserver, performance } = require('node:perf_hooks'); - * - * const obs = new PerformanceObserver((items) => { - * console.log(items.getEntries()[0].duration); - * performance.clearMarks(); - * }); - * obs.observe({ type: 'measure' }); - * performance.measure('Start to Now'); - * - * performance.mark('A'); - * doSomeLongRunningProcess(() => { - * performance.measure('A to Now', 'A'); - * - * performance.mark('B'); - * performance.measure('A to B', 'A', 'B'); - * }); - * ``` - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/perf_hooks.js) - */ -declare module "perf_hooks" { - import { AsyncResource } from "node:async_hooks"; - type EntryType = "node" | "mark" | "measure" | "gc" | "function" | "http2" | "http" | "dns" | "net"; - interface NodeGCPerformanceDetail { - /** - * When `performanceEntry.entryType` is equal to 'gc', `the performance.kind` property identifies - * the type of garbage collection operation that occurred. - * See perf_hooks.constants for valid values. - */ - readonly kind?: number | undefined; - /** - * When `performanceEntry.entryType` is equal to 'gc', the `performance.flags` - * property contains additional information about garbage collection operation. - * See perf_hooks.constants for valid values. - */ - readonly flags?: number | undefined; - } - /** - * The constructor of this class is not exposed to users directly. - * @since v8.5.0 - */ - class PerformanceEntry { - protected constructor(); - /** - * The total number of milliseconds elapsed for this entry. This value will not - * be meaningful for all Performance Entry types. - * @since v8.5.0 - */ - readonly duration: number; - /** - * The name of the performance entry. - * @since v8.5.0 - */ - readonly name: string; - /** - * The high resolution millisecond timestamp marking the starting time of the - * Performance Entry. - * @since v8.5.0 - */ - readonly startTime: number; - /** - * The type of the performance entry. It may be one of: - * - * * `'node'` (Node.js only) - * * `'mark'` (available on the Web) - * * `'measure'` (available on the Web) - * * `'gc'` (Node.js only) - * * `'function'` (Node.js only) - * * `'http2'` (Node.js only) - * * `'http'` (Node.js only) - * @since v8.5.0 - */ - readonly entryType: EntryType; - /** - * Additional detail specific to the `entryType`. - * @since v16.0.0 - */ - readonly detail?: NodeGCPerformanceDetail | unknown | undefined; // TODO: Narrow this based on entry type. - toJSON(): any; - } - /** - * Exposes marks created via the `Performance.mark()` method. - * @since v18.2.0, v16.17.0 - */ - class PerformanceMark extends PerformanceEntry { - readonly duration: 0; - readonly entryType: "mark"; - } - /** - * Exposes measures created via the `Performance.measure()` method. - * - * The constructor of this class is not exposed to users directly. - * @since v18.2.0, v16.17.0 - */ - class PerformanceMeasure extends PerformanceEntry { - readonly entryType: "measure"; - } - /** - * _This property is an extension by Node.js. It is not available in Web browsers._ - * - * Provides timing details for Node.js itself. The constructor of this class - * is not exposed to users. - * @since v8.5.0 - */ - class PerformanceNodeTiming extends PerformanceEntry { - /** - * The high resolution millisecond timestamp at which the Node.js process - * completed bootstrapping. If bootstrapping has not yet finished, the property - * has the value of -1. - * @since v8.5.0 - */ - readonly bootstrapComplete: number; - /** - * The high resolution millisecond timestamp at which the Node.js environment was - * initialized. - * @since v8.5.0 - */ - readonly environment: number; - /** - * The high resolution millisecond timestamp of the amount of time the event loop - * has been idle within the event loop's event provider (e.g. `epoll_wait`). This - * does not take CPU usage into consideration. If the event loop has not yet - * started (e.g., in the first tick of the main script), the property has the - * value of 0. - * @since v14.10.0, v12.19.0 - */ - readonly idleTime: number; - /** - * The high resolution millisecond timestamp at which the Node.js event loop - * exited. If the event loop has not yet exited, the property has the value of -1\. - * It can only have a value of not -1 in a handler of the `'exit'` event. - * @since v8.5.0 - */ - readonly loopExit: number; - /** - * The high resolution millisecond timestamp at which the Node.js event loop - * started. If the event loop has not yet started (e.g., in the first tick of the - * main script), the property has the value of -1. - * @since v8.5.0 - */ - readonly loopStart: number; - /** - * The high resolution millisecond timestamp at which the V8 platform was - * initialized. - * @since v8.5.0 - */ - readonly v8Start: number; - } - interface EventLoopUtilization { - idle: number; - active: number; - utilization: number; - } - /** - * @param util1 The result of a previous call to eventLoopUtilization() - * @param util2 The result of a previous call to eventLoopUtilization() prior to util1 - */ - type EventLoopUtilityFunction = ( - util1?: EventLoopUtilization, - util2?: EventLoopUtilization, - ) => EventLoopUtilization; - interface MarkOptions { - /** - * Additional optional detail to include with the mark. - */ - detail?: unknown | undefined; - /** - * An optional timestamp to be used as the mark time. - * @default `performance.now()`. - */ - startTime?: number | undefined; - } - interface MeasureOptions { - /** - * Additional optional detail to include with the mark. - */ - detail?: unknown | undefined; - /** - * Duration between start and end times. - */ - duration?: number | undefined; - /** - * Timestamp to be used as the end time, or a string identifying a previously recorded mark. - */ - end?: number | string | undefined; - /** - * Timestamp to be used as the start time, or a string identifying a previously recorded mark. - */ - start?: number | string | undefined; - } - interface TimerifyOptions { - /** - * A histogram object created using - * `perf_hooks.createHistogram()` that will record runtime durations in - * nanoseconds. - */ - histogram?: RecordableHistogram | undefined; - } - interface Performance { - /** - * If name is not provided, removes all PerformanceMark objects from the Performance Timeline. - * If name is provided, removes only the named mark. - * @param name - */ - clearMarks(name?: string): void; - /** - * If name is not provided, removes all PerformanceMeasure objects from the Performance Timeline. - * If name is provided, removes only the named measure. - * @param name - * @since v16.7.0 - */ - clearMeasures(name?: string): void; - /** - * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime`. - * If you are only interested in performance entries of certain types or that have certain names, see - * `performance.getEntriesByType()` and `performance.getEntriesByName()`. - * @since v16.7.0 - */ - getEntries(): PerformanceEntry[]; - /** - * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` - * whose `performanceEntry.name` is equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to `type`. - * @param name - * @param type - * @since v16.7.0 - */ - getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; - /** - * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` - * whose `performanceEntry.entryType` is equal to `type`. - * @param type - * @since v16.7.0 - */ - getEntriesByType(type: EntryType): PerformanceEntry[]; - /** - * Creates a new PerformanceMark entry in the Performance Timeline. - * A PerformanceMark is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'mark', - * and whose performanceEntry.duration is always 0. - * Performance marks are used to mark specific significant moments in the Performance Timeline. - * @param name - * @return The PerformanceMark entry that was created - */ - mark(name?: string, options?: MarkOptions): PerformanceMark; - /** - * Creates a new PerformanceMeasure entry in the Performance Timeline. - * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', - * and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark. - * - * The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify - * any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist, - * then startMark is set to timeOrigin by default. - * - * The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp - * properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown. - * @param name - * @param startMark - * @param endMark - * @return The PerformanceMeasure entry that was created - */ - measure(name: string, startMark?: string, endMark?: string): PerformanceMeasure; - measure(name: string, options: MeasureOptions): PerformanceMeasure; - /** - * An instance of the PerformanceNodeTiming class that provides performance metrics for specific Node.js operational milestones. - */ - readonly nodeTiming: PerformanceNodeTiming; - /** - * @return the current high resolution millisecond timestamp - */ - now(): number; - /** - * The timeOrigin specifies the high resolution millisecond timestamp from which all performance metric durations are measured. - */ - readonly timeOrigin: number; - /** - * Wraps a function within a new function that measures the running time of the wrapped function. - * A PerformanceObserver must be subscribed to the 'function' event type in order for the timing details to be accessed. - * @param fn - */ - timerify any>(fn: T, options?: TimerifyOptions): T; - /** - * eventLoopUtilization is similar to CPU utilization except that it is calculated using high precision wall-clock time. - * It represents the percentage of time the event loop has spent outside the event loop's event provider (e.g. epoll_wait). - * No other CPU idle time is taken into consideration. - */ - eventLoopUtilization: EventLoopUtilityFunction; - } - interface PerformanceObserverEntryList { - /** - * Returns a list of `PerformanceEntry` objects in chronological order - * with respect to `performanceEntry.startTime`. - * - * ```js - * const { - * performance, - * PerformanceObserver, - * } = require('node:perf_hooks'); - * - * const obs = new PerformanceObserver((perfObserverList, observer) => { - * console.log(perfObserverList.getEntries()); - * - * * [ - * * PerformanceEntry { - * * name: 'test', - * * entryType: 'mark', - * * startTime: 81.465639, - * * duration: 0, - * * detail: null - * * }, - * * PerformanceEntry { - * * name: 'meow', - * * entryType: 'mark', - * * startTime: 81.860064, - * * duration: 0, - * * detail: null - * * } - * * ] - * - * performance.clearMarks(); - * performance.clearMeasures(); - * observer.disconnect(); - * }); - * obs.observe({ type: 'mark' }); - * - * performance.mark('test'); - * performance.mark('meow'); - * ``` - * @since v8.5.0 - */ - getEntries(): PerformanceEntry[]; - /** - * Returns a list of `PerformanceEntry` objects in chronological order - * with respect to `performanceEntry.startTime` whose `performanceEntry.name` is - * equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to`type`. - * - * ```js - * const { - * performance, - * PerformanceObserver, - * } = require('node:perf_hooks'); - * - * const obs = new PerformanceObserver((perfObserverList, observer) => { - * console.log(perfObserverList.getEntriesByName('meow')); - * - * * [ - * * PerformanceEntry { - * * name: 'meow', - * * entryType: 'mark', - * * startTime: 98.545991, - * * duration: 0, - * * detail: null - * * } - * * ] - * - * console.log(perfObserverList.getEntriesByName('nope')); // [] - * - * console.log(perfObserverList.getEntriesByName('test', 'mark')); - * - * * [ - * * PerformanceEntry { - * * name: 'test', - * * entryType: 'mark', - * * startTime: 63.518931, - * * duration: 0, - * * detail: null - * * } - * * ] - * - * console.log(perfObserverList.getEntriesByName('test', 'measure')); // [] - * - * performance.clearMarks(); - * performance.clearMeasures(); - * observer.disconnect(); - * }); - * obs.observe({ entryTypes: ['mark', 'measure'] }); - * - * performance.mark('test'); - * performance.mark('meow'); - * ``` - * @since v8.5.0 - */ - getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; - /** - * Returns a list of `PerformanceEntry` objects in chronological order - * with respect to `performanceEntry.startTime` whose `performanceEntry.entryType`is equal to `type`. - * - * ```js - * const { - * performance, - * PerformanceObserver, - * } = require('node:perf_hooks'); - * - * const obs = new PerformanceObserver((perfObserverList, observer) => { - * console.log(perfObserverList.getEntriesByType('mark')); - * - * * [ - * * PerformanceEntry { - * * name: 'test', - * * entryType: 'mark', - * * startTime: 55.897834, - * * duration: 0, - * * detail: null - * * }, - * * PerformanceEntry { - * * name: 'meow', - * * entryType: 'mark', - * * startTime: 56.350146, - * * duration: 0, - * * detail: null - * * } - * * ] - * - * performance.clearMarks(); - * performance.clearMeasures(); - * observer.disconnect(); - * }); - * obs.observe({ type: 'mark' }); - * - * performance.mark('test'); - * performance.mark('meow'); - * ``` - * @since v8.5.0 - */ - getEntriesByType(type: EntryType): PerformanceEntry[]; - } - type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; - /** - * @since v8.5.0 - */ - class PerformanceObserver extends AsyncResource { - constructor(callback: PerformanceObserverCallback); - /** - * Disconnects the `PerformanceObserver` instance from all notifications. - * @since v8.5.0 - */ - disconnect(): void; - /** - * Subscribes the `PerformanceObserver` instance to notifications of new `PerformanceEntry` instances identified either by `options.entryTypes`or `options.type`: - * - * ```js - * const { - * performance, - * PerformanceObserver, - * } = require('node:perf_hooks'); - * - * const obs = new PerformanceObserver((list, observer) => { - * // Called once asynchronously. `list` contains three items. - * }); - * obs.observe({ type: 'mark' }); - * - * for (let n = 0; n < 3; n++) - * performance.mark(`test${n}`); - * ``` - * @since v8.5.0 - */ - observe( - options: - | { - entryTypes: readonly EntryType[]; - buffered?: boolean | undefined; - } - | { - type: EntryType; - buffered?: boolean | undefined; - }, - ): void; - } - namespace constants { - const NODE_PERFORMANCE_GC_MAJOR: number; - const NODE_PERFORMANCE_GC_MINOR: number; - const NODE_PERFORMANCE_GC_INCREMENTAL: number; - const NODE_PERFORMANCE_GC_WEAKCB: number; - const NODE_PERFORMANCE_GC_FLAGS_NO: number; - const NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED: number; - const NODE_PERFORMANCE_GC_FLAGS_FORCED: number; - const NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING: number; - const NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE: number; - const NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY: number; - const NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE: number; - } - const performance: Performance; - interface EventLoopMonitorOptions { - /** - * The sampling rate in milliseconds. - * Must be greater than zero. - * @default 10 - */ - resolution?: number | undefined; - } - interface Histogram { - /** - * Returns a `Map` object detailing the accumulated percentile distribution. - * @since v11.10.0 - */ - readonly percentiles: Map; - /** - * The number of times the event loop delay exceeded the maximum 1 hour event - * loop delay threshold. - * @since v11.10.0 - */ - readonly exceeds: number; - /** - * The minimum recorded event loop delay. - * @since v11.10.0 - */ - readonly min: number; - /** - * The maximum recorded event loop delay. - * @since v11.10.0 - */ - readonly max: number; - /** - * The mean of the recorded event loop delays. - * @since v11.10.0 - */ - readonly mean: number; - /** - * The standard deviation of the recorded event loop delays. - * @since v11.10.0 - */ - readonly stddev: number; - /** - * Resets the collected histogram data. - * @since v11.10.0 - */ - reset(): void; - /** - * Returns the value at the given percentile. - * @since v11.10.0 - * @param percentile A percentile value in the range (0, 100]. - */ - percentile(percentile: number): number; - } - interface IntervalHistogram extends Histogram { - /** - * Enables the update interval timer. Returns `true` if the timer was - * started, `false` if it was already started. - * @since v11.10.0 - */ - enable(): boolean; - /** - * Disables the update interval timer. Returns `true` if the timer was - * stopped, `false` if it was already stopped. - * @since v11.10.0 - */ - disable(): boolean; - } - interface RecordableHistogram extends Histogram { - /** - * @since v15.9.0, v14.18.0 - * @param val The amount to record in the histogram. - */ - record(val: number | bigint): void; - /** - * Calculates the amount of time (in nanoseconds) that has passed since the - * previous call to `recordDelta()` and records that amount in the histogram. - * - * ## Examples - * @since v15.9.0, v14.18.0 - */ - recordDelta(): void; - /** - * Adds the values from `other` to this histogram. - * @since v17.4.0, v16.14.0 - */ - add(other: RecordableHistogram): void; - } - /** - * _This property is an extension by Node.js. It is not available in Web browsers._ - * - * Creates an `IntervalHistogram` object that samples and reports the event loop - * delay over time. The delays will be reported in nanoseconds. - * - * Using a timer to detect approximate event loop delay works because the - * execution of timers is tied specifically to the lifecycle of the libuv - * event loop. That is, a delay in the loop will cause a delay in the execution - * of the timer, and those delays are specifically what this API is intended to - * detect. - * - * ```js - * const { monitorEventLoopDelay } = require('node:perf_hooks'); - * const h = monitorEventLoopDelay({ resolution: 20 }); - * h.enable(); - * // Do something. - * h.disable(); - * console.log(h.min); - * console.log(h.max); - * console.log(h.mean); - * console.log(h.stddev); - * console.log(h.percentiles); - * console.log(h.percentile(50)); - * console.log(h.percentile(99)); - * ``` - * @since v11.10.0 - */ - function monitorEventLoopDelay(options?: EventLoopMonitorOptions): IntervalHistogram; - interface CreateHistogramOptions { - /** - * The minimum recordable value. Must be an integer value greater than 0. - * @default 1 - */ - min?: number | bigint | undefined; - /** - * The maximum recordable value. Must be an integer value greater than min. - * @default Number.MAX_SAFE_INTEGER - */ - max?: number | bigint | undefined; - /** - * The number of accuracy digits. Must be a number between 1 and 5. - * @default 3 - */ - figures?: number | undefined; - } - /** - * Returns a `RecordableHistogram`. - * @since v15.9.0, v14.18.0 - */ - function createHistogram(options?: CreateHistogramOptions): RecordableHistogram; - import { performance as _performance } from "perf_hooks"; - global { - /** - * `performance` is a global reference for `require('perf_hooks').performance` - * https://nodejs.org/api/globals.html#performance - * @since v16.0.0 - */ - var performance: typeof globalThis extends { - onmessage: any; - performance: infer T; - } ? T - : typeof _performance; - } -} -declare module "node:perf_hooks" { - export * from "perf_hooks"; -} diff --git a/node_modules/@types/node/ts4.8/process.d.ts b/node_modules/@types/node/ts4.8/process.d.ts deleted file mode 100644 index d22308f6cba9971f38badf9f9706933d7350c446..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/process.d.ts +++ /dev/null @@ -1,1561 +0,0 @@ -declare module "process" { - import * as tty from "node:tty"; - import { Worker } from "node:worker_threads"; - global { - var process: NodeJS.Process; - namespace NodeJS { - // this namespace merge is here because these are specifically used - // as the type for process.stdin, process.stdout, and process.stderr. - // they can't live in tty.d.ts because we need to disambiguate the imported name. - interface ReadStream extends tty.ReadStream {} - interface WriteStream extends tty.WriteStream {} - interface MemoryUsageFn { - /** - * The `process.memoryUsage()` method iterate over each page to gather informations about memory - * usage which can be slow depending on the program memory allocations. - */ - (): MemoryUsage; - /** - * method returns an integer representing the Resident Set Size (RSS) in bytes. - */ - rss(): number; - } - interface MemoryUsage { - rss: number; - heapTotal: number; - heapUsed: number; - external: number; - arrayBuffers: number; - } - interface CpuUsage { - user: number; - system: number; - } - interface ProcessRelease { - name: string; - sourceUrl?: string | undefined; - headersUrl?: string | undefined; - libUrl?: string | undefined; - lts?: string | undefined; - } - interface ProcessVersions extends Dict { - http_parser: string; - node: string; - v8: string; - ares: string; - uv: string; - zlib: string; - modules: string; - openssl: string; - } - type Platform = - | "aix" - | "android" - | "darwin" - | "freebsd" - | "haiku" - | "linux" - | "openbsd" - | "sunos" - | "win32" - | "cygwin" - | "netbsd"; - type Architecture = - | "arm" - | "arm64" - | "ia32" - | "mips" - | "mipsel" - | "ppc" - | "ppc64" - | "riscv64" - | "s390" - | "s390x" - | "x64"; - type Signals = - | "SIGABRT" - | "SIGALRM" - | "SIGBUS" - | "SIGCHLD" - | "SIGCONT" - | "SIGFPE" - | "SIGHUP" - | "SIGILL" - | "SIGINT" - | "SIGIO" - | "SIGIOT" - | "SIGKILL" - | "SIGPIPE" - | "SIGPOLL" - | "SIGPROF" - | "SIGPWR" - | "SIGQUIT" - | "SIGSEGV" - | "SIGSTKFLT" - | "SIGSTOP" - | "SIGSYS" - | "SIGTERM" - | "SIGTRAP" - | "SIGTSTP" - | "SIGTTIN" - | "SIGTTOU" - | "SIGUNUSED" - | "SIGURG" - | "SIGUSR1" - | "SIGUSR2" - | "SIGVTALRM" - | "SIGWINCH" - | "SIGXCPU" - | "SIGXFSZ" - | "SIGBREAK" - | "SIGLOST" - | "SIGINFO"; - type UncaughtExceptionOrigin = "uncaughtException" | "unhandledRejection"; - type MultipleResolveType = "resolve" | "reject"; - type BeforeExitListener = (code: number) => void; - type DisconnectListener = () => void; - type ExitListener = (code: number) => void; - type RejectionHandledListener = (promise: Promise) => void; - type UncaughtExceptionListener = (error: Error, origin: UncaughtExceptionOrigin) => void; - /** - * Most of the time the unhandledRejection will be an Error, but this should not be relied upon - * as *anything* can be thrown/rejected, it is therefore unsafe to assume that the value is an Error. - */ - type UnhandledRejectionListener = (reason: unknown, promise: Promise) => void; - type WarningListener = (warning: Error) => void; - type MessageListener = (message: unknown, sendHandle: unknown) => void; - type SignalsListener = (signal: Signals) => void; - type MultipleResolveListener = ( - type: MultipleResolveType, - promise: Promise, - value: unknown, - ) => void; - type WorkerListener = (worker: Worker) => void; - interface Socket extends ReadWriteStream { - isTTY?: true | undefined; - } - // Alias for compatibility - interface ProcessEnv extends Dict { - /** - * Can be used to change the default timezone at runtime - */ - TZ?: string; - } - interface HRTime { - (time?: [number, number]): [number, number]; - bigint(): bigint; - } - interface ProcessReport { - /** - * Directory where the report is written. - * working directory of the Node.js process. - * @default '' indicating that reports are written to the current - */ - directory: string; - /** - * Filename where the report is written. - * The default value is the empty string. - * @default '' the output filename will be comprised of a timestamp, - * PID, and sequence number. - */ - filename: string; - /** - * Returns a JSON-formatted diagnostic report for the running process. - * The report's JavaScript stack trace is taken from err, if present. - */ - getReport(err?: Error): string; - /** - * If true, a diagnostic report is generated on fatal errors, - * such as out of memory errors or failed C++ assertions. - * @default false - */ - reportOnFatalError: boolean; - /** - * If true, a diagnostic report is generated when the process - * receives the signal specified by process.report.signal. - * @default false - */ - reportOnSignal: boolean; - /** - * If true, a diagnostic report is generated on uncaught exception. - * @default false - */ - reportOnUncaughtException: boolean; - /** - * The signal used to trigger the creation of a diagnostic report. - * @default 'SIGUSR2' - */ - signal: Signals; - /** - * Writes a diagnostic report to a file. If filename is not provided, the default filename - * includes the date, time, PID, and a sequence number. - * The report's JavaScript stack trace is taken from err, if present. - * - * @param fileName Name of the file where the report is written. - * This should be a relative path, that will be appended to the directory specified in - * `process.report.directory`, or the current working directory of the Node.js process, - * if unspecified. - * @param error A custom error used for reporting the JavaScript stack. - * @return Filename of the generated report. - */ - writeReport(fileName?: string): string; - writeReport(error?: Error): string; - writeReport(fileName?: string, err?: Error): string; - } - interface ResourceUsage { - fsRead: number; - fsWrite: number; - involuntaryContextSwitches: number; - ipcReceived: number; - ipcSent: number; - majorPageFault: number; - maxRSS: number; - minorPageFault: number; - sharedMemorySize: number; - signalsCount: number; - swappedOut: number; - systemCPUTime: number; - unsharedDataSize: number; - unsharedStackSize: number; - userCPUTime: number; - voluntaryContextSwitches: number; - } - interface EmitWarningOptions { - /** - * When `warning` is a `string`, `type` is the name to use for the _type_ of warning being emitted. - * - * @default 'Warning' - */ - type?: string | undefined; - /** - * A unique identifier for the warning instance being emitted. - */ - code?: string | undefined; - /** - * When `warning` is a `string`, `ctor` is an optional function used to limit the generated stack trace. - * - * @default process.emitWarning - */ - ctor?: Function | undefined; - /** - * Additional text to include with the error. - */ - detail?: string | undefined; - } - interface ProcessConfig { - readonly target_defaults: { - readonly cflags: any[]; - readonly default_configuration: string; - readonly defines: string[]; - readonly include_dirs: string[]; - readonly libraries: string[]; - }; - readonly variables: { - readonly clang: number; - readonly host_arch: string; - readonly node_install_npm: boolean; - readonly node_install_waf: boolean; - readonly node_prefix: string; - readonly node_shared_openssl: boolean; - readonly node_shared_v8: boolean; - readonly node_shared_zlib: boolean; - readonly node_use_dtrace: boolean; - readonly node_use_etw: boolean; - readonly node_use_openssl: boolean; - readonly target_arch: string; - readonly v8_no_strict_aliasing: number; - readonly v8_use_snapshot: boolean; - readonly visibility: string; - }; - } - interface Process extends EventEmitter { - /** - * The `process.stdout` property returns a stream connected to`stdout` (fd `1`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `1` refers to a file, in which case it is - * a `Writable` stream. - * - * For example, to copy `process.stdin` to `process.stdout`: - * - * ```js - * import { stdin, stdout } from 'node:process'; - * - * stdin.pipe(stdout); - * ``` - * - * `process.stdout` differs from other Node.js streams in important ways. See `note on process I/O` for more information. - */ - stdout: WriteStream & { - fd: 1; - }; - /** - * The `process.stderr` property returns a stream connected to`stderr` (fd `2`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `2` refers to a file, in which case it is - * a `Writable` stream. - * - * `process.stderr` differs from other Node.js streams in important ways. See `note on process I/O` for more information. - */ - stderr: WriteStream & { - fd: 2; - }; - /** - * The `process.stdin` property returns a stream connected to`stdin` (fd `0`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `0` refers to a file, in which case it is - * a `Readable` stream. - * - * For details of how to read from `stdin` see `readable.read()`. - * - * As a `Duplex` stream, `process.stdin` can also be used in "old" mode that - * is compatible with scripts written for Node.js prior to v0.10\. - * For more information see `Stream compatibility`. - * - * In "old" streams mode the `stdin` stream is paused by default, so one - * must call `process.stdin.resume()` to read from it. Note also that calling`process.stdin.resume()` itself would switch stream to "old" mode. - */ - stdin: ReadStream & { - fd: 0; - }; - openStdin(): Socket; - /** - * The `process.argv` property returns an array containing the command-line - * arguments passed when the Node.js process was launched. The first element will - * be {@link execPath}. See `process.argv0` if access to the original value - * of `argv[0]` is needed. The second element will be the path to the JavaScript - * file being executed. The remaining elements will be any additional command-line - * arguments. - * - * For example, assuming the following script for `process-args.js`: - * - * ```js - * import { argv } from 'node:process'; - * - * // print process.argv - * argv.forEach((val, index) => { - * console.log(`${index}: ${val}`); - * }); - * ``` - * - * Launching the Node.js process as: - * - * ```bash - * node process-args.js one two=three four - * ``` - * - * Would generate the output: - * - * ```text - * 0: /usr/local/bin/node - * 1: /Users/mjr/work/node/process-args.js - * 2: one - * 3: two=three - * 4: four - * ``` - * @since v0.1.27 - */ - argv: string[]; - /** - * The `process.argv0` property stores a read-only copy of the original value of`argv[0]` passed when Node.js starts. - * - * ```console - * $ bash -c 'exec -a customArgv0 ./node' - * > process.argv[0] - * '/Volumes/code/external/node/out/Release/node' - * > process.argv0 - * 'customArgv0' - * ``` - * @since v6.4.0 - */ - argv0: string; - /** - * The `process.execArgv` property returns the set of Node.js-specific command-line - * options passed when the Node.js process was launched. These options do not - * appear in the array returned by the {@link argv} property, and do not - * include the Node.js executable, the name of the script, or any options following - * the script name. These options are useful in order to spawn child processes with - * the same execution environment as the parent. - * - * ```bash - * node --harmony script.js --version - * ``` - * - * Results in `process.execArgv`: - * - * ```js - * ['--harmony'] - * ``` - * - * And `process.argv`: - * - * ```js - * ['/usr/local/bin/node', 'script.js', '--version'] - * ``` - * - * Refer to `Worker constructor` for the detailed behavior of worker - * threads with this property. - * @since v0.7.7 - */ - execArgv: string[]; - /** - * The `process.execPath` property returns the absolute pathname of the executable - * that started the Node.js process. Symbolic links, if any, are resolved. - * - * ```js - * '/usr/local/bin/node' - * ``` - * @since v0.1.100 - */ - execPath: string; - /** - * The `process.abort()` method causes the Node.js process to exit immediately and - * generate a core file. - * - * This feature is not available in `Worker` threads. - * @since v0.7.0 - */ - abort(): never; - /** - * The `process.chdir()` method changes the current working directory of the - * Node.js process or throws an exception if doing so fails (for instance, if - * the specified `directory` does not exist). - * - * ```js - * import { chdir, cwd } from 'node:process'; - * - * console.log(`Starting directory: ${cwd()}`); - * try { - * chdir('/tmp'); - * console.log(`New directory: ${cwd()}`); - * } catch (err) { - * console.error(`chdir: ${err}`); - * } - * ``` - * - * This feature is not available in `Worker` threads. - * @since v0.1.17 - */ - chdir(directory: string): void; - /** - * The `process.cwd()` method returns the current working directory of the Node.js - * process. - * - * ```js - * import { cwd } from 'node:process'; - * - * console.log(`Current directory: ${cwd()}`); - * ``` - * @since v0.1.8 - */ - cwd(): string; - /** - * The port used by the Node.js debugger when enabled. - * - * ```js - * import process from 'node:process'; - * - * process.debugPort = 5858; - * ``` - * @since v0.7.2 - */ - debugPort: number; - /** - * The `process.emitWarning()` method can be used to emit custom or application - * specific process warnings. These can be listened for by adding a handler to the `'warning'` event. - * - * ```js - * import { emitWarning } from 'node:process'; - * - * // Emit a warning with a code and additional detail. - * emitWarning('Something happened!', { - * code: 'MY_WARNING', - * detail: 'This is some additional information', - * }); - * // Emits: - * // (node:56338) [MY_WARNING] Warning: Something happened! - * // This is some additional information - * ``` - * - * In this example, an `Error` object is generated internally by`process.emitWarning()` and passed through to the `'warning'` handler. - * - * ```js - * import process from 'node:process'; - * - * process.on('warning', (warning) => { - * console.warn(warning.name); // 'Warning' - * console.warn(warning.message); // 'Something happened!' - * console.warn(warning.code); // 'MY_WARNING' - * console.warn(warning.stack); // Stack trace - * console.warn(warning.detail); // 'This is some additional information' - * }); - * ``` - * - * If `warning` is passed as an `Error` object, the `options` argument is ignored. - * @since v8.0.0 - * @param warning The warning to emit. - */ - emitWarning(warning: string | Error, ctor?: Function): void; - emitWarning(warning: string | Error, type?: string, ctor?: Function): void; - emitWarning(warning: string | Error, type?: string, code?: string, ctor?: Function): void; - emitWarning(warning: string | Error, options?: EmitWarningOptions): void; - /** - * The `process.env` property returns an object containing the user environment. - * See [`environ(7)`](http://man7.org/linux/man-pages/man7/environ.7.html). - * - * An example of this object looks like: - * - * ```js - * { - * TERM: 'xterm-256color', - * SHELL: '/usr/local/bin/bash', - * USER: 'maciej', - * PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', - * PWD: '/Users/maciej', - * EDITOR: 'vim', - * SHLVL: '1', - * HOME: '/Users/maciej', - * LOGNAME: 'maciej', - * _: '/usr/local/bin/node' - * } - * ``` - * - * It is possible to modify this object, but such modifications will not be - * reflected outside the Node.js process, or (unless explicitly requested) - * to other `Worker` threads. - * In other words, the following example would not work: - * - * ```bash - * node -e 'process.env.foo = "bar"' && echo $foo - * ``` - * - * While the following will: - * - * ```js - * import { env } from 'node:process'; - * - * env.foo = 'bar'; - * console.log(env.foo); - * ``` - * - * Assigning a property on `process.env` will implicitly convert the value - * to a string. **This behavior is deprecated.** Future versions of Node.js may - * throw an error when the value is not a string, number, or boolean. - * - * ```js - * import { env } from 'node:process'; - * - * env.test = null; - * console.log(env.test); - * // => 'null' - * env.test = undefined; - * console.log(env.test); - * // => 'undefined' - * ``` - * - * Use `delete` to delete a property from `process.env`. - * - * ```js - * import { env } from 'node:process'; - * - * env.TEST = 1; - * delete env.TEST; - * console.log(env.TEST); - * // => undefined - * ``` - * - * On Windows operating systems, environment variables are case-insensitive. - * - * ```js - * import { env } from 'node:process'; - * - * env.TEST = 1; - * console.log(env.test); - * // => 1 - * ``` - * - * Unless explicitly specified when creating a `Worker` instance, - * each `Worker` thread has its own copy of `process.env`, based on its - * parent thread's `process.env`, or whatever was specified as the `env` option - * to the `Worker` constructor. Changes to `process.env` will not be visible - * across `Worker` threads, and only the main thread can make changes that - * are visible to the operating system or to native add-ons. On Windows, a copy of`process.env` on a `Worker` instance operates in a case-sensitive manner - * unlike the main thread. - * @since v0.1.27 - */ - env: ProcessEnv; - /** - * The `process.exit()` method instructs Node.js to terminate the process - * synchronously with an exit status of `code`. If `code` is omitted, exit uses - * either the 'success' code `0` or the value of `process.exitCode` if it has been - * set. Node.js will not terminate until all the `'exit'` event listeners are - * called. - * - * To exit with a 'failure' code: - * - * ```js - * import { exit } from 'node:process'; - * - * exit(1); - * ``` - * - * The shell that executed Node.js should see the exit code as `1`. - * - * Calling `process.exit()` will force the process to exit as quickly as possible - * even if there are still asynchronous operations pending that have not yet - * completed fully, including I/O operations to `process.stdout` and`process.stderr`. - * - * In most situations, it is not actually necessary to call `process.exit()`explicitly. The Node.js process will exit on its own _if there is no additional_ - * _work pending_ in the event loop. The `process.exitCode` property can be set to - * tell the process which exit code to use when the process exits gracefully. - * - * For instance, the following example illustrates a _misuse_ of the`process.exit()` method that could lead to data printed to stdout being - * truncated and lost: - * - * ```js - * import { exit } from 'node:process'; - * - * // This is an example of what *not* to do: - * if (someConditionNotMet()) { - * printUsageToStdout(); - * exit(1); - * } - * ``` - * - * The reason this is problematic is because writes to `process.stdout` in Node.js - * are sometimes _asynchronous_ and may occur over multiple ticks of the Node.js - * event loop. Calling `process.exit()`, however, forces the process to exit _before_ those additional writes to `stdout` can be performed. - * - * Rather than calling `process.exit()` directly, the code _should_ set the`process.exitCode` and allow the process to exit naturally by avoiding - * scheduling any additional work for the event loop: - * - * ```js - * import process from 'node:process'; - * - * // How to properly set the exit code while letting - * // the process exit gracefully. - * if (someConditionNotMet()) { - * printUsageToStdout(); - * process.exitCode = 1; - * } - * ``` - * - * If it is necessary to terminate the Node.js process due to an error condition, - * throwing an _uncaught_ error and allowing the process to terminate accordingly - * is safer than calling `process.exit()`. - * - * In `Worker` threads, this function stops the current thread rather - * than the current process. - * @since v0.1.13 - * @param [code=0] The exit code. For string type, only integer strings (e.g.,'1') are allowed. - */ - exit(code?: number): never; - /** - * A number which will be the process exit code, when the process either - * exits gracefully, or is exited via {@link exit} without specifying - * a code. - * - * Specifying a code to {@link exit} will override any - * previous setting of `process.exitCode`. - * @since v0.11.8 - */ - exitCode?: number | undefined; - /** - * The `process.getgid()` method returns the numerical group identity of the - * process. (See [`getgid(2)`](http://man7.org/linux/man-pages/man2/getgid.2.html).) - * - * ```js - * import process from 'process'; - * - * if (process.getgid) { - * console.log(`Current gid: ${process.getgid()}`); - * } - * ``` - * - * This function is only available on POSIX platforms (i.e. not Windows or - * Android). - * @since v0.1.31 - */ - getgid?: () => number; - /** - * The `process.setgid()` method sets the group identity of the process. (See [`setgid(2)`](http://man7.org/linux/man-pages/man2/setgid.2.html).) The `id` can be passed as either a - * numeric ID or a group name - * string. If a group name is specified, this method blocks while resolving the - * associated numeric ID. - * - * ```js - * import process from 'process'; - * - * if (process.getgid && process.setgid) { - * console.log(`Current gid: ${process.getgid()}`); - * try { - * process.setgid(501); - * console.log(`New gid: ${process.getgid()}`); - * } catch (err) { - * console.log(`Failed to set gid: ${err}`); - * } - * } - * ``` - * - * This function is only available on POSIX platforms (i.e. not Windows or - * Android). - * This feature is not available in `Worker` threads. - * @since v0.1.31 - * @param id The group name or ID - */ - setgid?: (id: number | string) => void; - /** - * The `process.getuid()` method returns the numeric user identity of the process. - * (See [`getuid(2)`](http://man7.org/linux/man-pages/man2/getuid.2.html).) - * - * ```js - * import process from 'process'; - * - * if (process.getuid) { - * console.log(`Current uid: ${process.getuid()}`); - * } - * ``` - * - * This function is only available on POSIX platforms (i.e. not Windows or - * Android). - * @since v0.1.28 - */ - getuid?: () => number; - /** - * The `process.setuid(id)` method sets the user identity of the process. (See [`setuid(2)`](http://man7.org/linux/man-pages/man2/setuid.2.html).) The `id` can be passed as either a - * numeric ID or a username string. - * If a username is specified, the method blocks while resolving the associated - * numeric ID. - * - * ```js - * import process from 'process'; - * - * if (process.getuid && process.setuid) { - * console.log(`Current uid: ${process.getuid()}`); - * try { - * process.setuid(501); - * console.log(`New uid: ${process.getuid()}`); - * } catch (err) { - * console.log(`Failed to set uid: ${err}`); - * } - * } - * ``` - * - * This function is only available on POSIX platforms (i.e. not Windows or - * Android). - * This feature is not available in `Worker` threads. - * @since v0.1.28 - */ - setuid?: (id: number | string) => void; - /** - * The `process.geteuid()` method returns the numerical effective user identity of - * the process. (See [`geteuid(2)`](http://man7.org/linux/man-pages/man2/geteuid.2.html).) - * - * ```js - * import process from 'process'; - * - * if (process.geteuid) { - * console.log(`Current uid: ${process.geteuid()}`); - * } - * ``` - * - * This function is only available on POSIX platforms (i.e. not Windows or - * Android). - * @since v2.0.0 - */ - geteuid?: () => number; - /** - * The `process.seteuid()` method sets the effective user identity of the process. - * (See [`seteuid(2)`](http://man7.org/linux/man-pages/man2/seteuid.2.html).) The `id` can be passed as either a numeric ID or a username - * string. If a username is specified, the method blocks while resolving the - * associated numeric ID. - * - * ```js - * import process from 'process'; - * - * if (process.geteuid && process.seteuid) { - * console.log(`Current uid: ${process.geteuid()}`); - * try { - * process.seteuid(501); - * console.log(`New uid: ${process.geteuid()}`); - * } catch (err) { - * console.log(`Failed to set uid: ${err}`); - * } - * } - * ``` - * - * This function is only available on POSIX platforms (i.e. not Windows or - * Android). - * This feature is not available in `Worker` threads. - * @since v2.0.0 - * @param id A user name or ID - */ - seteuid?: (id: number | string) => void; - /** - * The `process.getegid()` method returns the numerical effective group identity - * of the Node.js process. (See [`getegid(2)`](http://man7.org/linux/man-pages/man2/getegid.2.html).) - * - * ```js - * import process from 'process'; - * - * if (process.getegid) { - * console.log(`Current gid: ${process.getegid()}`); - * } - * ``` - * - * This function is only available on POSIX platforms (i.e. not Windows or - * Android). - * @since v2.0.0 - */ - getegid?: () => number; - /** - * The `process.setegid()` method sets the effective group identity of the process. - * (See [`setegid(2)`](http://man7.org/linux/man-pages/man2/setegid.2.html).) The `id` can be passed as either a numeric ID or a group - * name string. If a group name is specified, this method blocks while resolving - * the associated a numeric ID. - * - * ```js - * import process from 'process'; - * - * if (process.getegid && process.setegid) { - * console.log(`Current gid: ${process.getegid()}`); - * try { - * process.setegid(501); - * console.log(`New gid: ${process.getegid()}`); - * } catch (err) { - * console.log(`Failed to set gid: ${err}`); - * } - * } - * ``` - * - * This function is only available on POSIX platforms (i.e. not Windows or - * Android). - * This feature is not available in `Worker` threads. - * @since v2.0.0 - * @param id A group name or ID - */ - setegid?: (id: number | string) => void; - /** - * The `process.getgroups()` method returns an array with the supplementary group - * IDs. POSIX leaves it unspecified if the effective group ID is included but - * Node.js ensures it always is. - * - * ```js - * import process from 'process'; - * - * if (process.getgroups) { - * console.log(process.getgroups()); // [ 16, 21, 297 ] - * } - * ``` - * - * This function is only available on POSIX platforms (i.e. not Windows or - * Android). - * @since v0.9.4 - */ - getgroups?: () => number[]; - /** - * The `process.setgroups()` method sets the supplementary group IDs for the - * Node.js process. This is a privileged operation that requires the Node.js - * process to have `root` or the `CAP_SETGID` capability. - * - * The `groups` array can contain numeric group IDs, group names, or both. - * - * ```js - * import process from 'process'; - * - * if (process.getgroups && process.setgroups) { - * try { - * process.setgroups([501]); - * console.log(process.getgroups()); // new groups - * } catch (err) { - * console.log(`Failed to set groups: ${err}`); - * } - * } - * ``` - * - * This function is only available on POSIX platforms (i.e. not Windows or - * Android). - * This feature is not available in `Worker` threads. - * @since v0.9.4 - */ - setgroups?: (groups: ReadonlyArray) => void; - /** - * The `process.setUncaughtExceptionCaptureCallback()` function sets a function - * that will be invoked when an uncaught exception occurs, which will receive the - * exception value itself as its first argument. - * - * If such a function is set, the `'uncaughtException'` event will - * not be emitted. If `--abort-on-uncaught-exception` was passed from the - * command line or set through `v8.setFlagsFromString()`, the process will - * not abort. Actions configured to take place on exceptions such as report - * generations will be affected too - * - * To unset the capture function,`process.setUncaughtExceptionCaptureCallback(null)` may be used. Calling this - * method with a non-`null` argument while another capture function is set will - * throw an error. - * - * Using this function is mutually exclusive with using the deprecated `domain` built-in module. - * @since v9.3.0 - */ - setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; - /** - * Indicates whether a callback has been set using {@link setUncaughtExceptionCaptureCallback}. - * @since v9.3.0 - */ - hasUncaughtExceptionCaptureCallback(): boolean; - /** - * The `process.sourceMapsEnabled` property returns whether the [Source Map v3](https://sourcemaps.info/spec.html) support for stack traces is enabled. - * @since v20.7.0 - * @experimental - */ - readonly sourceMapsEnabled: boolean; - /** - * This function enables or disables the [Source Map v3](https://sourcemaps.info/spec.html) support for - * stack traces. - * - * It provides same features as launching Node.js process with commandline options`--enable-source-maps`. - * - * Only source maps in JavaScript files that are loaded after source maps has been - * enabled will be parsed and loaded. - * @since v16.6.0, v14.18.0 - * @experimental - */ - setSourceMapsEnabled(value: boolean): void; - /** - * The `process.version` property contains the Node.js version string. - * - * ```js - * import { version } from 'node:process'; - * - * console.log(`Version: ${version}`); - * // Version: v14.8.0 - * ``` - * - * To get the version string without the prepended _v_, use`process.versions.node`. - * @since v0.1.3 - */ - readonly version: string; - /** - * The `process.versions` property returns an object listing the version strings of - * Node.js and its dependencies. `process.versions.modules` indicates the current - * ABI version, which is increased whenever a C++ API changes. Node.js will refuse - * to load modules that were compiled against a different module ABI version. - * - * ```js - * import { versions } from 'node:process'; - * - * console.log(versions); - * ``` - * - * Will generate an object similar to: - * - * ```console - * { node: '20.2.0', - * acorn: '8.8.2', - * ada: '2.4.0', - * ares: '1.19.0', - * base64: '0.5.0', - * brotli: '1.0.9', - * cjs_module_lexer: '1.2.2', - * cldr: '43.0', - * icu: '73.1', - * llhttp: '8.1.0', - * modules: '115', - * napi: '8', - * nghttp2: '1.52.0', - * nghttp3: '0.7.0', - * ngtcp2: '0.8.1', - * openssl: '3.0.8+quic', - * simdutf: '3.2.9', - * tz: '2023c', - * undici: '5.22.0', - * unicode: '15.0', - * uv: '1.44.2', - * uvwasi: '0.0.16', - * v8: '11.3.244.8-node.9', - * zlib: '1.2.13' } - * ``` - * @since v0.2.0 - */ - readonly versions: ProcessVersions; - /** - * The `process.config` property returns a frozen `Object` containing the - * JavaScript representation of the configure options used to compile the current - * Node.js executable. This is the same as the `config.gypi` file that was produced - * when running the `./configure` script. - * - * An example of the possible output looks like: - * - * ```js - * { - * target_defaults: - * { cflags: [], - * default_configuration: 'Release', - * defines: [], - * include_dirs: [], - * libraries: [] }, - * variables: - * { - * host_arch: 'x64', - * napi_build_version: 5, - * node_install_npm: 'true', - * node_prefix: '', - * node_shared_cares: 'false', - * node_shared_http_parser: 'false', - * node_shared_libuv: 'false', - * node_shared_zlib: 'false', - * node_use_openssl: 'true', - * node_shared_openssl: 'false', - * strict_aliasing: 'true', - * target_arch: 'x64', - * v8_use_snapshot: 1 - * } - * } - * ``` - * @since v0.7.7 - */ - readonly config: ProcessConfig; - /** - * The `process.kill()` method sends the `signal` to the process identified by`pid`. - * - * Signal names are strings such as `'SIGINT'` or `'SIGHUP'`. See `Signal Events` and [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for more information. - * - * This method will throw an error if the target `pid` does not exist. As a special - * case, a signal of `0` can be used to test for the existence of a process. - * Windows platforms will throw an error if the `pid` is used to kill a process - * group. - * - * Even though the name of this function is `process.kill()`, it is really just a - * signal sender, like the `kill` system call. The signal sent may do something - * other than kill the target process. - * - * ```js - * import process, { kill } from 'node:process'; - * - * process.on('SIGHUP', () => { - * console.log('Got SIGHUP signal.'); - * }); - * - * setTimeout(() => { - * console.log('Exiting.'); - * process.exit(0); - * }, 100); - * - * kill(process.pid, 'SIGHUP'); - * ``` - * - * When `SIGUSR1` is received by a Node.js process, Node.js will start the - * debugger. See `Signal Events`. - * @since v0.0.6 - * @param pid A process ID - * @param [signal='SIGTERM'] The signal to send, either as a string or number. - */ - kill(pid: number, signal?: string | number): true; - /** - * The `process.pid` property returns the PID of the process. - * - * ```js - * import { pid } from 'node:process'; - * - * console.log(`This process is pid ${pid}`); - * ``` - * @since v0.1.15 - */ - readonly pid: number; - /** - * The `process.ppid` property returns the PID of the parent of the - * current process. - * - * ```js - * import { ppid } from 'node:process'; - * - * console.log(`The parent process is pid ${ppid}`); - * ``` - * @since v9.2.0, v8.10.0, v6.13.0 - */ - readonly ppid: number; - /** - * The `process.title` property returns the current process title (i.e. returns - * the current value of `ps`). Assigning a new value to `process.title` modifies - * the current value of `ps`. - * - * When a new value is assigned, different platforms will impose different maximum - * length restrictions on the title. Usually such restrictions are quite limited. - * For instance, on Linux and macOS, `process.title` is limited to the size of the - * binary name plus the length of the command-line arguments because setting the`process.title` overwrites the `argv` memory of the process. Node.js v0.8 - * allowed for longer process title strings by also overwriting the `environ`memory but that was potentially insecure and confusing in some (rather obscure) - * cases. - * - * Assigning a value to `process.title` might not result in an accurate label - * within process manager applications such as macOS Activity Monitor or Windows - * Services Manager. - * @since v0.1.104 - */ - title: string; - /** - * The operating system CPU architecture for which the Node.js binary was compiled. - * Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`, `'mips'`,`'mipsel'`, `'ppc'`, `'ppc64'`, `'riscv64'`, `'s390'`, `'s390x'`, and `'x64'`. - * - * ```js - * import { arch } from 'node:process'; - * - * console.log(`This processor architecture is ${arch}`); - * ``` - * @since v0.5.0 - */ - readonly arch: Architecture; - /** - * The `process.platform` property returns a string identifying the operating - * system platform for which the Node.js binary was compiled. - * - * Currently possible values are: - * - * * `'aix'` - * * `'darwin'` - * * `'freebsd'` - * * `'linux'` - * * `'openbsd'` - * * `'sunos'` - * * `'win32'` - * - * ```js - * import { platform } from 'node:process'; - * - * console.log(`This platform is ${platform}`); - * ``` - * - * The value `'android'` may also be returned if the Node.js is built on the - * Android operating system. However, Android support in Node.js [is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). - * @since v0.1.16 - */ - readonly platform: Platform; - /** - * The `process.mainModule` property provides an alternative way of retrieving `require.main`. The difference is that if the main module changes at - * runtime, `require.main` may still refer to the original main module in - * modules that were required before the change occurred. Generally, it's - * safe to assume that the two refer to the same module. - * - * As with `require.main`, `process.mainModule` will be `undefined` if there - * is no entry script. - * @since v0.1.17 - * @deprecated Since v14.0.0 - Use `main` instead. - */ - mainModule?: Module | undefined; - memoryUsage: MemoryUsageFn; - /** - * Gets the amount of memory available to the process (in bytes) based on - * limits imposed by the OS. If there is no such constraint, or the constraint - * is unknown, `undefined` is returned. - * - * See [`uv_get_constrained_memory`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_get_constrained_memory) for more - * information. - * @since v19.6.0, v18.15.0 - * @experimental - */ - constrainedMemory(): number | undefined; - /** - * The `process.cpuUsage()` method returns the user and system CPU time usage of - * the current process, in an object with properties `user` and `system`, whose - * values are microsecond values (millionth of a second). These values measure time - * spent in user and system code respectively, and may end up being greater than - * actual elapsed time if multiple CPU cores are performing work for this process. - * - * The result of a previous call to `process.cpuUsage()` can be passed as the - * argument to the function, to get a diff reading. - * - * ```js - * import { cpuUsage } from 'node:process'; - * - * const startUsage = cpuUsage(); - * // { user: 38579, system: 6986 } - * - * // spin the CPU for 500 milliseconds - * const now = Date.now(); - * while (Date.now() - now < 500); - * - * console.log(cpuUsage(startUsage)); - * // { user: 514883, system: 11226 } - * ``` - * @since v6.1.0 - * @param previousValue A previous return value from calling `process.cpuUsage()` - */ - cpuUsage(previousValue?: CpuUsage): CpuUsage; - /** - * `process.nextTick()` adds `callback` to the "next tick queue". This queue is - * fully drained after the current operation on the JavaScript stack runs to - * completion and before the event loop is allowed to continue. It's possible to - * create an infinite loop if one were to recursively call `process.nextTick()`. - * See the [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#process-nexttick) guide for more background. - * - * ```js - * import { nextTick } from 'node:process'; - * - * console.log('start'); - * nextTick(() => { - * console.log('nextTick callback'); - * }); - * console.log('scheduled'); - * // Output: - * // start - * // scheduled - * // nextTick callback - * ``` - * - * This is important when developing APIs in order to give users the opportunity - * to assign event handlers _after_ an object has been constructed but before any - * I/O has occurred: - * - * ```js - * import { nextTick } from 'node:process'; - * - * function MyThing(options) { - * this.setupOptions(options); - * - * nextTick(() => { - * this.startDoingStuff(); - * }); - * } - * - * const thing = new MyThing(); - * thing.getReadyForStuff(); - * - * // thing.startDoingStuff() gets called now, not before. - * ``` - * - * It is very important for APIs to be either 100% synchronous or 100% - * asynchronous. Consider this example: - * - * ```js - * // WARNING! DO NOT USE! BAD UNSAFE HAZARD! - * function maybeSync(arg, cb) { - * if (arg) { - * cb(); - * return; - * } - * - * fs.stat('file', cb); - * } - * ``` - * - * This API is hazardous because in the following case: - * - * ```js - * const maybeTrue = Math.random() > 0.5; - * - * maybeSync(maybeTrue, () => { - * foo(); - * }); - * - * bar(); - * ``` - * - * It is not clear whether `foo()` or `bar()` will be called first. - * - * The following approach is much better: - * - * ```js - * import { nextTick } from 'node:process'; - * - * function definitelyAsync(arg, cb) { - * if (arg) { - * nextTick(cb); - * return; - * } - * - * fs.stat('file', cb); - * } - * ``` - * @since v0.1.26 - * @param args Additional arguments to pass when invoking the `callback` - */ - nextTick(callback: Function, ...args: any[]): void; - /** - * The `process.release` property returns an `Object` containing metadata related - * to the current release, including URLs for the source tarball and headers-only - * tarball. - * - * `process.release` contains the following properties: - * - * ```js - * { - * name: 'node', - * lts: 'Hydrogen', - * sourceUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0.tar.gz', - * headersUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0-headers.tar.gz', - * libUrl: 'https://nodejs.org/download/release/v18.12.0/win-x64/node.lib' - * } - * ``` - * - * In custom builds from non-release versions of the source tree, only the`name` property may be present. The additional properties should not be - * relied upon to exist. - * @since v3.0.0 - */ - readonly release: ProcessRelease; - features: { - inspector: boolean; - debug: boolean; - uv: boolean; - ipv6: boolean; - tls_alpn: boolean; - tls_sni: boolean; - tls_ocsp: boolean; - tls: boolean; - }; - /** - * `process.umask()` returns the Node.js process's file mode creation mask. Child - * processes inherit the mask from the parent process. - * @since v0.1.19 - * @deprecated Calling `process.umask()` with no argument causes the process-wide umask to be written twice. This introduces a race condition between threads, and is a potential * - * security vulnerability. There is no safe, cross-platform alternative API. - */ - umask(): number; - /** - * Can only be set if not in worker thread. - */ - umask(mask: string | number): number; - /** - * The `process.uptime()` method returns the number of seconds the current Node.js - * process has been running. - * - * The return value includes fractions of a second. Use `Math.floor()` to get whole - * seconds. - * @since v0.5.0 - */ - uptime(): number; - hrtime: HRTime; - /** - * If the Node.js process was spawned with an IPC channel, the process.channel property is a reference to the IPC channel. - * If no IPC channel exists, this property is undefined. - * @since v7.1.0 - */ - channel?: { - /** - * This method makes the IPC channel keep the event loop of the process running if .unref() has been called before. - * @since v7.1.0 - */ - ref(): void; - /** - * This method makes the IPC channel not keep the event loop of the process running, and lets it finish even while the channel is open. - * @since v7.1.0 - */ - unref(): void; - }; - /** - * If Node.js is spawned with an IPC channel, the `process.send()` method can be - * used to send messages to the parent process. Messages will be received as a `'message'` event on the parent's `ChildProcess` object. - * - * If Node.js was not spawned with an IPC channel, `process.send` will be `undefined`. - * - * The message goes through serialization and parsing. The resulting message might - * not be the same as what is originally sent. - * @since v0.5.9 - * @param options used to parameterize the sending of certain types of handles.`options` supports the following properties: - */ - send?( - message: any, - sendHandle?: any, - options?: { - swallowErrors?: boolean | undefined; - }, - callback?: (error: Error | null) => void, - ): boolean; - /** - * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.disconnect()` method will close the - * IPC channel to the parent process, allowing the child process to exit gracefully - * once there are no other connections keeping it alive. - * - * The effect of calling `process.disconnect()` is the same as calling `ChildProcess.disconnect()` from the parent process. - * - * If the Node.js process was not spawned with an IPC channel,`process.disconnect()` will be `undefined`. - * @since v0.7.2 - */ - disconnect(): void; - /** - * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.connected` property will return`true` so long as the IPC - * channel is connected and will return `false` after`process.disconnect()` is called. - * - * Once `process.connected` is `false`, it is no longer possible to send messages - * over the IPC channel using `process.send()`. - * @since v0.7.2 - */ - connected: boolean; - /** - * The `process.allowedNodeEnvironmentFlags` property is a special, - * read-only `Set` of flags allowable within the `NODE_OPTIONS` environment variable. - * - * `process.allowedNodeEnvironmentFlags` extends `Set`, but overrides`Set.prototype.has` to recognize several different possible flag - * representations. `process.allowedNodeEnvironmentFlags.has()` will - * return `true` in the following cases: - * - * * Flags may omit leading single (`-`) or double (`--`) dashes; e.g.,`inspect-brk` for `--inspect-brk`, or `r` for `-r`. - * * Flags passed through to V8 (as listed in `--v8-options`) may replace - * one or more _non-leading_ dashes for an underscore, or vice-versa; - * e.g., `--perf_basic_prof`, `--perf-basic-prof`, `--perf_basic-prof`, - * etc. - * * Flags may contain one or more equals (`=`) characters; all - * characters after and including the first equals will be ignored; - * e.g., `--stack-trace-limit=100`. - * * Flags _must_ be allowable within `NODE_OPTIONS`. - * - * When iterating over `process.allowedNodeEnvironmentFlags`, flags will - * appear only _once_; each will begin with one or more dashes. Flags - * passed through to V8 will contain underscores instead of non-leading - * dashes: - * - * ```js - * import { allowedNodeEnvironmentFlags } from 'node:process'; - * - * allowedNodeEnvironmentFlags.forEach((flag) => { - * // -r - * // --inspect-brk - * // --abort_on_uncaught_exception - * // ... - * }); - * ``` - * - * The methods `add()`, `clear()`, and `delete()` of`process.allowedNodeEnvironmentFlags` do nothing, and will fail - * silently. - * - * If Node.js was compiled _without_ `NODE_OPTIONS` support (shown in {@link config}), `process.allowedNodeEnvironmentFlags` will - * contain what _would have_ been allowable. - * @since v10.10.0 - */ - allowedNodeEnvironmentFlags: ReadonlySet; - /** - * `process.report` is an object whose methods are used to generate diagnostic - * reports for the current process. Additional documentation is available in the `report documentation`. - * @since v11.8.0 - */ - report?: ProcessReport | undefined; - /** - * ```js - * import { resourceUsage } from 'node:process'; - * - * console.log(resourceUsage()); - * /* - * Will output: - * { - * userCPUTime: 82872, - * systemCPUTime: 4143, - * maxRSS: 33164, - * sharedMemorySize: 0, - * unsharedDataSize: 0, - * unsharedStackSize: 0, - * minorPageFault: 2469, - * majorPageFault: 0, - * swappedOut: 0, - * fsRead: 0, - * fsWrite: 8, - * ipcSent: 0, - * ipcReceived: 0, - * signalsCount: 0, - * voluntaryContextSwitches: 79, - * involuntaryContextSwitches: 1 - * } - * - * ``` - * @since v12.6.0 - * @return the resource usage for the current process. All of these values come from the `uv_getrusage` call which returns a [`uv_rusage_t` struct][uv_rusage_t]. - */ - resourceUsage(): ResourceUsage; - /** - * The `process.traceDeprecation` property indicates whether the`--trace-deprecation` flag is set on the current Node.js process. See the - * documentation for the `'warning' event` and the `emitWarning() method` for more information about this - * flag's behavior. - * @since v0.8.0 - */ - traceDeprecation: boolean; - /* EventEmitter */ - addListener(event: "beforeExit", listener: BeforeExitListener): this; - addListener(event: "disconnect", listener: DisconnectListener): this; - addListener(event: "exit", listener: ExitListener): this; - addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; - addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; - addListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; - addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - addListener(event: "warning", listener: WarningListener): this; - addListener(event: "message", listener: MessageListener): this; - addListener(event: Signals, listener: SignalsListener): this; - addListener(event: "multipleResolves", listener: MultipleResolveListener): this; - addListener(event: "worker", listener: WorkerListener): this; - emit(event: "beforeExit", code: number): boolean; - emit(event: "disconnect"): boolean; - emit(event: "exit", code: number): boolean; - emit(event: "rejectionHandled", promise: Promise): boolean; - emit(event: "uncaughtException", error: Error): boolean; - emit(event: "uncaughtExceptionMonitor", error: Error): boolean; - emit(event: "unhandledRejection", reason: unknown, promise: Promise): boolean; - emit(event: "warning", warning: Error): boolean; - emit(event: "message", message: unknown, sendHandle: unknown): this; - emit(event: Signals, signal?: Signals): boolean; - emit( - event: "multipleResolves", - type: MultipleResolveType, - promise: Promise, - value: unknown, - ): this; - emit(event: "worker", listener: WorkerListener): this; - on(event: "beforeExit", listener: BeforeExitListener): this; - on(event: "disconnect", listener: DisconnectListener): this; - on(event: "exit", listener: ExitListener): this; - on(event: "rejectionHandled", listener: RejectionHandledListener): this; - on(event: "uncaughtException", listener: UncaughtExceptionListener): this; - on(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; - on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - on(event: "warning", listener: WarningListener): this; - on(event: "message", listener: MessageListener): this; - on(event: Signals, listener: SignalsListener): this; - on(event: "multipleResolves", listener: MultipleResolveListener): this; - on(event: "worker", listener: WorkerListener): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: "beforeExit", listener: BeforeExitListener): this; - once(event: "disconnect", listener: DisconnectListener): this; - once(event: "exit", listener: ExitListener): this; - once(event: "rejectionHandled", listener: RejectionHandledListener): this; - once(event: "uncaughtException", listener: UncaughtExceptionListener): this; - once(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; - once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - once(event: "warning", listener: WarningListener): this; - once(event: "message", listener: MessageListener): this; - once(event: Signals, listener: SignalsListener): this; - once(event: "multipleResolves", listener: MultipleResolveListener): this; - once(event: "worker", listener: WorkerListener): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener(event: "beforeExit", listener: BeforeExitListener): this; - prependListener(event: "disconnect", listener: DisconnectListener): this; - prependListener(event: "exit", listener: ExitListener): this; - prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; - prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; - prependListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; - prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - prependListener(event: "warning", listener: WarningListener): this; - prependListener(event: "message", listener: MessageListener): this; - prependListener(event: Signals, listener: SignalsListener): this; - prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; - prependListener(event: "worker", listener: WorkerListener): this; - prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; - prependOnceListener(event: "disconnect", listener: DisconnectListener): this; - prependOnceListener(event: "exit", listener: ExitListener): this; - prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; - prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; - prependOnceListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; - prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - prependOnceListener(event: "warning", listener: WarningListener): this; - prependOnceListener(event: "message", listener: MessageListener): this; - prependOnceListener(event: Signals, listener: SignalsListener): this; - prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; - prependOnceListener(event: "worker", listener: WorkerListener): this; - listeners(event: "beforeExit"): BeforeExitListener[]; - listeners(event: "disconnect"): DisconnectListener[]; - listeners(event: "exit"): ExitListener[]; - listeners(event: "rejectionHandled"): RejectionHandledListener[]; - listeners(event: "uncaughtException"): UncaughtExceptionListener[]; - listeners(event: "uncaughtExceptionMonitor"): UncaughtExceptionListener[]; - listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; - listeners(event: "warning"): WarningListener[]; - listeners(event: "message"): MessageListener[]; - listeners(event: Signals): SignalsListener[]; - listeners(event: "multipleResolves"): MultipleResolveListener[]; - listeners(event: "worker"): WorkerListener[]; - } - } - } - export = process; -} -declare module "node:process" { - import process = require("process"); - export = process; -} diff --git a/node_modules/@types/node/ts4.8/punycode.d.ts b/node_modules/@types/node/ts4.8/punycode.d.ts deleted file mode 100644 index d2fc9f9a8ffbcffd5d9e966ef1d2b75fce902017..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/punycode.d.ts +++ /dev/null @@ -1,117 +0,0 @@ -/** - * **The version of the punycode module bundled in Node.js is being deprecated.**In a future major version of Node.js this module will be removed. Users - * currently depending on the `punycode` module should switch to using the - * userland-provided [Punycode.js](https://github.com/bestiejs/punycode.js) module instead. For punycode-based URL - * encoding, see `url.domainToASCII` or, more generally, the `WHATWG URL API`. - * - * The `punycode` module is a bundled version of the [Punycode.js](https://github.com/bestiejs/punycode.js) module. It - * can be accessed using: - * - * ```js - * const punycode = require('punycode'); - * ``` - * - * [Punycode](https://tools.ietf.org/html/rfc3492) is a character encoding scheme defined by RFC 3492 that is - * primarily intended for use in Internationalized Domain Names. Because host - * names in URLs are limited to ASCII characters only, Domain Names that contain - * non-ASCII characters must be converted into ASCII using the Punycode scheme. - * For instance, the Japanese character that translates into the English word,`'example'` is `'例'`. The Internationalized Domain Name, `'例.com'` (equivalent - * to `'example.com'`) is represented by Punycode as the ASCII string`'xn--fsq.com'`. - * - * The `punycode` module provides a simple implementation of the Punycode standard. - * - * The `punycode` module is a third-party dependency used by Node.js and - * made available to developers as a convenience. Fixes or other modifications to - * the module must be directed to the [Punycode.js](https://github.com/bestiejs/punycode.js) project. - * @deprecated Since v7.0.0 - Deprecated - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/punycode.js) - */ -declare module "punycode" { - /** - * The `punycode.decode()` method converts a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only - * characters to the equivalent string of Unicode codepoints. - * - * ```js - * punycode.decode('maana-pta'); // 'mañana' - * punycode.decode('--dqo34k'); // '☃-⌘' - * ``` - * @since v0.5.1 - */ - function decode(string: string): string; - /** - * The `punycode.encode()` method converts a string of Unicode codepoints to a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only characters. - * - * ```js - * punycode.encode('mañana'); // 'maana-pta' - * punycode.encode('☃-⌘'); // '--dqo34k' - * ``` - * @since v0.5.1 - */ - function encode(string: string): string; - /** - * The `punycode.toUnicode()` method converts a string representing a domain name - * containing [Punycode](https://tools.ietf.org/html/rfc3492) encoded characters into Unicode. Only the [Punycode](https://tools.ietf.org/html/rfc3492) encoded parts of the domain name are be - * converted. - * - * ```js - * // decode domain names - * punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com' - * punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com' - * punycode.toUnicode('example.com'); // 'example.com' - * ``` - * @since v0.6.1 - */ - function toUnicode(domain: string): string; - /** - * The `punycode.toASCII()` method converts a Unicode string representing an - * Internationalized Domain Name to [Punycode](https://tools.ietf.org/html/rfc3492). Only the non-ASCII parts of the - * domain name will be converted. Calling `punycode.toASCII()` on a string that - * already only contains ASCII characters will have no effect. - * - * ```js - * // encode domain names - * punycode.toASCII('mañana.com'); // 'xn--maana-pta.com' - * punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com' - * punycode.toASCII('example.com'); // 'example.com' - * ``` - * @since v0.6.1 - */ - function toASCII(domain: string): string; - /** - * @deprecated since v7.0.0 - * The version of the punycode module bundled in Node.js is being deprecated. - * In a future major version of Node.js this module will be removed. - * Users currently depending on the punycode module should switch to using - * the userland-provided Punycode.js module instead. - */ - const ucs2: ucs2; - interface ucs2 { - /** - * @deprecated since v7.0.0 - * The version of the punycode module bundled in Node.js is being deprecated. - * In a future major version of Node.js this module will be removed. - * Users currently depending on the punycode module should switch to using - * the userland-provided Punycode.js module instead. - */ - decode(string: string): number[]; - /** - * @deprecated since v7.0.0 - * The version of the punycode module bundled in Node.js is being deprecated. - * In a future major version of Node.js this module will be removed. - * Users currently depending on the punycode module should switch to using - * the userland-provided Punycode.js module instead. - */ - encode(codePoints: readonly number[]): string; - } - /** - * @deprecated since v7.0.0 - * The version of the punycode module bundled in Node.js is being deprecated. - * In a future major version of Node.js this module will be removed. - * Users currently depending on the punycode module should switch to using - * the userland-provided Punycode.js module instead. - */ - const version: string; -} -declare module "node:punycode" { - export * from "punycode"; -} diff --git a/node_modules/@types/node/ts4.8/querystring.d.ts b/node_modules/@types/node/ts4.8/querystring.d.ts deleted file mode 100644 index b36ea2c13014b641baf04669dc15bd40c928fbee..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/querystring.d.ts +++ /dev/null @@ -1,141 +0,0 @@ -/** - * The `node:querystring` module provides utilities for parsing and formatting URL - * query strings. It can be accessed using: - * - * ```js - * const querystring = require('node:querystring'); - * ``` - * - * `querystring` is more performant than `URLSearchParams` but is not a - * standardized API. Use `URLSearchParams` when performance is not critical or - * when compatibility with browser code is desirable. - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/querystring.js) - */ -declare module "querystring" { - interface StringifyOptions { - encodeURIComponent?: ((str: string) => string) | undefined; - } - interface ParseOptions { - maxKeys?: number | undefined; - decodeURIComponent?: ((str: string) => string) | undefined; - } - interface ParsedUrlQuery extends NodeJS.Dict {} - interface ParsedUrlQueryInput extends - NodeJS.Dict< - | string - | number - | boolean - | readonly string[] - | readonly number[] - | readonly boolean[] - | null - > - {} - /** - * The `querystring.stringify()` method produces a URL query string from a - * given `obj` by iterating through the object's "own properties". - * - * It serializes the following types of values passed in `obj`:[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | - * [number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | - * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | - * [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | - * [string\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | - * [number\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | - * [bigint\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | - * [boolean\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The numeric values must be finite. Any other input values will be coerced to - * empty strings. - * - * ```js - * querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' }); - * // Returns 'foo=bar&baz=qux&baz=quux&corge=' - * - * querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':'); - * // Returns 'foo:bar;baz:qux' - * ``` - * - * By default, characters requiring percent-encoding within the query string will - * be encoded as UTF-8\. If an alternative encoding is required, then an alternative`encodeURIComponent` option will need to be specified: - * - * ```js - * // Assuming gbkEncodeURIComponent function already exists, - * - * querystring.stringify({ w: '中文', foo: 'bar' }, null, null, - * { encodeURIComponent: gbkEncodeURIComponent }); - * ``` - * @since v0.1.25 - * @param obj The object to serialize into a URL query string - * @param [sep='&'] The substring used to delimit key and value pairs in the query string. - * @param [eq='='] . The substring used to delimit keys and values in the query string. - */ - function stringify(obj?: ParsedUrlQueryInput, sep?: string, eq?: string, options?: StringifyOptions): string; - /** - * The `querystring.parse()` method parses a URL query string (`str`) into a - * collection of key and value pairs. - * - * For example, the query string `'foo=bar&abc=xyz&abc=123'` is parsed into: - * - * ```json - * { - * "foo": "bar", - * "abc": ["xyz", "123"] - * } - * ``` - * - * The object returned by the `querystring.parse()` method _does not_prototypically inherit from the JavaScript `Object`. This means that typical`Object` methods such as `obj.toString()`, - * `obj.hasOwnProperty()`, and others - * are not defined and _will not work_. - * - * By default, percent-encoded characters within the query string will be assumed - * to use UTF-8 encoding. If an alternative character encoding is used, then an - * alternative `decodeURIComponent` option will need to be specified: - * - * ```js - * // Assuming gbkDecodeURIComponent function already exists... - * - * querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null, - * { decodeURIComponent: gbkDecodeURIComponent }); - * ``` - * @since v0.1.25 - * @param str The URL query string to parse - * @param [sep='&'] The substring used to delimit key and value pairs in the query string. - * @param [eq='='] . The substring used to delimit keys and values in the query string. - */ - function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery; - /** - * The querystring.encode() function is an alias for querystring.stringify(). - */ - const encode: typeof stringify; - /** - * The querystring.decode() function is an alias for querystring.parse(). - */ - const decode: typeof parse; - /** - * The `querystring.escape()` method performs URL percent-encoding on the given`str` in a manner that is optimized for the specific requirements of URL - * query strings. - * - * The `querystring.escape()` method is used by `querystring.stringify()` and is - * generally not expected to be used directly. It is exported primarily to allow - * application code to provide a replacement percent-encoding implementation if - * necessary by assigning `querystring.escape` to an alternative function. - * @since v0.1.25 - */ - function escape(str: string): string; - /** - * The `querystring.unescape()` method performs decoding of URL percent-encoded - * characters on the given `str`. - * - * The `querystring.unescape()` method is used by `querystring.parse()` and is - * generally not expected to be used directly. It is exported primarily to allow - * application code to provide a replacement decoding implementation if - * necessary by assigning `querystring.unescape` to an alternative function. - * - * By default, the `querystring.unescape()` method will attempt to use the - * JavaScript built-in `decodeURIComponent()` method to decode. If that fails, - * a safer equivalent that does not throw on malformed URLs will be used. - * @since v0.1.25 - */ - function unescape(str: string): string; -} -declare module "node:querystring" { - export * from "querystring"; -} diff --git a/node_modules/@types/node/ts4.8/readline.d.ts b/node_modules/@types/node/ts4.8/readline.d.ts deleted file mode 100644 index b06d58b85e62c03ff7d388177c9dce7bdde86569..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/readline.d.ts +++ /dev/null @@ -1,539 +0,0 @@ -/** - * The `node:readline` module provides an interface for reading data from a `Readable` stream (such as `process.stdin`) one line at a time. - * - * To use the promise-based APIs: - * - * ```js - * import * as readline from 'node:readline/promises'; - * ``` - * - * To use the callback and sync APIs: - * - * ```js - * import * as readline from 'node:readline'; - * ``` - * - * The following simple example illustrates the basic use of the `node:readline`module. - * - * ```js - * import * as readline from 'node:readline/promises'; - * import { stdin as input, stdout as output } from 'node:process'; - * - * const rl = readline.createInterface({ input, output }); - * - * const answer = await rl.question('What do you think of Node.js? '); - * - * console.log(`Thank you for your valuable feedback: ${answer}`); - * - * rl.close(); - * ``` - * - * Once this code is invoked, the Node.js application will not terminate until the`readline.Interface` is closed because the interface waits for data to be - * received on the `input` stream. - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/readline.js) - */ -declare module "readline" { - import { Abortable, EventEmitter } from "node:events"; - import * as promises from "node:readline/promises"; - export { promises }; - export interface Key { - sequence?: string | undefined; - name?: string | undefined; - ctrl?: boolean | undefined; - meta?: boolean | undefined; - shift?: boolean | undefined; - } - /** - * Instances of the `readline.Interface` class are constructed using the`readline.createInterface()` method. Every instance is associated with a - * single `input` `Readable` stream and a single `output` `Writable` stream. - * The `output` stream is used to print prompts for user input that arrives on, - * and is read from, the `input` stream. - * @since v0.1.104 - */ - export class Interface extends EventEmitter { - readonly terminal: boolean; - /** - * The current input data being processed by node. - * - * This can be used when collecting input from a TTY stream to retrieve the - * current value that has been processed thus far, prior to the `line` event - * being emitted. Once the `line` event has been emitted, this property will - * be an empty string. - * - * Be aware that modifying the value during the instance runtime may have - * unintended consequences if `rl.cursor` is not also controlled. - * - * **If not using a TTY stream for input, use the `'line'` event.** - * - * One possible use case would be as follows: - * - * ```js - * const values = ['lorem ipsum', 'dolor sit amet']; - * const rl = readline.createInterface(process.stdin); - * const showResults = debounce(() => { - * console.log( - * '\n', - * values.filter((val) => val.startsWith(rl.line)).join(' '), - * ); - * }, 300); - * process.stdin.on('keypress', (c, k) => { - * showResults(); - * }); - * ``` - * @since v0.1.98 - */ - readonly line: string; - /** - * The cursor position relative to `rl.line`. - * - * This will track where the current cursor lands in the input string, when - * reading input from a TTY stream. The position of cursor determines the - * portion of the input string that will be modified as input is processed, - * as well as the column where the terminal caret will be rendered. - * @since v0.1.98 - */ - readonly cursor: number; - /** - * NOTE: According to the documentation: - * - * > Instances of the `readline.Interface` class are constructed using the - * > `readline.createInterface()` method. - * - * @see https://nodejs.org/dist/latest-v20.x/docs/api/readline.html#class-interfaceconstructor - */ - protected constructor( - input: NodeJS.ReadableStream, - output?: NodeJS.WritableStream, - completer?: Completer | AsyncCompleter, - terminal?: boolean, - ); - /** - * NOTE: According to the documentation: - * - * > Instances of the `readline.Interface` class are constructed using the - * > `readline.createInterface()` method. - * - * @see https://nodejs.org/dist/latest-v20.x/docs/api/readline.html#class-interfaceconstructor - */ - protected constructor(options: ReadLineOptions); - /** - * The `rl.getPrompt()` method returns the current prompt used by `rl.prompt()`. - * @since v15.3.0, v14.17.0 - * @return the current prompt string - */ - getPrompt(): string; - /** - * The `rl.setPrompt()` method sets the prompt that will be written to `output`whenever `rl.prompt()` is called. - * @since v0.1.98 - */ - setPrompt(prompt: string): void; - /** - * The `rl.prompt()` method writes the `Interface` instances configured`prompt` to a new line in `output` in order to provide a user with a new - * location at which to provide input. - * - * When called, `rl.prompt()` will resume the `input` stream if it has been - * paused. - * - * If the `Interface` was created with `output` set to `null` or`undefined` the prompt is not written. - * @since v0.1.98 - * @param preserveCursor If `true`, prevents the cursor placement from being reset to `0`. - */ - prompt(preserveCursor?: boolean): void; - /** - * The `rl.question()` method displays the `query` by writing it to the `output`, - * waits for user input to be provided on `input`, then invokes the `callback`function passing the provided input as the first argument. - * - * When called, `rl.question()` will resume the `input` stream if it has been - * paused. - * - * If the `Interface` was created with `output` set to `null` or`undefined` the `query` is not written. - * - * The `callback` function passed to `rl.question()` does not follow the typical - * pattern of accepting an `Error` object or `null` as the first argument. - * The `callback` is called with the provided answer as the only argument. - * - * An error will be thrown if calling `rl.question()` after `rl.close()`. - * - * Example usage: - * - * ```js - * rl.question('What is your favorite food? ', (answer) => { - * console.log(`Oh, so your favorite food is ${answer}`); - * }); - * ``` - * - * Using an `AbortController` to cancel a question. - * - * ```js - * const ac = new AbortController(); - * const signal = ac.signal; - * - * rl.question('What is your favorite food? ', { signal }, (answer) => { - * console.log(`Oh, so your favorite food is ${answer}`); - * }); - * - * signal.addEventListener('abort', () => { - * console.log('The food question timed out'); - * }, { once: true }); - * - * setTimeout(() => ac.abort(), 10000); - * ``` - * @since v0.3.3 - * @param query A statement or query to write to `output`, prepended to the prompt. - * @param callback A callback function that is invoked with the user's input in response to the `query`. - */ - question(query: string, callback: (answer: string) => void): void; - question(query: string, options: Abortable, callback: (answer: string) => void): void; - /** - * The `rl.pause()` method pauses the `input` stream, allowing it to be resumed - * later if necessary. - * - * Calling `rl.pause()` does not immediately pause other events (including`'line'`) from being emitted by the `Interface` instance. - * @since v0.3.4 - */ - pause(): this; - /** - * The `rl.resume()` method resumes the `input` stream if it has been paused. - * @since v0.3.4 - */ - resume(): this; - /** - * The `rl.close()` method closes the `Interface` instance and - * relinquishes control over the `input` and `output` streams. When called, - * the `'close'` event will be emitted. - * - * Calling `rl.close()` does not immediately stop other events (including `'line'`) - * from being emitted by the `Interface` instance. - * @since v0.1.98 - */ - close(): void; - /** - * The `rl.write()` method will write either `data` or a key sequence identified - * by `key` to the `output`. The `key` argument is supported only if `output` is - * a `TTY` text terminal. See `TTY keybindings` for a list of key - * combinations. - * - * If `key` is specified, `data` is ignored. - * - * When called, `rl.write()` will resume the `input` stream if it has been - * paused. - * - * If the `Interface` was created with `output` set to `null` or`undefined` the `data` and `key` are not written. - * - * ```js - * rl.write('Delete this!'); - * // Simulate Ctrl+U to delete the line written previously - * rl.write(null, { ctrl: true, name: 'u' }); - * ``` - * - * The `rl.write()` method will write the data to the `readline` `Interface`'s`input`_as if it were provided by the user_. - * @since v0.1.98 - */ - write(data: string | Buffer, key?: Key): void; - write(data: undefined | null | string | Buffer, key: Key): void; - /** - * Returns the real position of the cursor in relation to the input - * prompt + string. Long input (wrapping) strings, as well as multiple - * line prompts are included in the calculations. - * @since v13.5.0, v12.16.0 - */ - getCursorPos(): CursorPos; - /** - * events.EventEmitter - * 1. close - * 2. line - * 3. pause - * 4. resume - * 5. SIGCONT - * 6. SIGINT - * 7. SIGTSTP - * 8. history - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "line", listener: (input: string) => void): this; - addListener(event: "pause", listener: () => void): this; - addListener(event: "resume", listener: () => void): this; - addListener(event: "SIGCONT", listener: () => void): this; - addListener(event: "SIGINT", listener: () => void): this; - addListener(event: "SIGTSTP", listener: () => void): this; - addListener(event: "history", listener: (history: string[]) => void): this; - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "line", input: string): boolean; - emit(event: "pause"): boolean; - emit(event: "resume"): boolean; - emit(event: "SIGCONT"): boolean; - emit(event: "SIGINT"): boolean; - emit(event: "SIGTSTP"): boolean; - emit(event: "history", history: string[]): boolean; - on(event: string, listener: (...args: any[]) => void): this; - on(event: "close", listener: () => void): this; - on(event: "line", listener: (input: string) => void): this; - on(event: "pause", listener: () => void): this; - on(event: "resume", listener: () => void): this; - on(event: "SIGCONT", listener: () => void): this; - on(event: "SIGINT", listener: () => void): this; - on(event: "SIGTSTP", listener: () => void): this; - on(event: "history", listener: (history: string[]) => void): this; - once(event: string, listener: (...args: any[]) => void): this; - once(event: "close", listener: () => void): this; - once(event: "line", listener: (input: string) => void): this; - once(event: "pause", listener: () => void): this; - once(event: "resume", listener: () => void): this; - once(event: "SIGCONT", listener: () => void): this; - once(event: "SIGINT", listener: () => void): this; - once(event: "SIGTSTP", listener: () => void): this; - once(event: "history", listener: (history: string[]) => void): this; - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "line", listener: (input: string) => void): this; - prependListener(event: "pause", listener: () => void): this; - prependListener(event: "resume", listener: () => void): this; - prependListener(event: "SIGCONT", listener: () => void): this; - prependListener(event: "SIGINT", listener: () => void): this; - prependListener(event: "SIGTSTP", listener: () => void): this; - prependListener(event: "history", listener: (history: string[]) => void): this; - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "line", listener: (input: string) => void): this; - prependOnceListener(event: "pause", listener: () => void): this; - prependOnceListener(event: "resume", listener: () => void): this; - prependOnceListener(event: "SIGCONT", listener: () => void): this; - prependOnceListener(event: "SIGINT", listener: () => void): this; - prependOnceListener(event: "SIGTSTP", listener: () => void): this; - prependOnceListener(event: "history", listener: (history: string[]) => void): this; - [Symbol.asyncIterator](): AsyncIterableIterator; - } - export type ReadLine = Interface; // type forwarded for backwards compatibility - export type Completer = (line: string) => CompleterResult; - export type AsyncCompleter = ( - line: string, - callback: (err?: null | Error, result?: CompleterResult) => void, - ) => void; - export type CompleterResult = [string[], string]; - export interface ReadLineOptions { - input: NodeJS.ReadableStream; - output?: NodeJS.WritableStream | undefined; - completer?: Completer | AsyncCompleter | undefined; - terminal?: boolean | undefined; - /** - * Initial list of history lines. This option makes sense - * only if `terminal` is set to `true` by the user or by an internal `output` - * check, otherwise the history caching mechanism is not initialized at all. - * @default [] - */ - history?: string[] | undefined; - historySize?: number | undefined; - prompt?: string | undefined; - crlfDelay?: number | undefined; - /** - * If `true`, when a new input line added - * to the history list duplicates an older one, this removes the older line - * from the list. - * @default false - */ - removeHistoryDuplicates?: boolean | undefined; - escapeCodeTimeout?: number | undefined; - tabSize?: number | undefined; - } - /** - * The `readline.createInterface()` method creates a new `readline.Interface`instance. - * - * ```js - * const readline = require('node:readline'); - * const rl = readline.createInterface({ - * input: process.stdin, - * output: process.stdout, - * }); - * ``` - * - * Once the `readline.Interface` instance is created, the most common case is to - * listen for the `'line'` event: - * - * ```js - * rl.on('line', (line) => { - * console.log(`Received: ${line}`); - * }); - * ``` - * - * If `terminal` is `true` for this instance then the `output` stream will get - * the best compatibility if it defines an `output.columns` property and emits - * a `'resize'` event on the `output` if or when the columns ever change - * (`process.stdout` does this automatically when it is a TTY). - * - * When creating a `readline.Interface` using `stdin` as input, the program - * will not terminate until it receives an [EOF character](https://en.wikipedia.org/wiki/End-of-file#EOF_character). To exit without - * waiting for user input, call `process.stdin.unref()`. - * @since v0.1.98 - */ - export function createInterface( - input: NodeJS.ReadableStream, - output?: NodeJS.WritableStream, - completer?: Completer | AsyncCompleter, - terminal?: boolean, - ): Interface; - export function createInterface(options: ReadLineOptions): Interface; - /** - * The `readline.emitKeypressEvents()` method causes the given `Readable` stream to begin emitting `'keypress'` events corresponding to received input. - * - * Optionally, `interface` specifies a `readline.Interface` instance for which - * autocompletion is disabled when copy-pasted input is detected. - * - * If the `stream` is a `TTY`, then it must be in raw mode. - * - * This is automatically called by any readline instance on its `input` if the`input` is a terminal. Closing the `readline` instance does not stop - * the `input` from emitting `'keypress'` events. - * - * ```js - * readline.emitKeypressEvents(process.stdin); - * if (process.stdin.isTTY) - * process.stdin.setRawMode(true); - * ``` - * - * ## Example: Tiny CLI - * - * The following example illustrates the use of `readline.Interface` class to - * implement a small command-line interface: - * - * ```js - * const readline = require('node:readline'); - * const rl = readline.createInterface({ - * input: process.stdin, - * output: process.stdout, - * prompt: 'OHAI> ', - * }); - * - * rl.prompt(); - * - * rl.on('line', (line) => { - * switch (line.trim()) { - * case 'hello': - * console.log('world!'); - * break; - * default: - * console.log(`Say what? I might have heard '${line.trim()}'`); - * break; - * } - * rl.prompt(); - * }).on('close', () => { - * console.log('Have a great day!'); - * process.exit(0); - * }); - * ``` - * - * ## Example: Read file stream line-by-Line - * - * A common use case for `readline` is to consume an input file one line at a - * time. The easiest way to do so is leveraging the `fs.ReadStream` API as - * well as a `for await...of` loop: - * - * ```js - * const fs = require('node:fs'); - * const readline = require('node:readline'); - * - * async function processLineByLine() { - * const fileStream = fs.createReadStream('input.txt'); - * - * const rl = readline.createInterface({ - * input: fileStream, - * crlfDelay: Infinity, - * }); - * // Note: we use the crlfDelay option to recognize all instances of CR LF - * // ('\r\n') in input.txt as a single line break. - * - * for await (const line of rl) { - * // Each line in input.txt will be successively available here as `line`. - * console.log(`Line from file: ${line}`); - * } - * } - * - * processLineByLine(); - * ``` - * - * Alternatively, one could use the `'line'` event: - * - * ```js - * const fs = require('node:fs'); - * const readline = require('node:readline'); - * - * const rl = readline.createInterface({ - * input: fs.createReadStream('sample.txt'), - * crlfDelay: Infinity, - * }); - * - * rl.on('line', (line) => { - * console.log(`Line from file: ${line}`); - * }); - * ``` - * - * Currently, `for await...of` loop can be a bit slower. If `async` / `await`flow and speed are both essential, a mixed approach can be applied: - * - * ```js - * const { once } = require('node:events'); - * const { createReadStream } = require('node:fs'); - * const { createInterface } = require('node:readline'); - * - * (async function processLineByLine() { - * try { - * const rl = createInterface({ - * input: createReadStream('big-file.txt'), - * crlfDelay: Infinity, - * }); - * - * rl.on('line', (line) => { - * // Process the line. - * }); - * - * await once(rl, 'close'); - * - * console.log('File processed.'); - * } catch (err) { - * console.error(err); - * } - * })(); - * ``` - * @since v0.7.7 - */ - export function emitKeypressEvents(stream: NodeJS.ReadableStream, readlineInterface?: Interface): void; - export type Direction = -1 | 0 | 1; - export interface CursorPos { - rows: number; - cols: number; - } - /** - * The `readline.clearLine()` method clears current line of given `TTY` stream - * in a specified direction identified by `dir`. - * @since v0.7.7 - * @param callback Invoked once the operation completes. - * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. - */ - export function clearLine(stream: NodeJS.WritableStream, dir: Direction, callback?: () => void): boolean; - /** - * The `readline.clearScreenDown()` method clears the given `TTY` stream from - * the current position of the cursor down. - * @since v0.7.7 - * @param callback Invoked once the operation completes. - * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. - */ - export function clearScreenDown(stream: NodeJS.WritableStream, callback?: () => void): boolean; - /** - * The `readline.cursorTo()` method moves cursor to the specified position in a - * given `TTY` `stream`. - * @since v0.7.7 - * @param callback Invoked once the operation completes. - * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. - */ - export function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number, callback?: () => void): boolean; - /** - * The `readline.moveCursor()` method moves the cursor _relative_ to its current - * position in a given `TTY` `stream`. - * @since v0.7.7 - * @param callback Invoked once the operation completes. - * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. - */ - export function moveCursor(stream: NodeJS.WritableStream, dx: number, dy: number, callback?: () => void): boolean; -} -declare module "node:readline" { - export * from "readline"; -} diff --git a/node_modules/@types/node/ts4.8/readline/promises.d.ts b/node_modules/@types/node/ts4.8/readline/promises.d.ts deleted file mode 100644 index 73fb1115d50096f9e6bcadf04943a597c5146312..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/readline/promises.d.ts +++ /dev/null @@ -1,150 +0,0 @@ -/** - * @since v17.0.0 - * @experimental - */ -declare module "readline/promises" { - import { AsyncCompleter, Completer, Direction, Interface as _Interface, ReadLineOptions } from "node:readline"; - import { Abortable } from "node:events"; - /** - * Instances of the `readlinePromises.Interface` class are constructed using the`readlinePromises.createInterface()` method. Every instance is associated with a - * single `input` `Readable` stream and a single `output` `Writable` stream. - * The `output` stream is used to print prompts for user input that arrives on, - * and is read from, the `input` stream. - * @since v17.0.0 - */ - class Interface extends _Interface { - /** - * The `rl.question()` method displays the `query` by writing it to the `output`, - * waits for user input to be provided on `input`, then invokes the `callback`function passing the provided input as the first argument. - * - * When called, `rl.question()` will resume the `input` stream if it has been - * paused. - * - * If the `Interface` was created with `output` set to `null` or`undefined` the `query` is not written. - * - * If the question is called after `rl.close()`, it returns a rejected promise. - * - * Example usage: - * - * ```js - * const answer = await rl.question('What is your favorite food? '); - * console.log(`Oh, so your favorite food is ${answer}`); - * ``` - * - * Using an `AbortSignal` to cancel a question. - * - * ```js - * const signal = AbortSignal.timeout(10_000); - * - * signal.addEventListener('abort', () => { - * console.log('The food question timed out'); - * }, { once: true }); - * - * const answer = await rl.question('What is your favorite food? ', { signal }); - * console.log(`Oh, so your favorite food is ${answer}`); - * ``` - * @since v17.0.0 - * @param query A statement or query to write to `output`, prepended to the prompt. - * @return A promise that is fulfilled with the user's input in response to the `query`. - */ - question(query: string): Promise; - question(query: string, options: Abortable): Promise; - } - /** - * @since v17.0.0 - */ - class Readline { - /** - * @param stream A TTY stream. - */ - constructor( - stream: NodeJS.WritableStream, - options?: { - autoCommit?: boolean; - }, - ); - /** - * The `rl.clearLine()` method adds to the internal list of pending action an - * action that clears current line of the associated `stream` in a specified - * direction identified by `dir`. - * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true`was passed to the constructor. - * @since v17.0.0 - * @return this - */ - clearLine(dir: Direction): this; - /** - * The `rl.clearScreenDown()` method adds to the internal list of pending action an - * action that clears the associated stream from the current position of the - * cursor down. - * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true`was passed to the constructor. - * @since v17.0.0 - * @return this - */ - clearScreenDown(): this; - /** - * The `rl.commit()` method sends all the pending actions to the associated`stream` and clears the internal list of pending actions. - * @since v17.0.0 - */ - commit(): Promise; - /** - * The `rl.cursorTo()` method adds to the internal list of pending action an action - * that moves cursor to the specified position in the associated `stream`. - * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true`was passed to the constructor. - * @since v17.0.0 - * @return this - */ - cursorTo(x: number, y?: number): this; - /** - * The `rl.moveCursor()` method adds to the internal list of pending action an - * action that moves the cursor _relative_ to its current position in the - * associated `stream`. - * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true`was passed to the constructor. - * @since v17.0.0 - * @return this - */ - moveCursor(dx: number, dy: number): this; - /** - * The `rl.rollback` methods clears the internal list of pending actions without - * sending it to the associated `stream`. - * @since v17.0.0 - * @return this - */ - rollback(): this; - } - /** - * The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface`instance. - * - * ```js - * const readlinePromises = require('node:readline/promises'); - * const rl = readlinePromises.createInterface({ - * input: process.stdin, - * output: process.stdout, - * }); - * ``` - * - * Once the `readlinePromises.Interface` instance is created, the most common case - * is to listen for the `'line'` event: - * - * ```js - * rl.on('line', (line) => { - * console.log(`Received: ${line}`); - * }); - * ``` - * - * If `terminal` is `true` for this instance then the `output` stream will get - * the best compatibility if it defines an `output.columns` property and emits - * a `'resize'` event on the `output` if or when the columns ever change - * (`process.stdout` does this automatically when it is a TTY). - * @since v17.0.0 - */ - function createInterface( - input: NodeJS.ReadableStream, - output?: NodeJS.WritableStream, - completer?: Completer | AsyncCompleter, - terminal?: boolean, - ): Interface; - function createInterface(options: ReadLineOptions): Interface; -} -declare module "node:readline/promises" { - export * from "readline/promises"; -} diff --git a/node_modules/@types/node/ts4.8/repl.d.ts b/node_modules/@types/node/ts4.8/repl.d.ts deleted file mode 100644 index 6c5f81b399df50506180bd8d271840029659572b..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/repl.d.ts +++ /dev/null @@ -1,430 +0,0 @@ -/** - * The `node:repl` module provides a Read-Eval-Print-Loop (REPL) implementation - * that is available both as a standalone program or includible in other - * applications. It can be accessed using: - * - * ```js - * const repl = require('node:repl'); - * ``` - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/repl.js) - */ -declare module "repl" { - import { AsyncCompleter, Completer, Interface } from "node:readline"; - import { Context } from "node:vm"; - import { InspectOptions } from "node:util"; - interface ReplOptions { - /** - * The input prompt to display. - * @default "> " - */ - prompt?: string | undefined; - /** - * The `Readable` stream from which REPL input will be read. - * @default process.stdin - */ - input?: NodeJS.ReadableStream | undefined; - /** - * The `Writable` stream to which REPL output will be written. - * @default process.stdout - */ - output?: NodeJS.WritableStream | undefined; - /** - * If `true`, specifies that the output should be treated as a TTY terminal, and have - * ANSI/VT100 escape codes written to it. - * Default: checking the value of the `isTTY` property on the output stream upon - * instantiation. - */ - terminal?: boolean | undefined; - /** - * The function to be used when evaluating each given line of input. - * Default: an async wrapper for the JavaScript `eval()` function. An `eval` function can - * error with `repl.Recoverable` to indicate the input was incomplete and prompt for - * additional lines. - * - * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_default_evaluation - * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_custom_evaluation_functions - */ - eval?: REPLEval | undefined; - /** - * Defines if the repl prints output previews or not. - * @default `true` Always `false` in case `terminal` is falsy. - */ - preview?: boolean | undefined; - /** - * If `true`, specifies that the default `writer` function should include ANSI color - * styling to REPL output. If a custom `writer` function is provided then this has no - * effect. - * Default: the REPL instance's `terminal` value. - */ - useColors?: boolean | undefined; - /** - * If `true`, specifies that the default evaluation function will use the JavaScript - * `global` as the context as opposed to creating a new separate context for the REPL - * instance. The node CLI REPL sets this value to `true`. - * Default: `false`. - */ - useGlobal?: boolean | undefined; - /** - * If `true`, specifies that the default writer will not output the return value of a - * command if it evaluates to `undefined`. - * Default: `false`. - */ - ignoreUndefined?: boolean | undefined; - /** - * The function to invoke to format the output of each command before writing to `output`. - * Default: a wrapper for `util.inspect`. - * - * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_customizing_repl_output - */ - writer?: REPLWriter | undefined; - /** - * An optional function used for custom Tab auto completion. - * - * @see https://nodejs.org/dist/latest-v20.x/docs/api/readline.html#readline_use_of_the_completer_function - */ - completer?: Completer | AsyncCompleter | undefined; - /** - * A flag that specifies whether the default evaluator executes all JavaScript commands in - * strict mode or default (sloppy) mode. - * Accepted values are: - * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. - * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to - * prefacing every repl statement with `'use strict'`. - */ - replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT | undefined; - /** - * Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is - * pressed. This cannot be used together with a custom `eval` function. - * Default: `false`. - */ - breakEvalOnSigint?: boolean | undefined; - } - type REPLEval = ( - this: REPLServer, - evalCmd: string, - context: Context, - file: string, - cb: (err: Error | null, result: any) => void, - ) => void; - type REPLWriter = (this: REPLServer, obj: any) => string; - /** - * This is the default "writer" value, if none is passed in the REPL options, - * and it can be overridden by custom print functions. - */ - const writer: REPLWriter & { - options: InspectOptions; - }; - type REPLCommandAction = (this: REPLServer, text: string) => void; - interface REPLCommand { - /** - * Help text to be displayed when `.help` is entered. - */ - help?: string | undefined; - /** - * The function to execute, optionally accepting a single string argument. - */ - action: REPLCommandAction; - } - /** - * Instances of `repl.REPLServer` are created using the {@link start} method - * or directly using the JavaScript `new` keyword. - * - * ```js - * const repl = require('node:repl'); - * - * const options = { useColors: true }; - * - * const firstInstance = repl.start(options); - * const secondInstance = new repl.REPLServer(options); - * ``` - * @since v0.1.91 - */ - class REPLServer extends Interface { - /** - * The `vm.Context` provided to the `eval` function to be used for JavaScript - * evaluation. - */ - readonly context: Context; - /** - * @deprecated since v14.3.0 - Use `input` instead. - */ - readonly inputStream: NodeJS.ReadableStream; - /** - * @deprecated since v14.3.0 - Use `output` instead. - */ - readonly outputStream: NodeJS.WritableStream; - /** - * The `Readable` stream from which REPL input will be read. - */ - readonly input: NodeJS.ReadableStream; - /** - * The `Writable` stream to which REPL output will be written. - */ - readonly output: NodeJS.WritableStream; - /** - * The commands registered via `replServer.defineCommand()`. - */ - readonly commands: NodeJS.ReadOnlyDict; - /** - * A value indicating whether the REPL is currently in "editor mode". - * - * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_commands_and_special_keys - */ - readonly editorMode: boolean; - /** - * A value indicating whether the `_` variable has been assigned. - * - * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable - */ - readonly underscoreAssigned: boolean; - /** - * The last evaluation result from the REPL (assigned to the `_` variable inside of the REPL). - * - * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable - */ - readonly last: any; - /** - * A value indicating whether the `_error` variable has been assigned. - * - * @since v9.8.0 - * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable - */ - readonly underscoreErrAssigned: boolean; - /** - * The last error raised inside the REPL (assigned to the `_error` variable inside of the REPL). - * - * @since v9.8.0 - * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable - */ - readonly lastError: any; - /** - * Specified in the REPL options, this is the function to be used when evaluating each - * given line of input. If not specified in the REPL options, this is an async wrapper - * for the JavaScript `eval()` function. - */ - readonly eval: REPLEval; - /** - * Specified in the REPL options, this is a value indicating whether the default - * `writer` function should include ANSI color styling to REPL output. - */ - readonly useColors: boolean; - /** - * Specified in the REPL options, this is a value indicating whether the default `eval` - * function will use the JavaScript `global` as the context as opposed to creating a new - * separate context for the REPL instance. - */ - readonly useGlobal: boolean; - /** - * Specified in the REPL options, this is a value indicating whether the default `writer` - * function should output the result of a command if it evaluates to `undefined`. - */ - readonly ignoreUndefined: boolean; - /** - * Specified in the REPL options, this is the function to invoke to format the output of - * each command before writing to `outputStream`. If not specified in the REPL options, - * this will be a wrapper for `util.inspect`. - */ - readonly writer: REPLWriter; - /** - * Specified in the REPL options, this is the function to use for custom Tab auto-completion. - */ - readonly completer: Completer | AsyncCompleter; - /** - * Specified in the REPL options, this is a flag that specifies whether the default `eval` - * function should execute all JavaScript commands in strict mode or default (sloppy) mode. - * Possible values are: - * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. - * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to - * prefacing every repl statement with `'use strict'`. - */ - readonly replMode: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; - /** - * NOTE: According to the documentation: - * - * > Instances of `repl.REPLServer` are created using the `repl.start()` method and - * > _should not_ be created directly using the JavaScript `new` keyword. - * - * `REPLServer` cannot be subclassed due to implementation specifics in NodeJS. - * - * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_class_replserver - */ - private constructor(); - /** - * The `replServer.defineCommand()` method is used to add new `.`\-prefixed commands - * to the REPL instance. Such commands are invoked by typing a `.` followed by the`keyword`. The `cmd` is either a `Function` or an `Object` with the following - * properties: - * - * The following example shows two new commands added to the REPL instance: - * - * ```js - * const repl = require('node:repl'); - * - * const replServer = repl.start({ prompt: '> ' }); - * replServer.defineCommand('sayhello', { - * help: 'Say hello', - * action(name) { - * this.clearBufferedCommand(); - * console.log(`Hello, ${name}!`); - * this.displayPrompt(); - * }, - * }); - * replServer.defineCommand('saybye', function saybye() { - * console.log('Goodbye!'); - * this.close(); - * }); - * ``` - * - * The new commands can then be used from within the REPL instance: - * - * ```console - * > .sayhello Node.js User - * Hello, Node.js User! - * > .saybye - * Goodbye! - * ``` - * @since v0.3.0 - * @param keyword The command keyword (_without_ a leading `.` character). - * @param cmd The function to invoke when the command is processed. - */ - defineCommand(keyword: string, cmd: REPLCommandAction | REPLCommand): void; - /** - * The `replServer.displayPrompt()` method readies the REPL instance for input - * from the user, printing the configured `prompt` to a new line in the `output`and resuming the `input` to accept new input. - * - * When multi-line input is being entered, an ellipsis is printed rather than the - * 'prompt'. - * - * When `preserveCursor` is `true`, the cursor placement will not be reset to `0`. - * - * The `replServer.displayPrompt` method is primarily intended to be called from - * within the action function for commands registered using the`replServer.defineCommand()` method. - * @since v0.1.91 - */ - displayPrompt(preserveCursor?: boolean): void; - /** - * The `replServer.clearBufferedCommand()` method clears any command that has been - * buffered but not yet executed. This method is primarily intended to be - * called from within the action function for commands registered using the`replServer.defineCommand()` method. - * @since v9.0.0 - */ - clearBufferedCommand(): void; - /** - * Initializes a history log file for the REPL instance. When executing the - * Node.js binary and using the command-line REPL, a history file is initialized - * by default. However, this is not the case when creating a REPL - * programmatically. Use this method to initialize a history log file when working - * with REPL instances programmatically. - * @since v11.10.0 - * @param historyPath the path to the history file - * @param callback called when history writes are ready or upon error - */ - setupHistory(path: string, callback: (err: Error | null, repl: this) => void): void; - /** - * events.EventEmitter - * 1. close - inherited from `readline.Interface` - * 2. line - inherited from `readline.Interface` - * 3. pause - inherited from `readline.Interface` - * 4. resume - inherited from `readline.Interface` - * 5. SIGCONT - inherited from `readline.Interface` - * 6. SIGINT - inherited from `readline.Interface` - * 7. SIGTSTP - inherited from `readline.Interface` - * 8. exit - * 9. reset - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "line", listener: (input: string) => void): this; - addListener(event: "pause", listener: () => void): this; - addListener(event: "resume", listener: () => void): this; - addListener(event: "SIGCONT", listener: () => void): this; - addListener(event: "SIGINT", listener: () => void): this; - addListener(event: "SIGTSTP", listener: () => void): this; - addListener(event: "exit", listener: () => void): this; - addListener(event: "reset", listener: (context: Context) => void): this; - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "line", input: string): boolean; - emit(event: "pause"): boolean; - emit(event: "resume"): boolean; - emit(event: "SIGCONT"): boolean; - emit(event: "SIGINT"): boolean; - emit(event: "SIGTSTP"): boolean; - emit(event: "exit"): boolean; - emit(event: "reset", context: Context): boolean; - on(event: string, listener: (...args: any[]) => void): this; - on(event: "close", listener: () => void): this; - on(event: "line", listener: (input: string) => void): this; - on(event: "pause", listener: () => void): this; - on(event: "resume", listener: () => void): this; - on(event: "SIGCONT", listener: () => void): this; - on(event: "SIGINT", listener: () => void): this; - on(event: "SIGTSTP", listener: () => void): this; - on(event: "exit", listener: () => void): this; - on(event: "reset", listener: (context: Context) => void): this; - once(event: string, listener: (...args: any[]) => void): this; - once(event: "close", listener: () => void): this; - once(event: "line", listener: (input: string) => void): this; - once(event: "pause", listener: () => void): this; - once(event: "resume", listener: () => void): this; - once(event: "SIGCONT", listener: () => void): this; - once(event: "SIGINT", listener: () => void): this; - once(event: "SIGTSTP", listener: () => void): this; - once(event: "exit", listener: () => void): this; - once(event: "reset", listener: (context: Context) => void): this; - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "line", listener: (input: string) => void): this; - prependListener(event: "pause", listener: () => void): this; - prependListener(event: "resume", listener: () => void): this; - prependListener(event: "SIGCONT", listener: () => void): this; - prependListener(event: "SIGINT", listener: () => void): this; - prependListener(event: "SIGTSTP", listener: () => void): this; - prependListener(event: "exit", listener: () => void): this; - prependListener(event: "reset", listener: (context: Context) => void): this; - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "line", listener: (input: string) => void): this; - prependOnceListener(event: "pause", listener: () => void): this; - prependOnceListener(event: "resume", listener: () => void): this; - prependOnceListener(event: "SIGCONT", listener: () => void): this; - prependOnceListener(event: "SIGINT", listener: () => void): this; - prependOnceListener(event: "SIGTSTP", listener: () => void): this; - prependOnceListener(event: "exit", listener: () => void): this; - prependOnceListener(event: "reset", listener: (context: Context) => void): this; - } - /** - * A flag passed in the REPL options. Evaluates expressions in sloppy mode. - */ - const REPL_MODE_SLOPPY: unique symbol; - /** - * A flag passed in the REPL options. Evaluates expressions in strict mode. - * This is equivalent to prefacing every repl statement with `'use strict'`. - */ - const REPL_MODE_STRICT: unique symbol; - /** - * The `repl.start()` method creates and starts a {@link REPLServer} instance. - * - * If `options` is a string, then it specifies the input prompt: - * - * ```js - * const repl = require('node:repl'); - * - * // a Unix style prompt - * repl.start('$ '); - * ``` - * @since v0.1.91 - */ - function start(options?: string | ReplOptions): REPLServer; - /** - * Indicates a recoverable error that a `REPLServer` can use to support multi-line input. - * - * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_recoverable_errors - */ - class Recoverable extends SyntaxError { - err: Error; - constructor(err: Error); - } -} -declare module "node:repl" { - export * from "repl"; -} diff --git a/node_modules/@types/node/ts4.8/stream.d.ts b/node_modules/@types/node/ts4.8/stream.d.ts deleted file mode 100644 index 947a0193f489237de1902e06faaefad02fa085dd..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/stream.d.ts +++ /dev/null @@ -1,1701 +0,0 @@ -/** - * A stream is an abstract interface for working with streaming data in Node.js. - * The `node:stream` module provides an API for implementing the stream interface. - * - * There are many stream objects provided by Node.js. For instance, a `request to an HTTP server` and `process.stdout` are both stream instances. - * - * Streams can be readable, writable, or both. All streams are instances of `EventEmitter`. - * - * To access the `node:stream` module: - * - * ```js - * const stream = require('node:stream'); - * ``` - * - * The `node:stream` module is useful for creating new types of stream instances. - * It is usually not necessary to use the `node:stream` module to consume streams. - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/stream.js) - */ -declare module "stream" { - import { Abortable, EventEmitter } from "node:events"; - import { Blob as NodeBlob } from "node:buffer"; - import * as streamPromises from "node:stream/promises"; - import * as streamConsumers from "node:stream/consumers"; - import * as streamWeb from "node:stream/web"; - - type ComposeFnParam = (source: any) => void; - - class internal extends EventEmitter { - pipe( - destination: T, - options?: { - end?: boolean | undefined; - }, - ): T; - compose( - stream: T | ComposeFnParam | Iterable | AsyncIterable, - options?: { signal: AbortSignal }, - ): T; - } - import Stream = internal.Stream; - import Readable = internal.Readable; - import ReadableOptions = internal.ReadableOptions; - interface ArrayOptions { - /** the maximum concurrent invocations of `fn` to call on the stream at once. **Default: 1**. */ - concurrency?: number; - /** allows destroying the stream if the signal is aborted. */ - signal?: AbortSignal; - } - class ReadableBase extends Stream implements NodeJS.ReadableStream { - /** - * A utility method for creating Readable Streams out of iterators. - */ - static from(iterable: Iterable | AsyncIterable, options?: ReadableOptions): Readable; - /** - * Returns whether the stream has been read from or cancelled. - * @since v16.8.0 - */ - static isDisturbed(stream: Readable | NodeJS.ReadableStream): boolean; - /** - * Returns whether the stream was destroyed or errored before emitting `'end'`. - * @since v16.8.0 - * @experimental - */ - readonly readableAborted: boolean; - /** - * Is `true` if it is safe to call `readable.read()`, which means - * the stream has not been destroyed or emitted `'error'` or `'end'`. - * @since v11.4.0 - */ - readable: boolean; - /** - * Returns whether `'data'` has been emitted. - * @since v16.7.0, v14.18.0 - * @experimental - */ - readonly readableDidRead: boolean; - /** - * Getter for the property `encoding` of a given `Readable` stream. The `encoding`property can be set using the `readable.setEncoding()` method. - * @since v12.7.0 - */ - readonly readableEncoding: BufferEncoding | null; - /** - * Becomes `true` when `'end'` event is emitted. - * @since v12.9.0 - */ - readonly readableEnded: boolean; - /** - * This property reflects the current state of a `Readable` stream as described - * in the `Three states` section. - * @since v9.4.0 - */ - readonly readableFlowing: boolean | null; - /** - * Returns the value of `highWaterMark` passed when creating this `Readable`. - * @since v9.3.0 - */ - readonly readableHighWaterMark: number; - /** - * This property contains the number of bytes (or objects) in the queue - * ready to be read. The value provides introspection data regarding - * the status of the `highWaterMark`. - * @since v9.4.0 - */ - readonly readableLength: number; - /** - * Getter for the property `objectMode` of a given `Readable` stream. - * @since v12.3.0 - */ - readonly readableObjectMode: boolean; - /** - * Is `true` after `readable.destroy()` has been called. - * @since v8.0.0 - */ - destroyed: boolean; - /** - * Is `true` after `'close'` has been emitted. - * @since v18.0.0 - */ - readonly closed: boolean; - /** - * Returns error if the stream has been destroyed with an error. - * @since v18.0.0 - */ - readonly errored: Error | null; - constructor(opts?: ReadableOptions); - _construct?(callback: (error?: Error | null) => void): void; - _read(size: number): void; - /** - * The `readable.read()` method reads data out of the internal buffer and - * returns it. If no data is available to be read, `null` is returned. By default, - * the data is returned as a `Buffer` object unless an encoding has been - * specified using the `readable.setEncoding()` method or the stream is operating - * in object mode. - * - * The optional `size` argument specifies a specific number of bytes to read. If`size` bytes are not available to be read, `null` will be returned _unless_the stream has ended, in which - * case all of the data remaining in the internal - * buffer will be returned. - * - * If the `size` argument is not specified, all of the data contained in the - * internal buffer will be returned. - * - * The `size` argument must be less than or equal to 1 GiB. - * - * The `readable.read()` method should only be called on `Readable` streams - * operating in paused mode. In flowing mode, `readable.read()` is called - * automatically until the internal buffer is fully drained. - * - * ```js - * const readable = getReadableStreamSomehow(); - * - * // 'readable' may be triggered multiple times as data is buffered in - * readable.on('readable', () => { - * let chunk; - * console.log('Stream is readable (new data received in buffer)'); - * // Use a loop to make sure we read all currently available data - * while (null !== (chunk = readable.read())) { - * console.log(`Read ${chunk.length} bytes of data...`); - * } - * }); - * - * // 'end' will be triggered once when there is no more data available - * readable.on('end', () => { - * console.log('Reached end of stream.'); - * }); - * ``` - * - * Each call to `readable.read()` returns a chunk of data, or `null`. The chunks - * are not concatenated. A `while` loop is necessary to consume all data - * currently in the buffer. When reading a large file `.read()` may return `null`, - * having consumed all buffered content so far, but there is still more data to - * come not yet buffered. In this case a new `'readable'` event will be emitted - * when there is more data in the buffer. Finally the `'end'` event will be - * emitted when there is no more data to come. - * - * Therefore to read a file's whole contents from a `readable`, it is necessary - * to collect chunks across multiple `'readable'` events: - * - * ```js - * const chunks = []; - * - * readable.on('readable', () => { - * let chunk; - * while (null !== (chunk = readable.read())) { - * chunks.push(chunk); - * } - * }); - * - * readable.on('end', () => { - * const content = chunks.join(''); - * }); - * ``` - * - * A `Readable` stream in object mode will always return a single item from - * a call to `readable.read(size)`, regardless of the value of the`size` argument. - * - * If the `readable.read()` method returns a chunk of data, a `'data'` event will - * also be emitted. - * - * Calling {@link read} after the `'end'` event has - * been emitted will return `null`. No runtime error will be raised. - * @since v0.9.4 - * @param size Optional argument to specify how much data to read. - */ - read(size?: number): any; - /** - * The `readable.setEncoding()` method sets the character encoding for - * data read from the `Readable` stream. - * - * By default, no encoding is assigned and stream data will be returned as`Buffer` objects. Setting an encoding causes the stream data - * to be returned as strings of the specified encoding rather than as `Buffer`objects. For instance, calling `readable.setEncoding('utf8')` will cause the - * output data to be interpreted as UTF-8 data, and passed as strings. Calling`readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal - * string format. - * - * The `Readable` stream will properly handle multi-byte characters delivered - * through the stream that would otherwise become improperly decoded if simply - * pulled from the stream as `Buffer` objects. - * - * ```js - * const readable = getReadableStreamSomehow(); - * readable.setEncoding('utf8'); - * readable.on('data', (chunk) => { - * assert.equal(typeof chunk, 'string'); - * console.log('Got %d characters of string data:', chunk.length); - * }); - * ``` - * @since v0.9.4 - * @param encoding The encoding to use. - */ - setEncoding(encoding: BufferEncoding): this; - /** - * The `readable.pause()` method will cause a stream in flowing mode to stop - * emitting `'data'` events, switching out of flowing mode. Any data that - * becomes available will remain in the internal buffer. - * - * ```js - * const readable = getReadableStreamSomehow(); - * readable.on('data', (chunk) => { - * console.log(`Received ${chunk.length} bytes of data.`); - * readable.pause(); - * console.log('There will be no additional data for 1 second.'); - * setTimeout(() => { - * console.log('Now data will start flowing again.'); - * readable.resume(); - * }, 1000); - * }); - * ``` - * - * The `readable.pause()` method has no effect if there is a `'readable'`event listener. - * @since v0.9.4 - */ - pause(): this; - /** - * The `readable.resume()` method causes an explicitly paused `Readable` stream to - * resume emitting `'data'` events, switching the stream into flowing mode. - * - * The `readable.resume()` method can be used to fully consume the data from a - * stream without actually processing any of that data: - * - * ```js - * getReadableStreamSomehow() - * .resume() - * .on('end', () => { - * console.log('Reached the end, but did not read anything.'); - * }); - * ``` - * - * The `readable.resume()` method has no effect if there is a `'readable'`event listener. - * @since v0.9.4 - */ - resume(): this; - /** - * The `readable.isPaused()` method returns the current operating state of the`Readable`. This is used primarily by the mechanism that underlies the`readable.pipe()` method. In most - * typical cases, there will be no reason to - * use this method directly. - * - * ```js - * const readable = new stream.Readable(); - * - * readable.isPaused(); // === false - * readable.pause(); - * readable.isPaused(); // === true - * readable.resume(); - * readable.isPaused(); // === false - * ``` - * @since v0.11.14 - */ - isPaused(): boolean; - /** - * The `readable.unpipe()` method detaches a `Writable` stream previously attached - * using the {@link pipe} method. - * - * If the `destination` is not specified, then _all_ pipes are detached. - * - * If the `destination` is specified, but no pipe is set up for it, then - * the method does nothing. - * - * ```js - * const fs = require('node:fs'); - * const readable = getReadableStreamSomehow(); - * const writable = fs.createWriteStream('file.txt'); - * // All the data from readable goes into 'file.txt', - * // but only for the first second. - * readable.pipe(writable); - * setTimeout(() => { - * console.log('Stop writing to file.txt.'); - * readable.unpipe(writable); - * console.log('Manually close the file stream.'); - * writable.end(); - * }, 1000); - * ``` - * @since v0.9.4 - * @param destination Optional specific stream to unpipe - */ - unpipe(destination?: NodeJS.WritableStream): this; - /** - * Passing `chunk` as `null` signals the end of the stream (EOF) and behaves the - * same as `readable.push(null)`, after which no more data can be written. The EOF - * signal is put at the end of the buffer and any buffered data will still be - * flushed. - * - * The `readable.unshift()` method pushes a chunk of data back into the internal - * buffer. This is useful in certain situations where a stream is being consumed by - * code that needs to "un-consume" some amount of data that it has optimistically - * pulled out of the source, so that the data can be passed on to some other party. - * - * The `stream.unshift(chunk)` method cannot be called after the `'end'` event - * has been emitted or a runtime error will be thrown. - * - * Developers using `stream.unshift()` often should consider switching to - * use of a `Transform` stream instead. See the `API for stream implementers` section for more information. - * - * ```js - * // Pull off a header delimited by \n\n. - * // Use unshift() if we get too much. - * // Call the callback with (error, header, stream). - * const { StringDecoder } = require('node:string_decoder'); - * function parseHeader(stream, callback) { - * stream.on('error', callback); - * stream.on('readable', onReadable); - * const decoder = new StringDecoder('utf8'); - * let header = ''; - * function onReadable() { - * let chunk; - * while (null !== (chunk = stream.read())) { - * const str = decoder.write(chunk); - * if (str.includes('\n\n')) { - * // Found the header boundary. - * const split = str.split(/\n\n/); - * header += split.shift(); - * const remaining = split.join('\n\n'); - * const buf = Buffer.from(remaining, 'utf8'); - * stream.removeListener('error', callback); - * // Remove the 'readable' listener before unshifting. - * stream.removeListener('readable', onReadable); - * if (buf.length) - * stream.unshift(buf); - * // Now the body of the message can be read from the stream. - * callback(null, header, stream); - * return; - * } - * // Still reading the header. - * header += str; - * } - * } - * } - * ``` - * - * Unlike {@link push}, `stream.unshift(chunk)` will not - * end the reading process by resetting the internal reading state of the stream. - * This can cause unexpected results if `readable.unshift()` is called during a - * read (i.e. from within a {@link _read} implementation on a - * custom stream). Following the call to `readable.unshift()` with an immediate {@link push} will reset the reading state appropriately, - * however it is best to simply avoid calling `readable.unshift()` while in the - * process of performing a read. - * @since v0.9.11 - * @param chunk Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer`, `Uint8Array`, or `null`. For object mode - * streams, `chunk` may be any JavaScript value. - * @param encoding Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`. - */ - unshift(chunk: any, encoding?: BufferEncoding): void; - /** - * Prior to Node.js 0.10, streams did not implement the entire `node:stream`module API as it is currently defined. (See `Compatibility` for more - * information.) - * - * When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the`readable.wrap()` method can be used to create a `Readable` - * stream that uses - * the old stream as its data source. - * - * It will rarely be necessary to use `readable.wrap()` but the method has been - * provided as a convenience for interacting with older Node.js applications and - * libraries. - * - * ```js - * const { OldReader } = require('./old-api-module.js'); - * const { Readable } = require('node:stream'); - * const oreader = new OldReader(); - * const myReader = new Readable().wrap(oreader); - * - * myReader.on('readable', () => { - * myReader.read(); // etc. - * }); - * ``` - * @since v0.9.4 - * @param stream An "old style" readable stream - */ - wrap(stream: NodeJS.ReadableStream): this; - push(chunk: any, encoding?: BufferEncoding): boolean; - /** - * The iterator created by this method gives users the option to cancel the destruction - * of the stream if the `for await...of` loop is exited by `return`, `break`, or `throw`, - * or if the iterator should destroy the stream if the stream emitted an error during iteration. - * @since v16.3.0 - * @param options.destroyOnReturn When set to `false`, calling `return` on the async iterator, - * or exiting a `for await...of` iteration using a `break`, `return`, or `throw` will not destroy the stream. - * **Default: `true`**. - */ - iterator(options?: { destroyOnReturn?: boolean }): AsyncIterableIterator; - /** - * This method allows mapping over the stream. The *fn* function will be called for every chunk in the stream. - * If the *fn* function returns a promise - that promise will be `await`ed before being passed to the result stream. - * @since v17.4.0, v16.14.0 - * @param fn a function to map over every chunk in the stream. Async or not. - * @returns a stream mapped with the function *fn*. - */ - map(fn: (data: any, options?: Pick) => any, options?: ArrayOptions): Readable; - /** - * This method allows filtering the stream. For each chunk in the stream the *fn* function will be called - * and if it returns a truthy value, the chunk will be passed to the result stream. - * If the *fn* function returns a promise - that promise will be `await`ed. - * @since v17.4.0, v16.14.0 - * @param fn a function to filter chunks from the stream. Async or not. - * @returns a stream filtered with the predicate *fn*. - */ - filter( - fn: (data: any, options?: Pick) => boolean | Promise, - options?: ArrayOptions, - ): Readable; - /** - * This method allows iterating a stream. For each chunk in the stream the *fn* function will be called. - * If the *fn* function returns a promise - that promise will be `await`ed. - * - * This method is different from `for await...of` loops in that it can optionally process chunks concurrently. - * In addition, a `forEach` iteration can only be stopped by having passed a `signal` option - * and aborting the related AbortController while `for await...of` can be stopped with `break` or `return`. - * In either case the stream will be destroyed. - * - * This method is different from listening to the `'data'` event in that it uses the `readable` event - * in the underlying machinary and can limit the number of concurrent *fn* calls. - * @since v17.5.0 - * @param fn a function to call on each chunk of the stream. Async or not. - * @returns a promise for when the stream has finished. - */ - forEach( - fn: (data: any, options?: Pick) => void | Promise, - options?: ArrayOptions, - ): Promise; - /** - * This method allows easily obtaining the contents of a stream. - * - * As this method reads the entire stream into memory, it negates the benefits of streams. It's intended - * for interoperability and convenience, not as the primary way to consume streams. - * @since v17.5.0 - * @returns a promise containing an array with the contents of the stream. - */ - toArray(options?: Pick): Promise; - /** - * This method is similar to `Array.prototype.some` and calls *fn* on each chunk in the stream - * until the awaited return value is `true` (or any truthy value). Once an *fn* call on a chunk - * `await`ed return value is truthy, the stream is destroyed and the promise is fulfilled with `true`. - * If none of the *fn* calls on the chunks return a truthy value, the promise is fulfilled with `false`. - * @since v17.5.0 - * @param fn a function to call on each chunk of the stream. Async or not. - * @returns a promise evaluating to `true` if *fn* returned a truthy value for at least one of the chunks. - */ - some( - fn: (data: any, options?: Pick) => boolean | Promise, - options?: ArrayOptions, - ): Promise; - /** - * This method is similar to `Array.prototype.find` and calls *fn* on each chunk in the stream - * to find a chunk with a truthy value for *fn*. Once an *fn* call's awaited return value is truthy, - * the stream is destroyed and the promise is fulfilled with value for which *fn* returned a truthy value. - * If all of the *fn* calls on the chunks return a falsy value, the promise is fulfilled with `undefined`. - * @since v17.5.0 - * @param fn a function to call on each chunk of the stream. Async or not. - * @returns a promise evaluating to the first chunk for which *fn* evaluated with a truthy value, - * or `undefined` if no element was found. - */ - find( - fn: (data: any, options?: Pick) => data is T, - options?: ArrayOptions, - ): Promise; - find( - fn: (data: any, options?: Pick) => boolean | Promise, - options?: ArrayOptions, - ): Promise; - /** - * This method is similar to `Array.prototype.every` and calls *fn* on each chunk in the stream - * to check if all awaited return values are truthy value for *fn*. Once an *fn* call on a chunk - * `await`ed return value is falsy, the stream is destroyed and the promise is fulfilled with `false`. - * If all of the *fn* calls on the chunks return a truthy value, the promise is fulfilled with `true`. - * @since v17.5.0 - * @param fn a function to call on each chunk of the stream. Async or not. - * @returns a promise evaluating to `true` if *fn* returned a truthy value for every one of the chunks. - */ - every( - fn: (data: any, options?: Pick) => boolean | Promise, - options?: ArrayOptions, - ): Promise; - /** - * This method returns a new stream by applying the given callback to each chunk of the stream - * and then flattening the result. - * - * It is possible to return a stream or another iterable or async iterable from *fn* and the result streams - * will be merged (flattened) into the returned stream. - * @since v17.5.0 - * @param fn a function to map over every chunk in the stream. May be async. May be a stream or generator. - * @returns a stream flat-mapped with the function *fn*. - */ - flatMap(fn: (data: any, options?: Pick) => any, options?: ArrayOptions): Readable; - /** - * This method returns a new stream with the first *limit* chunks dropped from the start. - * @since v17.5.0 - * @param limit the number of chunks to drop from the readable. - * @returns a stream with *limit* chunks dropped from the start. - */ - drop(limit: number, options?: Pick): Readable; - /** - * This method returns a new stream with the first *limit* chunks. - * @since v17.5.0 - * @param limit the number of chunks to take from the readable. - * @returns a stream with *limit* chunks taken. - */ - take(limit: number, options?: Pick): Readable; - /** - * This method returns a new stream with chunks of the underlying stream paired with a counter - * in the form `[index, chunk]`. The first index value is `0` and it increases by 1 for each chunk produced. - * @since v17.5.0 - * @returns a stream of indexed pairs. - */ - asIndexedPairs(options?: Pick): Readable; - /** - * This method calls *fn* on each chunk of the stream in order, passing it the result from the calculation - * on the previous element. It returns a promise for the final value of the reduction. - * - * If no *initial* value is supplied the first chunk of the stream is used as the initial value. - * If the stream is empty, the promise is rejected with a `TypeError` with the `ERR_INVALID_ARGS` code property. - * - * The reducer function iterates the stream element-by-element which means that there is no *concurrency* parameter - * or parallelism. To perform a reduce concurrently, you can extract the async function to `readable.map` method. - * @since v17.5.0 - * @param fn a reducer function to call over every chunk in the stream. Async or not. - * @param initial the initial value to use in the reduction. - * @returns a promise for the final value of the reduction. - */ - reduce( - fn: (previous: any, data: any, options?: Pick) => T, - initial?: undefined, - options?: Pick, - ): Promise; - reduce( - fn: (previous: T, data: any, options?: Pick) => T, - initial: T, - options?: Pick, - ): Promise; - _destroy(error: Error | null, callback: (error?: Error | null) => void): void; - /** - * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'`event (unless `emitClose` is set to `false`). After this call, the readable - * stream will release any internal resources and subsequent calls to `push()`will be ignored. - * - * Once `destroy()` has been called any further calls will be a no-op and no - * further errors except from `_destroy()` may be emitted as `'error'`. - * - * Implementors should not override this method, but instead implement `readable._destroy()`. - * @since v8.0.0 - * @param error Error which will be passed as payload in `'error'` event - */ - destroy(error?: Error): this; - /** - * Event emitter - * The defined events on documents including: - * 1. close - * 2. data - * 3. end - * 4. error - * 5. pause - * 6. readable - * 7. resume - */ - addListener(event: "close", listener: () => void): this; - addListener(event: "data", listener: (chunk: any) => void): this; - addListener(event: "end", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "pause", listener: () => void): this; - addListener(event: "readable", listener: () => void): this; - addListener(event: "resume", listener: () => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - emit(event: "close"): boolean; - emit(event: "data", chunk: any): boolean; - emit(event: "end"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "pause"): boolean; - emit(event: "readable"): boolean; - emit(event: "resume"): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - on(event: "close", listener: () => void): this; - on(event: "data", listener: (chunk: any) => void): this; - on(event: "end", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "pause", listener: () => void): this; - on(event: "readable", listener: () => void): this; - on(event: "resume", listener: () => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: "close", listener: () => void): this; - once(event: "data", listener: (chunk: any) => void): this; - once(event: "end", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "pause", listener: () => void): this; - once(event: "readable", listener: () => void): this; - once(event: "resume", listener: () => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "data", listener: (chunk: any) => void): this; - prependListener(event: "end", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "pause", listener: () => void): this; - prependListener(event: "readable", listener: () => void): this; - prependListener(event: "resume", listener: () => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "data", listener: (chunk: any) => void): this; - prependOnceListener(event: "end", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "pause", listener: () => void): this; - prependOnceListener(event: "readable", listener: () => void): this; - prependOnceListener(event: "resume", listener: () => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - removeListener(event: "close", listener: () => void): this; - removeListener(event: "data", listener: (chunk: any) => void): this; - removeListener(event: "end", listener: () => void): this; - removeListener(event: "error", listener: (err: Error) => void): this; - removeListener(event: "pause", listener: () => void): this; - removeListener(event: "readable", listener: () => void): this; - removeListener(event: "resume", listener: () => void): this; - removeListener(event: string | symbol, listener: (...args: any[]) => void): this; - [Symbol.asyncIterator](): AsyncIterableIterator; - /** - * Calls `readable.destroy()` with an `AbortError` and returns a promise that fulfills when the stream is finished. - * @since v20.4.0 - */ - [Symbol.asyncDispose](): Promise; - } - import WritableOptions = internal.WritableOptions; - class WritableBase extends Stream implements NodeJS.WritableStream { - /** - * Is `true` if it is safe to call `writable.write()`, which means - * the stream has not been destroyed, errored, or ended. - * @since v11.4.0 - */ - readonly writable: boolean; - /** - * Is `true` after `writable.end()` has been called. This property - * does not indicate whether the data has been flushed, for this use `writable.writableFinished` instead. - * @since v12.9.0 - */ - readonly writableEnded: boolean; - /** - * Is set to `true` immediately before the `'finish'` event is emitted. - * @since v12.6.0 - */ - readonly writableFinished: boolean; - /** - * Return the value of `highWaterMark` passed when creating this `Writable`. - * @since v9.3.0 - */ - readonly writableHighWaterMark: number; - /** - * This property contains the number of bytes (or objects) in the queue - * ready to be written. The value provides introspection data regarding - * the status of the `highWaterMark`. - * @since v9.4.0 - */ - readonly writableLength: number; - /** - * Getter for the property `objectMode` of a given `Writable` stream. - * @since v12.3.0 - */ - readonly writableObjectMode: boolean; - /** - * Number of times `writable.uncork()` needs to be - * called in order to fully uncork the stream. - * @since v13.2.0, v12.16.0 - */ - readonly writableCorked: number; - /** - * Is `true` after `writable.destroy()` has been called. - * @since v8.0.0 - */ - destroyed: boolean; - /** - * Is `true` after `'close'` has been emitted. - * @since v18.0.0 - */ - readonly closed: boolean; - /** - * Returns error if the stream has been destroyed with an error. - * @since v18.0.0 - */ - readonly errored: Error | null; - /** - * Is `true` if the stream's buffer has been full and stream will emit `'drain'`. - * @since v15.2.0, v14.17.0 - */ - readonly writableNeedDrain: boolean; - constructor(opts?: WritableOptions); - _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; - _writev?( - chunks: Array<{ - chunk: any; - encoding: BufferEncoding; - }>, - callback: (error?: Error | null) => void, - ): void; - _construct?(callback: (error?: Error | null) => void): void; - _destroy(error: Error | null, callback: (error?: Error | null) => void): void; - _final(callback: (error?: Error | null) => void): void; - /** - * The `writable.write()` method writes some data to the stream, and calls the - * supplied `callback` once the data has been fully handled. If an error - * occurs, the `callback` will be called with the error as its - * first argument. The `callback` is called asynchronously and before `'error'` is - * emitted. - * - * The return value is `true` if the internal buffer is less than the`highWaterMark` configured when the stream was created after admitting `chunk`. - * If `false` is returned, further attempts to write data to the stream should - * stop until the `'drain'` event is emitted. - * - * While a stream is not draining, calls to `write()` will buffer `chunk`, and - * return false. Once all currently buffered chunks are drained (accepted for - * delivery by the operating system), the `'drain'` event will be emitted. - * Once `write()` returns false, do not write more chunks - * until the `'drain'` event is emitted. While calling `write()` on a stream that - * is not draining is allowed, Node.js will buffer all written chunks until - * maximum memory usage occurs, at which point it will abort unconditionally. - * Even before it aborts, high memory usage will cause poor garbage collector - * performance and high RSS (which is not typically released back to the system, - * even after the memory is no longer required). Since TCP sockets may never - * drain if the remote peer does not read the data, writing a socket that is - * not draining may lead to a remotely exploitable vulnerability. - * - * Writing data while the stream is not draining is particularly - * problematic for a `Transform`, because the `Transform` streams are paused - * by default until they are piped or a `'data'` or `'readable'` event handler - * is added. - * - * If the data to be written can be generated or fetched on demand, it is - * recommended to encapsulate the logic into a `Readable` and use {@link pipe}. However, if calling `write()` is preferred, it is - * possible to respect backpressure and avoid memory issues using the `'drain'` event: - * - * ```js - * function write(data, cb) { - * if (!stream.write(data)) { - * stream.once('drain', cb); - * } else { - * process.nextTick(cb); - * } - * } - * - * // Wait for cb to be called before doing any other write. - * write('hello', () => { - * console.log('Write completed, do more writes now.'); - * }); - * ``` - * - * A `Writable` stream in object mode will always ignore the `encoding` argument. - * @since v0.9.4 - * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any - * JavaScript value other than `null`. - * @param [encoding='utf8'] The encoding, if `chunk` is a string. - * @param callback Callback for when this chunk of data is flushed. - * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. - */ - write(chunk: any, callback?: (error: Error | null | undefined) => void): boolean; - write(chunk: any, encoding: BufferEncoding, callback?: (error: Error | null | undefined) => void): boolean; - /** - * The `writable.setDefaultEncoding()` method sets the default `encoding` for a `Writable` stream. - * @since v0.11.15 - * @param encoding The new default encoding - */ - setDefaultEncoding(encoding: BufferEncoding): this; - /** - * Calling the `writable.end()` method signals that no more data will be written - * to the `Writable`. The optional `chunk` and `encoding` arguments allow one - * final additional chunk of data to be written immediately before closing the - * stream. - * - * Calling the {@link write} method after calling {@link end} will raise an error. - * - * ```js - * // Write 'hello, ' and then end with 'world!'. - * const fs = require('node:fs'); - * const file = fs.createWriteStream('example.txt'); - * file.write('hello, '); - * file.end('world!'); - * // Writing more now is not allowed! - * ``` - * @since v0.9.4 - * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any - * JavaScript value other than `null`. - * @param encoding The encoding if `chunk` is a string - * @param callback Callback for when the stream is finished. - */ - end(cb?: () => void): this; - end(chunk: any, cb?: () => void): this; - end(chunk: any, encoding: BufferEncoding, cb?: () => void): this; - /** - * The `writable.cork()` method forces all written data to be buffered in memory. - * The buffered data will be flushed when either the {@link uncork} or {@link end} methods are called. - * - * The primary intent of `writable.cork()` is to accommodate a situation in which - * several small chunks are written to the stream in rapid succession. Instead of - * immediately forwarding them to the underlying destination, `writable.cork()`buffers all the chunks until `writable.uncork()` is called, which will pass them - * all to `writable._writev()`, if present. This prevents a head-of-line blocking - * situation where data is being buffered while waiting for the first small chunk - * to be processed. However, use of `writable.cork()` without implementing`writable._writev()` may have an adverse effect on throughput. - * - * See also: `writable.uncork()`, `writable._writev()`. - * @since v0.11.2 - */ - cork(): void; - /** - * The `writable.uncork()` method flushes all data buffered since {@link cork} was called. - * - * When using `writable.cork()` and `writable.uncork()` to manage the buffering - * of writes to a stream, defer calls to `writable.uncork()` using`process.nextTick()`. Doing so allows batching of all`writable.write()` calls that occur within a given Node.js event - * loop phase. - * - * ```js - * stream.cork(); - * stream.write('some '); - * stream.write('data '); - * process.nextTick(() => stream.uncork()); - * ``` - * - * If the `writable.cork()` method is called multiple times on a stream, the - * same number of calls to `writable.uncork()` must be called to flush the buffered - * data. - * - * ```js - * stream.cork(); - * stream.write('some '); - * stream.cork(); - * stream.write('data '); - * process.nextTick(() => { - * stream.uncork(); - * // The data will not be flushed until uncork() is called a second time. - * stream.uncork(); - * }); - * ``` - * - * See also: `writable.cork()`. - * @since v0.11.2 - */ - uncork(): void; - /** - * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'`event (unless `emitClose` is set to `false`). After this call, the writable - * stream has ended and subsequent calls to `write()` or `end()` will result in - * an `ERR_STREAM_DESTROYED` error. - * This is a destructive and immediate way to destroy a stream. Previous calls to`write()` may not have drained, and may trigger an `ERR_STREAM_DESTROYED` error. - * Use `end()` instead of destroy if data should flush before close, or wait for - * the `'drain'` event before destroying the stream. - * - * Once `destroy()` has been called any further calls will be a no-op and no - * further errors except from `_destroy()` may be emitted as `'error'`. - * - * Implementors should not override this method, - * but instead implement `writable._destroy()`. - * @since v8.0.0 - * @param error Optional, an error to emit with `'error'` event. - */ - destroy(error?: Error): this; - /** - * Event emitter - * The defined events on documents including: - * 1. close - * 2. drain - * 3. error - * 4. finish - * 5. pipe - * 6. unpipe - */ - addListener(event: "close", listener: () => void): this; - addListener(event: "drain", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "finish", listener: () => void): this; - addListener(event: "pipe", listener: (src: Readable) => void): this; - addListener(event: "unpipe", listener: (src: Readable) => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - emit(event: "close"): boolean; - emit(event: "drain"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "finish"): boolean; - emit(event: "pipe", src: Readable): boolean; - emit(event: "unpipe", src: Readable): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - on(event: "close", listener: () => void): this; - on(event: "drain", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "finish", listener: () => void): this; - on(event: "pipe", listener: (src: Readable) => void): this; - on(event: "unpipe", listener: (src: Readable) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: "close", listener: () => void): this; - once(event: "drain", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "finish", listener: () => void): this; - once(event: "pipe", listener: (src: Readable) => void): this; - once(event: "unpipe", listener: (src: Readable) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "drain", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "finish", listener: () => void): this; - prependListener(event: "pipe", listener: (src: Readable) => void): this; - prependListener(event: "unpipe", listener: (src: Readable) => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "drain", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "finish", listener: () => void): this; - prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; - prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - removeListener(event: "close", listener: () => void): this; - removeListener(event: "drain", listener: () => void): this; - removeListener(event: "error", listener: (err: Error) => void): this; - removeListener(event: "finish", listener: () => void): this; - removeListener(event: "pipe", listener: (src: Readable) => void): this; - removeListener(event: "unpipe", listener: (src: Readable) => void): this; - removeListener(event: string | symbol, listener: (...args: any[]) => void): this; - } - namespace internal { - class Stream extends internal { - constructor(opts?: ReadableOptions); - } - interface StreamOptions extends Abortable { - emitClose?: boolean | undefined; - highWaterMark?: number | undefined; - objectMode?: boolean | undefined; - construct?(this: T, callback: (error?: Error | null) => void): void; - destroy?(this: T, error: Error | null, callback: (error?: Error | null) => void): void; - autoDestroy?: boolean | undefined; - } - interface ReadableOptions extends StreamOptions { - encoding?: BufferEncoding | undefined; - read?(this: Readable, size: number): void; - } - /** - * @since v0.9.4 - */ - class Readable extends ReadableBase { - /** - * A utility method for creating a `Readable` from a web `ReadableStream`. - * @since v17.0.0 - * @experimental - */ - static fromWeb( - readableStream: streamWeb.ReadableStream, - options?: Pick, - ): Readable; - /** - * A utility method for creating a web `ReadableStream` from a `Readable`. - * @since v17.0.0 - * @experimental - */ - static toWeb(streamReadable: Readable): streamWeb.ReadableStream; - } - interface WritableOptions extends StreamOptions { - decodeStrings?: boolean | undefined; - defaultEncoding?: BufferEncoding | undefined; - write?( - this: Writable, - chunk: any, - encoding: BufferEncoding, - callback: (error?: Error | null) => void, - ): void; - writev?( - this: Writable, - chunks: Array<{ - chunk: any; - encoding: BufferEncoding; - }>, - callback: (error?: Error | null) => void, - ): void; - final?(this: Writable, callback: (error?: Error | null) => void): void; - } - /** - * @since v0.9.4 - */ - class Writable extends WritableBase { - /** - * A utility method for creating a `Writable` from a web `WritableStream`. - * @since v17.0.0 - * @experimental - */ - static fromWeb( - writableStream: streamWeb.WritableStream, - options?: Pick, - ): Writable; - /** - * A utility method for creating a web `WritableStream` from a `Writable`. - * @since v17.0.0 - * @experimental - */ - static toWeb(streamWritable: Writable): streamWeb.WritableStream; - } - interface DuplexOptions extends ReadableOptions, WritableOptions { - allowHalfOpen?: boolean | undefined; - readableObjectMode?: boolean | undefined; - writableObjectMode?: boolean | undefined; - readableHighWaterMark?: number | undefined; - writableHighWaterMark?: number | undefined; - writableCorked?: number | undefined; - construct?(this: Duplex, callback: (error?: Error | null) => void): void; - read?(this: Duplex, size: number): void; - write?(this: Duplex, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; - writev?( - this: Duplex, - chunks: Array<{ - chunk: any; - encoding: BufferEncoding; - }>, - callback: (error?: Error | null) => void, - ): void; - final?(this: Duplex, callback: (error?: Error | null) => void): void; - destroy?(this: Duplex, error: Error | null, callback: (error?: Error | null) => void): void; - } - /** - * Duplex streams are streams that implement both the `Readable` and `Writable` interfaces. - * - * Examples of `Duplex` streams include: - * - * * `TCP sockets` - * * `zlib streams` - * * `crypto streams` - * @since v0.9.4 - */ - class Duplex extends ReadableBase implements WritableBase { - readonly writable: boolean; - readonly writableEnded: boolean; - readonly writableFinished: boolean; - readonly writableHighWaterMark: number; - readonly writableLength: number; - readonly writableObjectMode: boolean; - readonly writableCorked: number; - readonly writableNeedDrain: boolean; - readonly closed: boolean; - readonly errored: Error | null; - /** - * If `false` then the stream will automatically end the writable side when the - * readable side ends. Set initially by the `allowHalfOpen` constructor option, - * which defaults to `true`. - * - * This can be changed manually to change the half-open behavior of an existing`Duplex` stream instance, but must be changed before the `'end'` event is - * emitted. - * @since v0.9.4 - */ - allowHalfOpen: boolean; - constructor(opts?: DuplexOptions); - /** - * A utility method for creating duplex streams. - * - * - `Stream` converts writable stream into writable `Duplex` and readable stream - * to `Duplex`. - * - `Blob` converts into readable `Duplex`. - * - `string` converts into readable `Duplex`. - * - `ArrayBuffer` converts into readable `Duplex`. - * - `AsyncIterable` converts into a readable `Duplex`. Cannot yield `null`. - * - `AsyncGeneratorFunction` converts into a readable/writable transform - * `Duplex`. Must take a source `AsyncIterable` as first parameter. Cannot yield - * `null`. - * - `AsyncFunction` converts into a writable `Duplex`. Must return - * either `null` or `undefined` - * - `Object ({ writable, readable })` converts `readable` and - * `writable` into `Stream` and then combines them into `Duplex` where the - * `Duplex` will write to the `writable` and read from the `readable`. - * - `Promise` converts into readable `Duplex`. Value `null` is ignored. - * - * @since v16.8.0 - */ - static from( - src: - | Stream - | NodeBlob - | ArrayBuffer - | string - | Iterable - | AsyncIterable - | AsyncGeneratorFunction - | Promise - | Object, - ): Duplex; - _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; - _writev?( - chunks: Array<{ - chunk: any; - encoding: BufferEncoding; - }>, - callback: (error?: Error | null) => void, - ): void; - _destroy(error: Error | null, callback: (error?: Error | null) => void): void; - _final(callback: (error?: Error | null) => void): void; - write(chunk: any, encoding?: BufferEncoding, cb?: (error: Error | null | undefined) => void): boolean; - write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; - setDefaultEncoding(encoding: BufferEncoding): this; - end(cb?: () => void): this; - end(chunk: any, cb?: () => void): this; - end(chunk: any, encoding?: BufferEncoding, cb?: () => void): this; - cork(): void; - uncork(): void; - /** - * A utility method for creating a web `ReadableStream` and `WritableStream` from a `Duplex`. - * @since v17.0.0 - * @experimental - */ - static toWeb(streamDuplex: Duplex): { - readable: streamWeb.ReadableStream; - writable: streamWeb.WritableStream; - }; - /** - * A utility method for creating a `Duplex` from a web `ReadableStream` and `WritableStream`. - * @since v17.0.0 - * @experimental - */ - static fromWeb( - duplexStream: { - readable: streamWeb.ReadableStream; - writable: streamWeb.WritableStream; - }, - options?: Pick< - DuplexOptions, - "allowHalfOpen" | "decodeStrings" | "encoding" | "highWaterMark" | "objectMode" | "signal" - >, - ): Duplex; - /** - * Event emitter - * The defined events on documents including: - * 1. close - * 2. data - * 3. drain - * 4. end - * 5. error - * 6. finish - * 7. pause - * 8. pipe - * 9. readable - * 10. resume - * 11. unpipe - */ - addListener(event: "close", listener: () => void): this; - addListener(event: "data", listener: (chunk: any) => void): this; - addListener(event: "drain", listener: () => void): this; - addListener(event: "end", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "finish", listener: () => void): this; - addListener(event: "pause", listener: () => void): this; - addListener(event: "pipe", listener: (src: Readable) => void): this; - addListener(event: "readable", listener: () => void): this; - addListener(event: "resume", listener: () => void): this; - addListener(event: "unpipe", listener: (src: Readable) => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - emit(event: "close"): boolean; - emit(event: "data", chunk: any): boolean; - emit(event: "drain"): boolean; - emit(event: "end"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "finish"): boolean; - emit(event: "pause"): boolean; - emit(event: "pipe", src: Readable): boolean; - emit(event: "readable"): boolean; - emit(event: "resume"): boolean; - emit(event: "unpipe", src: Readable): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - on(event: "close", listener: () => void): this; - on(event: "data", listener: (chunk: any) => void): this; - on(event: "drain", listener: () => void): this; - on(event: "end", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "finish", listener: () => void): this; - on(event: "pause", listener: () => void): this; - on(event: "pipe", listener: (src: Readable) => void): this; - on(event: "readable", listener: () => void): this; - on(event: "resume", listener: () => void): this; - on(event: "unpipe", listener: (src: Readable) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: "close", listener: () => void): this; - once(event: "data", listener: (chunk: any) => void): this; - once(event: "drain", listener: () => void): this; - once(event: "end", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "finish", listener: () => void): this; - once(event: "pause", listener: () => void): this; - once(event: "pipe", listener: (src: Readable) => void): this; - once(event: "readable", listener: () => void): this; - once(event: "resume", listener: () => void): this; - once(event: "unpipe", listener: (src: Readable) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "data", listener: (chunk: any) => void): this; - prependListener(event: "drain", listener: () => void): this; - prependListener(event: "end", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "finish", listener: () => void): this; - prependListener(event: "pause", listener: () => void): this; - prependListener(event: "pipe", listener: (src: Readable) => void): this; - prependListener(event: "readable", listener: () => void): this; - prependListener(event: "resume", listener: () => void): this; - prependListener(event: "unpipe", listener: (src: Readable) => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "data", listener: (chunk: any) => void): this; - prependOnceListener(event: "drain", listener: () => void): this; - prependOnceListener(event: "end", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "finish", listener: () => void): this; - prependOnceListener(event: "pause", listener: () => void): this; - prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; - prependOnceListener(event: "readable", listener: () => void): this; - prependOnceListener(event: "resume", listener: () => void): this; - prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - removeListener(event: "close", listener: () => void): this; - removeListener(event: "data", listener: (chunk: any) => void): this; - removeListener(event: "drain", listener: () => void): this; - removeListener(event: "end", listener: () => void): this; - removeListener(event: "error", listener: (err: Error) => void): this; - removeListener(event: "finish", listener: () => void): this; - removeListener(event: "pause", listener: () => void): this; - removeListener(event: "pipe", listener: (src: Readable) => void): this; - removeListener(event: "readable", listener: () => void): this; - removeListener(event: "resume", listener: () => void): this; - removeListener(event: "unpipe", listener: (src: Readable) => void): this; - removeListener(event: string | symbol, listener: (...args: any[]) => void): this; - } - type TransformCallback = (error?: Error | null, data?: any) => void; - interface TransformOptions extends DuplexOptions { - construct?(this: Transform, callback: (error?: Error | null) => void): void; - read?(this: Transform, size: number): void; - write?( - this: Transform, - chunk: any, - encoding: BufferEncoding, - callback: (error?: Error | null) => void, - ): void; - writev?( - this: Transform, - chunks: Array<{ - chunk: any; - encoding: BufferEncoding; - }>, - callback: (error?: Error | null) => void, - ): void; - final?(this: Transform, callback: (error?: Error | null) => void): void; - destroy?(this: Transform, error: Error | null, callback: (error?: Error | null) => void): void; - transform?(this: Transform, chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; - flush?(this: Transform, callback: TransformCallback): void; - } - /** - * Transform streams are `Duplex` streams where the output is in some way - * related to the input. Like all `Duplex` streams, `Transform` streams - * implement both the `Readable` and `Writable` interfaces. - * - * Examples of `Transform` streams include: - * - * * `zlib streams` - * * `crypto streams` - * @since v0.9.4 - */ - class Transform extends Duplex { - constructor(opts?: TransformOptions); - _transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; - _flush(callback: TransformCallback): void; - } - /** - * The `stream.PassThrough` class is a trivial implementation of a `Transform` stream that simply passes the input bytes across to the output. Its purpose is - * primarily for examples and testing, but there are some use cases where`stream.PassThrough` is useful as a building block for novel sorts of streams. - */ - class PassThrough extends Transform {} - /** - * A stream to attach a signal to. - * - * Attaches an AbortSignal to a readable or writeable stream. This lets code - * control stream destruction using an `AbortController`. - * - * Calling `abort` on the `AbortController` corresponding to the passed`AbortSignal` will behave the same way as calling `.destroy(new AbortError())`on the stream, and `controller.error(new - * AbortError())` for webstreams. - * - * ```js - * const fs = require('node:fs'); - * - * const controller = new AbortController(); - * const read = addAbortSignal( - * controller.signal, - * fs.createReadStream(('object.json')), - * ); - * // Later, abort the operation closing the stream - * controller.abort(); - * ``` - * - * Or using an `AbortSignal` with a readable stream as an async iterable: - * - * ```js - * const controller = new AbortController(); - * setTimeout(() => controller.abort(), 10_000); // set a timeout - * const stream = addAbortSignal( - * controller.signal, - * fs.createReadStream(('object.json')), - * ); - * (async () => { - * try { - * for await (const chunk of stream) { - * await process(chunk); - * } - * } catch (e) { - * if (e.name === 'AbortError') { - * // The operation was cancelled - * } else { - * throw e; - * } - * } - * })(); - * ``` - * - * Or using an `AbortSignal` with a ReadableStream: - * - * ```js - * const controller = new AbortController(); - * const rs = new ReadableStream({ - * start(controller) { - * controller.enqueue('hello'); - * controller.enqueue('world'); - * controller.close(); - * }, - * }); - * - * addAbortSignal(controller.signal, rs); - * - * finished(rs, (err) => { - * if (err) { - * if (err.name === 'AbortError') { - * // The operation was cancelled - * } - * } - * }); - * - * const reader = rs.getReader(); - * - * reader.read().then(({ value, done }) => { - * console.log(value); // hello - * console.log(done); // false - * controller.abort(); - * }); - * ``` - * @since v15.4.0 - * @param signal A signal representing possible cancellation - * @param stream a stream to attach a signal to - */ - function addAbortSignal(signal: AbortSignal, stream: T): T; - /** - * Returns the default highWaterMark used by streams. - * Defaults to `16384` (16 KiB), or `16` for `objectMode`. - * @since v19.9.0 - * @param objectMode - */ - function getDefaultHighWaterMark(objectMode: boolean): number; - /** - * Sets the default highWaterMark used by streams. - * @since v19.9.0 - * @param objectMode - * @param value highWaterMark value - */ - function setDefaultHighWaterMark(objectMode: boolean, value: number): void; - interface FinishedOptions extends Abortable { - error?: boolean | undefined; - readable?: boolean | undefined; - writable?: boolean | undefined; - } - /** - * A readable and/or writable stream/webstream. - * - * A function to get notified when a stream is no longer readable, writable - * or has experienced an error or a premature close event. - * - * ```js - * const { finished } = require('node:stream'); - * const fs = require('node:fs'); - * - * const rs = fs.createReadStream('archive.tar'); - * - * finished(rs, (err) => { - * if (err) { - * console.error('Stream failed.', err); - * } else { - * console.log('Stream is done reading.'); - * } - * }); - * - * rs.resume(); // Drain the stream. - * ``` - * - * Especially useful in error handling scenarios where a stream is destroyed - * prematurely (like an aborted HTTP request), and will not emit `'end'`or `'finish'`. - * - * The `finished` API provides `promise version`. - * - * `stream.finished()` leaves dangling event listeners (in particular`'error'`, `'end'`, `'finish'` and `'close'`) after `callback` has been - * invoked. The reason for this is so that unexpected `'error'` events (due to - * incorrect stream implementations) do not cause unexpected crashes. - * If this is unwanted behavior then the returned cleanup function needs to be - * invoked in the callback: - * - * ```js - * const cleanup = finished(rs, (err) => { - * cleanup(); - * // ... - * }); - * ``` - * @since v10.0.0 - * @param stream A readable and/or writable stream. - * @param callback A callback function that takes an optional error argument. - * @return A cleanup function which removes all registered listeners. - */ - function finished( - stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, - options: FinishedOptions, - callback: (err?: NodeJS.ErrnoException | null) => void, - ): () => void; - function finished( - stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, - callback: (err?: NodeJS.ErrnoException | null) => void, - ): () => void; - namespace finished { - function __promisify__( - stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, - options?: FinishedOptions, - ): Promise; - } - type PipelineSourceFunction = () => Iterable | AsyncIterable; - type PipelineSource = Iterable | AsyncIterable | NodeJS.ReadableStream | PipelineSourceFunction; - type PipelineTransform, U> = - | NodeJS.ReadWriteStream - | (( - source: S extends (...args: any[]) => Iterable | AsyncIterable ? AsyncIterable - : S, - ) => AsyncIterable); - type PipelineTransformSource = PipelineSource | PipelineTransform; - type PipelineDestinationIterableFunction = (source: AsyncIterable) => AsyncIterable; - type PipelineDestinationPromiseFunction = (source: AsyncIterable) => Promise

; - type PipelineDestination, P> = S extends - PipelineTransformSource ? - | NodeJS.WritableStream - | PipelineDestinationIterableFunction - | PipelineDestinationPromiseFunction - : never; - type PipelineCallback> = S extends - PipelineDestinationPromiseFunction ? (err: NodeJS.ErrnoException | null, value: P) => void - : (err: NodeJS.ErrnoException | null) => void; - type PipelinePromise> = S extends - PipelineDestinationPromiseFunction ? Promise

: Promise; - interface PipelineOptions { - signal?: AbortSignal | undefined; - end?: boolean | undefined; - } - /** - * A module method to pipe between streams and generators forwarding errors and - * properly cleaning up and provide a callback when the pipeline is complete. - * - * ```js - * const { pipeline } = require('node:stream'); - * const fs = require('node:fs'); - * const zlib = require('node:zlib'); - * - * // Use the pipeline API to easily pipe a series of streams - * // together and get notified when the pipeline is fully done. - * - * // A pipeline to gzip a potentially huge tar file efficiently: - * - * pipeline( - * fs.createReadStream('archive.tar'), - * zlib.createGzip(), - * fs.createWriteStream('archive.tar.gz'), - * (err) => { - * if (err) { - * console.error('Pipeline failed.', err); - * } else { - * console.log('Pipeline succeeded.'); - * } - * }, - * ); - * ``` - * - * The `pipeline` API provides a `promise version`. - * - * `stream.pipeline()` will call `stream.destroy(err)` on all streams except: - * - * * `Readable` streams which have emitted `'end'` or `'close'`. - * * `Writable` streams which have emitted `'finish'` or `'close'`. - * - * `stream.pipeline()` leaves dangling event listeners on the streams - * after the `callback` has been invoked. In the case of reuse of streams after - * failure, this can cause event listener leaks and swallowed errors. If the last - * stream is readable, dangling event listeners will be removed so that the last - * stream can be consumed later. - * - * `stream.pipeline()` closes all the streams when an error is raised. - * The `IncomingRequest` usage with `pipeline` could lead to an unexpected behavior - * once it would destroy the socket without sending the expected response. - * See the example below: - * - * ```js - * const fs = require('node:fs'); - * const http = require('node:http'); - * const { pipeline } = require('node:stream'); - * - * const server = http.createServer((req, res) => { - * const fileStream = fs.createReadStream('./fileNotExist.txt'); - * pipeline(fileStream, res, (err) => { - * if (err) { - * console.log(err); // No such file - * // this message can't be sent once `pipeline` already destroyed the socket - * return res.end('error!!!'); - * } - * }); - * }); - * ``` - * @since v10.0.0 - * @param callback Called when the pipeline is fully done. - */ - function pipeline, B extends PipelineDestination>( - source: A, - destination: B, - callback?: PipelineCallback, - ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; - function pipeline< - A extends PipelineSource, - T1 extends PipelineTransform, - B extends PipelineDestination, - >( - source: A, - transform1: T1, - destination: B, - callback?: PipelineCallback, - ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; - function pipeline< - A extends PipelineSource, - T1 extends PipelineTransform, - T2 extends PipelineTransform, - B extends PipelineDestination, - >( - source: A, - transform1: T1, - transform2: T2, - destination: B, - callback?: PipelineCallback, - ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; - function pipeline< - A extends PipelineSource, - T1 extends PipelineTransform, - T2 extends PipelineTransform, - T3 extends PipelineTransform, - B extends PipelineDestination, - >( - source: A, - transform1: T1, - transform2: T2, - transform3: T3, - destination: B, - callback?: PipelineCallback, - ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; - function pipeline< - A extends PipelineSource, - T1 extends PipelineTransform, - T2 extends PipelineTransform, - T3 extends PipelineTransform, - T4 extends PipelineTransform, - B extends PipelineDestination, - >( - source: A, - transform1: T1, - transform2: T2, - transform3: T3, - transform4: T4, - destination: B, - callback?: PipelineCallback, - ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; - function pipeline( - streams: ReadonlyArray, - callback?: (err: NodeJS.ErrnoException | null) => void, - ): NodeJS.WritableStream; - function pipeline( - stream1: NodeJS.ReadableStream, - stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, - ...streams: Array< - NodeJS.ReadWriteStream | NodeJS.WritableStream | ((err: NodeJS.ErrnoException | null) => void) - > - ): NodeJS.WritableStream; - namespace pipeline { - function __promisify__, B extends PipelineDestination>( - source: A, - destination: B, - options?: PipelineOptions, - ): PipelinePromise; - function __promisify__< - A extends PipelineSource, - T1 extends PipelineTransform, - B extends PipelineDestination, - >( - source: A, - transform1: T1, - destination: B, - options?: PipelineOptions, - ): PipelinePromise; - function __promisify__< - A extends PipelineSource, - T1 extends PipelineTransform, - T2 extends PipelineTransform, - B extends PipelineDestination, - >( - source: A, - transform1: T1, - transform2: T2, - destination: B, - options?: PipelineOptions, - ): PipelinePromise; - function __promisify__< - A extends PipelineSource, - T1 extends PipelineTransform, - T2 extends PipelineTransform, - T3 extends PipelineTransform, - B extends PipelineDestination, - >( - source: A, - transform1: T1, - transform2: T2, - transform3: T3, - destination: B, - options?: PipelineOptions, - ): PipelinePromise; - function __promisify__< - A extends PipelineSource, - T1 extends PipelineTransform, - T2 extends PipelineTransform, - T3 extends PipelineTransform, - T4 extends PipelineTransform, - B extends PipelineDestination, - >( - source: A, - transform1: T1, - transform2: T2, - transform3: T3, - transform4: T4, - destination: B, - options?: PipelineOptions, - ): PipelinePromise; - function __promisify__( - streams: ReadonlyArray, - options?: PipelineOptions, - ): Promise; - function __promisify__( - stream1: NodeJS.ReadableStream, - stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, - ...streams: Array - ): Promise; - } - interface Pipe { - close(): void; - hasRef(): boolean; - ref(): void; - unref(): void; - } - /** - * Returns whether the stream has encountered an error. - * @since v17.3.0, v16.14.0 - * @experimental - */ - function isErrored(stream: Readable | Writable | NodeJS.ReadableStream | NodeJS.WritableStream): boolean; - /** - * Returns whether the stream is readable. - * @since v17.4.0, v16.14.0 - * @experimental - */ - function isReadable(stream: Readable | NodeJS.ReadableStream): boolean; - const promises: typeof streamPromises; - const consumers: typeof streamConsumers; - } - export = internal; -} -declare module "node:stream" { - import stream = require("stream"); - export = stream; -} diff --git a/node_modules/@types/node/ts4.8/stream/consumers.d.ts b/node_modules/@types/node/ts4.8/stream/consumers.d.ts deleted file mode 100644 index 5ad9cbab98829fd66db9effa031b885647ba251c..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/stream/consumers.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -declare module "stream/consumers" { - import { Blob as NodeBlob } from "node:buffer"; - import { Readable } from "node:stream"; - function buffer(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; - function text(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; - function arrayBuffer(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; - function blob(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; - function json(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; -} -declare module "node:stream/consumers" { - export * from "stream/consumers"; -} diff --git a/node_modules/@types/node/ts4.8/stream/promises.d.ts b/node_modules/@types/node/ts4.8/stream/promises.d.ts deleted file mode 100644 index 6eac5b7156a6b0cecea5c24cd8037a0a75af42eb..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/stream/promises.d.ts +++ /dev/null @@ -1,83 +0,0 @@ -declare module "stream/promises" { - import { - FinishedOptions, - PipelineDestination, - PipelineOptions, - PipelinePromise, - PipelineSource, - PipelineTransform, - } from "node:stream"; - function finished( - stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, - options?: FinishedOptions, - ): Promise; - function pipeline, B extends PipelineDestination>( - source: A, - destination: B, - options?: PipelineOptions, - ): PipelinePromise; - function pipeline< - A extends PipelineSource, - T1 extends PipelineTransform, - B extends PipelineDestination, - >( - source: A, - transform1: T1, - destination: B, - options?: PipelineOptions, - ): PipelinePromise; - function pipeline< - A extends PipelineSource, - T1 extends PipelineTransform, - T2 extends PipelineTransform, - B extends PipelineDestination, - >( - source: A, - transform1: T1, - transform2: T2, - destination: B, - options?: PipelineOptions, - ): PipelinePromise; - function pipeline< - A extends PipelineSource, - T1 extends PipelineTransform, - T2 extends PipelineTransform, - T3 extends PipelineTransform, - B extends PipelineDestination, - >( - source: A, - transform1: T1, - transform2: T2, - transform3: T3, - destination: B, - options?: PipelineOptions, - ): PipelinePromise; - function pipeline< - A extends PipelineSource, - T1 extends PipelineTransform, - T2 extends PipelineTransform, - T3 extends PipelineTransform, - T4 extends PipelineTransform, - B extends PipelineDestination, - >( - source: A, - transform1: T1, - transform2: T2, - transform3: T3, - transform4: T4, - destination: B, - options?: PipelineOptions, - ): PipelinePromise; - function pipeline( - streams: ReadonlyArray, - options?: PipelineOptions, - ): Promise; - function pipeline( - stream1: NodeJS.ReadableStream, - stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, - ...streams: Array - ): Promise; -} -declare module "node:stream/promises" { - export * from "stream/promises"; -} diff --git a/node_modules/@types/node/ts4.8/stream/web.d.ts b/node_modules/@types/node/ts4.8/stream/web.d.ts deleted file mode 100644 index 361594dfaf7774fde49f749c51b12c7dd177381e..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/stream/web.d.ts +++ /dev/null @@ -1,366 +0,0 @@ -declare module "stream/web" { - // stub module, pending copy&paste from .d.ts or manual impl - // copy from lib.dom.d.ts - interface ReadableWritablePair { - readable: ReadableStream; - /** - * Provides a convenient, chainable way of piping this readable stream - * through a transform stream (or any other { writable, readable } - * pair). It simply pipes the stream into the writable side of the - * supplied pair, and returns the readable side for further use. - * - * Piping a stream will lock it for the duration of the pipe, preventing - * any other consumer from acquiring a reader. - */ - writable: WritableStream; - } - interface StreamPipeOptions { - preventAbort?: boolean; - preventCancel?: boolean; - /** - * Pipes this readable stream to a given writable stream destination. - * The way in which the piping process behaves under various error - * conditions can be customized with a number of passed options. It - * returns a promise that fulfills when the piping process completes - * successfully, or rejects if any errors were encountered. - * - * Piping a stream will lock it for the duration of the pipe, preventing - * any other consumer from acquiring a reader. - * - * Errors and closures of the source and destination streams propagate - * as follows: - * - * An error in this source readable stream will abort destination, - * unless preventAbort is truthy. The returned promise will be rejected - * with the source's error, or with any error that occurs during - * aborting the destination. - * - * An error in destination will cancel this source readable stream, - * unless preventCancel is truthy. The returned promise will be rejected - * with the destination's error, or with any error that occurs during - * canceling the source. - * - * When this source readable stream closes, destination will be closed, - * unless preventClose is truthy. The returned promise will be fulfilled - * once this process completes, unless an error is encountered while - * closing the destination, in which case it will be rejected with that - * error. - * - * If destination starts out closed or closing, this source readable - * stream will be canceled, unless preventCancel is true. The returned - * promise will be rejected with an error indicating piping to a closed - * stream failed, or with any error that occurs during canceling the - * source. - * - * The signal option can be set to an AbortSignal to allow aborting an - * ongoing pipe operation via the corresponding AbortController. In this - * case, this source readable stream will be canceled, and destination - * aborted, unless the respective options preventCancel or preventAbort - * are set. - */ - preventClose?: boolean; - signal?: AbortSignal; - } - interface ReadableStreamGenericReader { - readonly closed: Promise; - cancel(reason?: any): Promise; - } - interface ReadableStreamDefaultReadValueResult { - done: false; - value: T; - } - interface ReadableStreamDefaultReadDoneResult { - done: true; - value?: undefined; - } - type ReadableStreamController = ReadableStreamDefaultController; - type ReadableStreamDefaultReadResult = - | ReadableStreamDefaultReadValueResult - | ReadableStreamDefaultReadDoneResult; - interface ReadableStreamReadValueResult { - done: false; - value: T; - } - interface ReadableStreamReadDoneResult { - done: true; - value?: T; - } - type ReadableStreamReadResult = ReadableStreamReadValueResult | ReadableStreamReadDoneResult; - interface ReadableByteStreamControllerCallback { - (controller: ReadableByteStreamController): void | PromiseLike; - } - interface UnderlyingSinkAbortCallback { - (reason?: any): void | PromiseLike; - } - interface UnderlyingSinkCloseCallback { - (): void | PromiseLike; - } - interface UnderlyingSinkStartCallback { - (controller: WritableStreamDefaultController): any; - } - interface UnderlyingSinkWriteCallback { - (chunk: W, controller: WritableStreamDefaultController): void | PromiseLike; - } - interface UnderlyingSourceCancelCallback { - (reason?: any): void | PromiseLike; - } - interface UnderlyingSourcePullCallback { - (controller: ReadableStreamController): void | PromiseLike; - } - interface UnderlyingSourceStartCallback { - (controller: ReadableStreamController): any; - } - interface TransformerFlushCallback { - (controller: TransformStreamDefaultController): void | PromiseLike; - } - interface TransformerStartCallback { - (controller: TransformStreamDefaultController): any; - } - interface TransformerTransformCallback { - (chunk: I, controller: TransformStreamDefaultController): void | PromiseLike; - } - interface UnderlyingByteSource { - autoAllocateChunkSize?: number; - cancel?: ReadableStreamErrorCallback; - pull?: ReadableByteStreamControllerCallback; - start?: ReadableByteStreamControllerCallback; - type: "bytes"; - } - interface UnderlyingSource { - cancel?: UnderlyingSourceCancelCallback; - pull?: UnderlyingSourcePullCallback; - start?: UnderlyingSourceStartCallback; - type?: undefined; - } - interface UnderlyingSink { - abort?: UnderlyingSinkAbortCallback; - close?: UnderlyingSinkCloseCallback; - start?: UnderlyingSinkStartCallback; - type?: undefined; - write?: UnderlyingSinkWriteCallback; - } - interface ReadableStreamErrorCallback { - (reason: any): void | PromiseLike; - } - /** This Streams API interface represents a readable stream of byte data. */ - interface ReadableStream { - readonly locked: boolean; - cancel(reason?: any): Promise; - getReader(): ReadableStreamDefaultReader; - getReader(options: { mode: "byob" }): ReadableStreamBYOBReader; - pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; - pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; - tee(): [ReadableStream, ReadableStream]; - values(options?: { preventCancel?: boolean }): AsyncIterableIterator; - [Symbol.asyncIterator](): AsyncIterableIterator; - } - const ReadableStream: { - prototype: ReadableStream; - new(underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; - new(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; - }; - interface ReadableStreamDefaultReader extends ReadableStreamGenericReader { - read(): Promise>; - releaseLock(): void; - } - interface ReadableStreamBYOBReader extends ReadableStreamGenericReader { - read(view: T): Promise>; - releaseLock(): void; - } - const ReadableStreamDefaultReader: { - prototype: ReadableStreamDefaultReader; - new(stream: ReadableStream): ReadableStreamDefaultReader; - }; - const ReadableStreamBYOBReader: any; - const ReadableStreamBYOBRequest: any; - interface ReadableByteStreamController { - readonly byobRequest: undefined; - readonly desiredSize: number | null; - close(): void; - enqueue(chunk: ArrayBufferView): void; - error(error?: any): void; - } - const ReadableByteStreamController: { - prototype: ReadableByteStreamController; - new(): ReadableByteStreamController; - }; - interface ReadableStreamDefaultController { - readonly desiredSize: number | null; - close(): void; - enqueue(chunk?: R): void; - error(e?: any): void; - } - const ReadableStreamDefaultController: { - prototype: ReadableStreamDefaultController; - new(): ReadableStreamDefaultController; - }; - interface Transformer { - flush?: TransformerFlushCallback; - readableType?: undefined; - start?: TransformerStartCallback; - transform?: TransformerTransformCallback; - writableType?: undefined; - } - interface TransformStream { - readonly readable: ReadableStream; - readonly writable: WritableStream; - } - const TransformStream: { - prototype: TransformStream; - new( - transformer?: Transformer, - writableStrategy?: QueuingStrategy, - readableStrategy?: QueuingStrategy, - ): TransformStream; - }; - interface TransformStreamDefaultController { - readonly desiredSize: number | null; - enqueue(chunk?: O): void; - error(reason?: any): void; - terminate(): void; - } - const TransformStreamDefaultController: { - prototype: TransformStreamDefaultController; - new(): TransformStreamDefaultController; - }; - /** - * This Streams API interface provides a standard abstraction for writing - * streaming data to a destination, known as a sink. This object comes with - * built-in back pressure and queuing. - */ - interface WritableStream { - readonly locked: boolean; - abort(reason?: any): Promise; - close(): Promise; - getWriter(): WritableStreamDefaultWriter; - } - const WritableStream: { - prototype: WritableStream; - new(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream; - }; - /** - * This Streams API interface is the object returned by - * WritableStream.getWriter() and once created locks the < writer to the - * WritableStream ensuring that no other streams can write to the underlying - * sink. - */ - interface WritableStreamDefaultWriter { - readonly closed: Promise; - readonly desiredSize: number | null; - readonly ready: Promise; - abort(reason?: any): Promise; - close(): Promise; - releaseLock(): void; - write(chunk?: W): Promise; - } - const WritableStreamDefaultWriter: { - prototype: WritableStreamDefaultWriter; - new(stream: WritableStream): WritableStreamDefaultWriter; - }; - /** - * This Streams API interface represents a controller allowing control of a - * WritableStream's state. When constructing a WritableStream, the - * underlying sink is given a corresponding WritableStreamDefaultController - * instance to manipulate. - */ - interface WritableStreamDefaultController { - error(e?: any): void; - } - const WritableStreamDefaultController: { - prototype: WritableStreamDefaultController; - new(): WritableStreamDefaultController; - }; - interface QueuingStrategy { - highWaterMark?: number; - size?: QueuingStrategySize; - } - interface QueuingStrategySize { - (chunk?: T): number; - } - interface QueuingStrategyInit { - /** - * Creates a new ByteLengthQueuingStrategy with the provided high water - * mark. - * - * Note that the provided high water mark will not be validated ahead of - * time. Instead, if it is negative, NaN, or not a number, the resulting - * ByteLengthQueuingStrategy will cause the corresponding stream - * constructor to throw. - */ - highWaterMark: number; - } - /** - * This Streams API interface provides a built-in byte length queuing - * strategy that can be used when constructing streams. - */ - interface ByteLengthQueuingStrategy extends QueuingStrategy { - readonly highWaterMark: number; - readonly size: QueuingStrategySize; - } - const ByteLengthQueuingStrategy: { - prototype: ByteLengthQueuingStrategy; - new(init: QueuingStrategyInit): ByteLengthQueuingStrategy; - }; - /** - * This Streams API interface provides a built-in byte length queuing - * strategy that can be used when constructing streams. - */ - interface CountQueuingStrategy extends QueuingStrategy { - readonly highWaterMark: number; - readonly size: QueuingStrategySize; - } - const CountQueuingStrategy: { - prototype: CountQueuingStrategy; - new(init: QueuingStrategyInit): CountQueuingStrategy; - }; - interface TextEncoderStream { - /** Returns "utf-8". */ - readonly encoding: "utf-8"; - readonly readable: ReadableStream; - readonly writable: WritableStream; - readonly [Symbol.toStringTag]: string; - } - const TextEncoderStream: { - prototype: TextEncoderStream; - new(): TextEncoderStream; - }; - interface TextDecoderOptions { - fatal?: boolean; - ignoreBOM?: boolean; - } - type BufferSource = ArrayBufferView | ArrayBuffer; - interface TextDecoderStream { - /** Returns encoding's name, lower cased. */ - readonly encoding: string; - /** Returns `true` if error mode is "fatal", and `false` otherwise. */ - readonly fatal: boolean; - /** Returns `true` if ignore BOM flag is set, and `false` otherwise. */ - readonly ignoreBOM: boolean; - readonly readable: ReadableStream; - readonly writable: WritableStream; - readonly [Symbol.toStringTag]: string; - } - const TextDecoderStream: { - prototype: TextDecoderStream; - new(encoding?: string, options?: TextDecoderOptions): TextDecoderStream; - }; - interface CompressionStream { - readonly readable: ReadableStream; - readonly writable: WritableStream; - } - const CompressionStream: { - prototype: CompressionStream; - new(format: string): CompressionStream; - }; - interface DecompressionStream { - readonly readable: ReadableStream; - readonly writable: WritableStream; - } - const DecompressionStream: { - prototype: DecompressionStream; - new(format: string): DecompressionStream; - }; -} -declare module "node:stream/web" { - export * from "stream/web"; -} diff --git a/node_modules/@types/node/ts4.8/string_decoder.d.ts b/node_modules/@types/node/ts4.8/string_decoder.d.ts deleted file mode 100644 index b8691e1f060076e08ed0f023889adef0f2e8fb4e..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/string_decoder.d.ts +++ /dev/null @@ -1,67 +0,0 @@ -/** - * The `node:string_decoder` module provides an API for decoding `Buffer` objects - * into strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16 - * characters. It can be accessed using: - * - * ```js - * const { StringDecoder } = require('node:string_decoder'); - * ``` - * - * The following example shows the basic use of the `StringDecoder` class. - * - * ```js - * const { StringDecoder } = require('node:string_decoder'); - * const decoder = new StringDecoder('utf8'); - * - * const cent = Buffer.from([0xC2, 0xA2]); - * console.log(decoder.write(cent)); // Prints: ¢ - * - * const euro = Buffer.from([0xE2, 0x82, 0xAC]); - * console.log(decoder.write(euro)); // Prints: € - * ``` - * - * When a `Buffer` instance is written to the `StringDecoder` instance, an - * internal buffer is used to ensure that the decoded string does not contain - * any incomplete multibyte characters. These are held in the buffer until the - * next call to `stringDecoder.write()` or until `stringDecoder.end()` is called. - * - * In the following example, the three UTF-8 encoded bytes of the European Euro - * symbol (`€`) are written over three separate operations: - * - * ```js - * const { StringDecoder } = require('node:string_decoder'); - * const decoder = new StringDecoder('utf8'); - * - * decoder.write(Buffer.from([0xE2])); - * decoder.write(Buffer.from([0x82])); - * console.log(decoder.end(Buffer.from([0xAC]))); // Prints: € - * ``` - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/string_decoder.js) - */ -declare module "string_decoder" { - class StringDecoder { - constructor(encoding?: BufferEncoding); - /** - * Returns a decoded string, ensuring that any incomplete multibyte characters at - * the end of the `Buffer`, or `TypedArray`, or `DataView` are omitted from the - * returned string and stored in an internal buffer for the next call to`stringDecoder.write()` or `stringDecoder.end()`. - * @since v0.1.99 - * @param buffer The bytes to decode. - */ - write(buffer: Buffer): string; - /** - * Returns any remaining input stored in the internal buffer as a string. Bytes - * representing incomplete UTF-8 and UTF-16 characters will be replaced with - * substitution characters appropriate for the character encoding. - * - * If the `buffer` argument is provided, one final call to `stringDecoder.write()`is performed before returning the remaining input. - * After `end()` is called, the `stringDecoder` object can be reused for new input. - * @since v0.9.3 - * @param buffer The bytes to decode. - */ - end(buffer?: Buffer): string; - } -} -declare module "node:string_decoder" { - export * from "string_decoder"; -} diff --git a/node_modules/@types/node/ts4.8/test.d.ts b/node_modules/@types/node/ts4.8/test.d.ts deleted file mode 100644 index 149c9e0b77671ac4cfd8a7cc0c3b9310f786c6fd..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/test.d.ts +++ /dev/null @@ -1,1465 +0,0 @@ -/** - * The `node:test` module facilitates the creation of JavaScript tests. - * To access it: - * - * ```js - * import test from 'node:test'; - * ``` - * - * This module is only available under the `node:` scheme. The following will not - * work: - * - * ```js - * import test from 'test'; - * ``` - * - * Tests created via the `test` module consist of a single function that is - * processed in one of three ways: - * - * 1. A synchronous function that is considered failing if it throws an exception, - * and is considered passing otherwise. - * 2. A function that returns a `Promise` that is considered failing if the`Promise` rejects, and is considered passing if the `Promise` fulfills. - * 3. A function that receives a callback function. If the callback receives any - * truthy value as its first argument, the test is considered failing. If a - * falsy value is passed as the first argument to the callback, the test is - * considered passing. If the test function receives a callback function and - * also returns a `Promise`, the test will fail. - * - * The following example illustrates how tests are written using the`test` module. - * - * ```js - * test('synchronous passing test', (t) => { - * // This test passes because it does not throw an exception. - * assert.strictEqual(1, 1); - * }); - * - * test('synchronous failing test', (t) => { - * // This test fails because it throws an exception. - * assert.strictEqual(1, 2); - * }); - * - * test('asynchronous passing test', async (t) => { - * // This test passes because the Promise returned by the async - * // function is settled and not rejected. - * assert.strictEqual(1, 1); - * }); - * - * test('asynchronous failing test', async (t) => { - * // This test fails because the Promise returned by the async - * // function is rejected. - * assert.strictEqual(1, 2); - * }); - * - * test('failing test using Promises', (t) => { - * // Promises can be used directly as well. - * return new Promise((resolve, reject) => { - * setImmediate(() => { - * reject(new Error('this will cause the test to fail')); - * }); - * }); - * }); - * - * test('callback passing test', (t, done) => { - * // done() is the callback function. When the setImmediate() runs, it invokes - * // done() with no arguments. - * setImmediate(done); - * }); - * - * test('callback failing test', (t, done) => { - * // When the setImmediate() runs, done() is invoked with an Error object and - * // the test fails. - * setImmediate(() => { - * done(new Error('callback failure')); - * }); - * }); - * ``` - * - * If any tests fail, the process exit code is set to `1`. - * @since v18.0.0, v16.17.0 - * @see [source](https://github.com/nodejs/node/blob/v20.4.0/lib/test.js) - */ -declare module "node:test" { - import { Readable } from "node:stream"; - import { AsyncResource } from "node:async_hooks"; - /** - * **Note:**`shard` is used to horizontally parallelize test running across - * machines or processes, ideal for large-scale executions across varied - * environments. It's incompatible with `watch` mode, tailored for rapid - * code iteration by automatically rerunning tests on file changes. - * - * ```js - * import { tap } from 'node:test/reporters'; - * import { run } from 'node:test'; - * import process from 'node:process'; - * import path from 'node:path'; - * - * run({ files: [path.resolve('./tests/test.js')] }) - * .compose(tap) - * .pipe(process.stdout); - * ``` - * @since v18.9.0, v16.19.0 - * @param options Configuration options for running tests. The following properties are supported: - */ - function run(options?: RunOptions): TestsStream; - /** - * The `test()` function is the value imported from the `test` module. Each - * invocation of this function results in reporting the test to the `TestsStream`. - * - * The `TestContext` object passed to the `fn` argument can be used to perform - * actions related to the current test. Examples include skipping the test, adding - * additional diagnostic information, or creating subtests. - * - * `test()` returns a `Promise` that fulfills once the test completes. - * if `test()` is called within a `describe()` block, it fulfills immediately. - * The return value can usually be discarded for top level tests. - * However, the return value from subtests should be used to prevent the parent - * test from finishing first and cancelling the subtest - * as shown in the following example. - * - * ```js - * test('top level test', async (t) => { - * // The setTimeout() in the following subtest would cause it to outlive its - * // parent test if 'await' is removed on the next line. Once the parent test - * // completes, it will cancel any outstanding subtests. - * await t.test('longer running subtest', async (t) => { - * return new Promise((resolve, reject) => { - * setTimeout(resolve, 1000); - * }); - * }); - * }); - * ``` - * - * The `timeout` option can be used to fail the test if it takes longer than`timeout` milliseconds to complete. However, it is not a reliable mechanism for - * canceling tests because a running test might block the application thread and - * thus prevent the scheduled cancellation. - * @since v18.0.0, v16.17.0 - * @param [name='The name'] The name of the test, which is displayed when reporting test results. - * @param options Configuration options for the test. The following properties are supported: - * @param [fn='A no-op function'] The function under test. The first argument to this function is a {@link TestContext} object. If the test uses callbacks, the callback function is passed as the - * second argument. - * @return Fulfilled with `undefined` once the test completes, or immediately if the test runs within {@link describe}. - */ - function test(name?: string, fn?: TestFn): Promise; - function test(name?: string, options?: TestOptions, fn?: TestFn): Promise; - function test(options?: TestOptions, fn?: TestFn): Promise; - function test(fn?: TestFn): Promise; - namespace test { - export { after, afterEach, before, beforeEach, describe, it, mock, only, run, skip, test, todo }; - } - /** - * The `describe()` function imported from the `node:test` module. Each - * invocation of this function results in the creation of a Subtest. - * After invocation of top level `describe` functions, - * all top level tests and suites will execute. - * @param [name='The name'] The name of the suite, which is displayed when reporting test results. - * @param options Configuration options for the suite. supports the same options as `test([name][, options][, fn])`. - * @param [fn='A no-op function'] The function under suite declaring all subtests and subsuites. The first argument to this function is a {@link SuiteContext} object. - * @return Immediately fulfilled with `undefined`. - */ - function describe(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; - function describe(name?: string, fn?: SuiteFn): Promise; - function describe(options?: TestOptions, fn?: SuiteFn): Promise; - function describe(fn?: SuiteFn): Promise; - namespace describe { - /** - * Shorthand for skipping a suite, same as `describe([name], { skip: true }[, fn])`. - */ - function skip(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; - function skip(name?: string, fn?: SuiteFn): Promise; - function skip(options?: TestOptions, fn?: SuiteFn): Promise; - function skip(fn?: SuiteFn): Promise; - /** - * Shorthand for marking a suite as `TODO`, same as `describe([name], { todo: true }[, fn])`. - */ - function todo(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; - function todo(name?: string, fn?: SuiteFn): Promise; - function todo(options?: TestOptions, fn?: SuiteFn): Promise; - function todo(fn?: SuiteFn): Promise; - /** - * Shorthand for marking a suite as `only`, same as `describe([name], { only: true }[, fn])`. - * @since v18.15.0 - */ - function only(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; - function only(name?: string, fn?: SuiteFn): Promise; - function only(options?: TestOptions, fn?: SuiteFn): Promise; - function only(fn?: SuiteFn): Promise; - } - /** - * Shorthand for `test()`. - * - * The `it()` function is imported from the `node:test` module. - * @since v18.6.0, v16.17.0 - */ - function it(name?: string, options?: TestOptions, fn?: TestFn): Promise; - function it(name?: string, fn?: TestFn): Promise; - function it(options?: TestOptions, fn?: TestFn): Promise; - function it(fn?: TestFn): Promise; - namespace it { - /** - * Shorthand for skipping a test, same as `it([name], { skip: true }[, fn])`. - */ - function skip(name?: string, options?: TestOptions, fn?: TestFn): Promise; - function skip(name?: string, fn?: TestFn): Promise; - function skip(options?: TestOptions, fn?: TestFn): Promise; - function skip(fn?: TestFn): Promise; - /** - * Shorthand for marking a test as `TODO`, same as `it([name], { todo: true }[, fn])`. - */ - function todo(name?: string, options?: TestOptions, fn?: TestFn): Promise; - function todo(name?: string, fn?: TestFn): Promise; - function todo(options?: TestOptions, fn?: TestFn): Promise; - function todo(fn?: TestFn): Promise; - /** - * Shorthand for marking a test as `only`, same as `it([name], { only: true }[, fn])`. - * @since v18.15.0 - */ - function only(name?: string, options?: TestOptions, fn?: TestFn): Promise; - function only(name?: string, fn?: TestFn): Promise; - function only(options?: TestOptions, fn?: TestFn): Promise; - function only(fn?: TestFn): Promise; - } - /** - * Shorthand for skipping a test, same as `test([name], { skip: true }[, fn])`. - * @since v20.2.0 - */ - function skip(name?: string, options?: TestOptions, fn?: TestFn): Promise; - function skip(name?: string, fn?: TestFn): Promise; - function skip(options?: TestOptions, fn?: TestFn): Promise; - function skip(fn?: TestFn): Promise; - /** - * Shorthand for marking a test as `TODO`, same as `test([name], { todo: true }[, fn])`. - * @since v20.2.0 - */ - function todo(name?: string, options?: TestOptions, fn?: TestFn): Promise; - function todo(name?: string, fn?: TestFn): Promise; - function todo(options?: TestOptions, fn?: TestFn): Promise; - function todo(fn?: TestFn): Promise; - /** - * Shorthand for marking a test as `only`, same as `test([name], { only: true }[, fn])`. - * @since v20.2.0 - */ - function only(name?: string, options?: TestOptions, fn?: TestFn): Promise; - function only(name?: string, fn?: TestFn): Promise; - function only(options?: TestOptions, fn?: TestFn): Promise; - function only(fn?: TestFn): Promise; - /** - * The type of a function under test. The first argument to this function is a - * {@link TestContext} object. If the test uses callbacks, the callback function is passed as - * the second argument. - */ - type TestFn = (t: TestContext, done: (result?: any) => void) => void | Promise; - /** - * The type of a function under Suite. - */ - type SuiteFn = (s: SuiteContext) => void | Promise; - interface TestShard { - /** - * A positive integer between 1 and `` that specifies the index of the shard to run. - */ - index: number; - /** - * A positive integer that specifies the total number of shards to split the test files to. - */ - total: number; - } - interface RunOptions { - /** - * If a number is provided, then that many files would run in parallel. - * If truthy, it would run (number of cpu cores - 1) files in parallel. - * If falsy, it would only run one file at a time. - * If unspecified, subtests inherit this value from their parent. - * @default true - */ - concurrency?: number | boolean | undefined; - /** - * An array containing the list of files to run. - * If unspecified, the test runner execution model will be used. - */ - files?: readonly string[] | undefined; - /** - * Allows aborting an in-progress test execution. - * @default undefined - */ - signal?: AbortSignal | undefined; - /** - * A number of milliseconds the test will fail after. - * If unspecified, subtests inherit this value from their parent. - * @default Infinity - */ - timeout?: number | undefined; - /** - * Sets inspector port of test child process. - * If a nullish value is provided, each process gets its own port, - * incremented from the primary's `process.debugPort`. - */ - inspectPort?: number | (() => number) | undefined; - /** - * That can be used to only run tests whose name matches the provided pattern. - * Test name patterns are interpreted as JavaScript regular expressions. - * For each test that is executed, any corresponding test hooks, such as `beforeEach()`, are also run. - */ - testNamePatterns?: string | RegExp | string[] | RegExp[]; - /** - * If truthy, the test context will only run tests that have the `only` option set - */ - only?: boolean; - /** - * A function that accepts the TestsStream instance and can be used to setup listeners before any tests are run. - */ - setup?: (root: Test) => void | Promise; - /** - * Whether to run in watch mode or not. - * @default false - */ - watch?: boolean | undefined; - /** - * Running tests in a specific shard. - * @default undefined - */ - shard?: TestShard | undefined; - } - class Test extends AsyncResource { - concurrency: number; - nesting: number; - only: boolean; - reporter: TestsStream; - runOnlySubtests: boolean; - testNumber: number; - timeout: number | null; - } - /** - * A successful call to `run()` method will return a new `TestsStream` object, streaming a series of events representing the execution of the tests.`TestsStream` will emit events, in the - * order of the tests definition - * @since v18.9.0, v16.19.0 - */ - class TestsStream extends Readable implements NodeJS.ReadableStream { - addListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; - addListener(event: "test:fail", listener: (data: TestFail) => void): this; - addListener(event: "test:pass", listener: (data: TestPass) => void): this; - addListener(event: "test:plan", listener: (data: TestPlan) => void): this; - addListener(event: "test:start", listener: (data: TestStart) => void): this; - addListener(event: "test:stderr", listener: (data: TestStderr) => void): this; - addListener(event: "test:stdout", listener: (data: TestStdout) => void): this; - addListener(event: string, listener: (...args: any[]) => void): this; - emit(event: "test:diagnostic", data: DiagnosticData): boolean; - emit(event: "test:fail", data: TestFail): boolean; - emit(event: "test:pass", data: TestPass): boolean; - emit(event: "test:plan", data: TestPlan): boolean; - emit(event: "test:start", data: TestStart): boolean; - emit(event: "test:stderr", data: TestStderr): boolean; - emit(event: "test:stdout", data: TestStdout): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - on(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; - on(event: "test:fail", listener: (data: TestFail) => void): this; - on(event: "test:pass", listener: (data: TestPass) => void): this; - on(event: "test:plan", listener: (data: TestPlan) => void): this; - on(event: "test:start", listener: (data: TestStart) => void): this; - on(event: "test:stderr", listener: (data: TestStderr) => void): this; - on(event: "test:stdout", listener: (data: TestStdout) => void): this; - on(event: string, listener: (...args: any[]) => void): this; - once(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; - once(event: "test:fail", listener: (data: TestFail) => void): this; - once(event: "test:pass", listener: (data: TestPass) => void): this; - once(event: "test:plan", listener: (data: TestPlan) => void): this; - once(event: "test:start", listener: (data: TestStart) => void): this; - once(event: "test:stderr", listener: (data: TestStderr) => void): this; - once(event: "test:stdout", listener: (data: TestStdout) => void): this; - once(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; - prependListener(event: "test:fail", listener: (data: TestFail) => void): this; - prependListener(event: "test:pass", listener: (data: TestPass) => void): this; - prependListener(event: "test:plan", listener: (data: TestPlan) => void): this; - prependListener(event: "test:start", listener: (data: TestStart) => void): this; - prependListener(event: "test:stderr", listener: (data: TestStderr) => void): this; - prependListener(event: "test:stdout", listener: (data: TestStdout) => void): this; - prependListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; - prependOnceListener(event: "test:fail", listener: (data: TestFail) => void): this; - prependOnceListener(event: "test:pass", listener: (data: TestPass) => void): this; - prependOnceListener(event: "test:plan", listener: (data: TestPlan) => void): this; - prependOnceListener(event: "test:start", listener: (data: TestStart) => void): this; - prependOnceListener(event: "test:stderr", listener: (data: TestStderr) => void): this; - prependOnceListener(event: "test:stdout", listener: (data: TestStdout) => void): this; - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - } - /** - * An instance of `TestContext` is passed to each test function in order to - * interact with the test runner. However, the `TestContext` constructor is not - * exposed as part of the API. - * @since v18.0.0, v16.17.0 - */ - class TestContext { - /** - * This function is used to create a hook running before subtest of the current test. - * @param fn The hook function. If the hook uses callbacks, the callback function is passed as - * the second argument. Default: A no-op function. - * @param options Configuration options for the hook. - * @since v20.1.0 - */ - before: typeof before; - /** - * This function is used to create a hook running before each subtest of the current test. - * @param fn The hook function. If the hook uses callbacks, the callback function is passed as - * the second argument. Default: A no-op function. - * @param options Configuration options for the hook. - * @since v18.8.0 - */ - beforeEach: typeof beforeEach; - /** - * This function is used to create a hook that runs after the current test finishes. - * @param fn The hook function. If the hook uses callbacks, the callback function is passed as - * the second argument. Default: A no-op function. - * @param options Configuration options for the hook. - * @since v18.13.0 - */ - after: typeof after; - /** - * This function is used to create a hook running after each subtest of the current test. - * @param fn The hook function. If the hook uses callbacks, the callback function is passed as - * the second argument. Default: A no-op function. - * @param options Configuration options for the hook. - * @since v18.8.0 - */ - afterEach: typeof afterEach; - /** - * This function is used to write diagnostics to the output. Any diagnostic - * information is included at the end of the test's results. This function does - * not return a value. - * - * ```js - * test('top level test', (t) => { - * t.diagnostic('A diagnostic message'); - * }); - * ``` - * @since v18.0.0, v16.17.0 - * @param message Message to be reported. - */ - diagnostic(message: string): void; - /** - * The name of the test. - * @since v18.8.0, v16.18.0 - */ - readonly name: string; - /** - * If `shouldRunOnlyTests` is truthy, the test context will only run tests that - * have the `only` option set. Otherwise, all tests are run. If Node.js was not - * started with the `--test-only` command-line option, this function is a - * no-op. - * - * ```js - * test('top level test', (t) => { - * // The test context can be set to run subtests with the 'only' option. - * t.runOnly(true); - * return Promise.all([ - * t.test('this subtest is now skipped'), - * t.test('this subtest is run', { only: true }), - * ]); - * }); - * ``` - * @since v18.0.0, v16.17.0 - * @param shouldRunOnlyTests Whether or not to run `only` tests. - */ - runOnly(shouldRunOnlyTests: boolean): void; - /** - * ```js - * test('top level test', async (t) => { - * await fetch('some/uri', { signal: t.signal }); - * }); - * ``` - * @since v18.7.0, v16.17.0 - */ - readonly signal: AbortSignal; - /** - * This function causes the test's output to indicate the test as skipped. If`message` is provided, it is included in the output. Calling `skip()` does - * not terminate execution of the test function. This function does not return a - * value. - * - * ```js - * test('top level test', (t) => { - * // Make sure to return here as well if the test contains additional logic. - * t.skip('this is skipped'); - * }); - * ``` - * @since v18.0.0, v16.17.0 - * @param message Optional skip message. - */ - skip(message?: string): void; - /** - * This function adds a `TODO` directive to the test's output. If `message` is - * provided, it is included in the output. Calling `todo()` does not terminate - * execution of the test function. This function does not return a value. - * - * ```js - * test('top level test', (t) => { - * // This test is marked as `TODO` - * t.todo('this is a todo'); - * }); - * ``` - * @since v18.0.0, v16.17.0 - * @param message Optional `TODO` message. - */ - todo(message?: string): void; - /** - * This function is used to create subtests under the current test. This function behaves in - * the same fashion as the top level {@link test} function. - * @since v18.0.0 - * @param name The name of the test, which is displayed when reporting test results. - * Default: The `name` property of fn, or `''` if `fn` does not have a name. - * @param options Configuration options for the test - * @param fn The function under test. This first argument to this function is a - * {@link TestContext} object. If the test uses callbacks, the callback function is - * passed as the second argument. Default: A no-op function. - * @returns A {@link Promise} resolved with `undefined` once the test completes. - */ - test: typeof test; - /** - * Each test provides its own MockTracker instance. - */ - readonly mock: MockTracker; - } - /** - * An instance of `SuiteContext` is passed to each suite function in order to - * interact with the test runner. However, the `SuiteContext` constructor is not - * exposed as part of the API. - * @since v18.7.0, v16.17.0 - */ - class SuiteContext { - /** - * The name of the suite. - * @since v18.8.0, v16.18.0 - */ - readonly name: string; - /** - * Can be used to abort test subtasks when the test has been aborted. - * @since v18.7.0, v16.17.0 - */ - readonly signal: AbortSignal; - } - interface TestOptions { - /** - * If a number is provided, then that many tests would run in parallel. - * If truthy, it would run (number of cpu cores - 1) tests in parallel. - * For subtests, it will be `Infinity` tests in parallel. - * If falsy, it would only run one test at a time. - * If unspecified, subtests inherit this value from their parent. - * @default false - */ - concurrency?: number | boolean | undefined; - /** - * If truthy, and the test context is configured to run `only` tests, then this test will be - * run. Otherwise, the test is skipped. - * @default false - */ - only?: boolean | undefined; - /** - * Allows aborting an in-progress test. - * @since v18.8.0 - */ - signal?: AbortSignal | undefined; - /** - * If truthy, the test is skipped. If a string is provided, that string is displayed in the - * test results as the reason for skipping the test. - * @default false - */ - skip?: boolean | string | undefined; - /** - * A number of milliseconds the test will fail after. If unspecified, subtests inherit this - * value from their parent. - * @default Infinity - * @since v18.7.0 - */ - timeout?: number | undefined; - /** - * If truthy, the test marked as `TODO`. If a string is provided, that string is displayed in - * the test results as the reason why the test is `TODO`. - * @default false - */ - todo?: boolean | string | undefined; - } - /** - * This function is used to create a hook running before running a suite. - * - * ```js - * describe('tests', async () => { - * before(() => console.log('about to run some test')); - * it('is a subtest', () => { - * assert.ok('some relevant assertion here'); - * }); - * }); - * ``` - * @since v18.8.0, v16.18.0 - * @param [fn='A no-op function'] The hook function. If the hook uses callbacks, the callback function is passed as the second argument. - * @param options Configuration options for the hook. The following properties are supported: - */ - function before(fn?: HookFn, options?: HookOptions): void; - /** - * This function is used to create a hook running after running a suite. - * - * ```js - * describe('tests', async () => { - * after(() => console.log('finished running tests')); - * it('is a subtest', () => { - * assert.ok('some relevant assertion here'); - * }); - * }); - * ``` - * @since v18.8.0, v16.18.0 - * @param [fn='A no-op function'] The hook function. If the hook uses callbacks, the callback function is passed as the second argument. - * @param options Configuration options for the hook. The following properties are supported: - */ - function after(fn?: HookFn, options?: HookOptions): void; - /** - * This function is used to create a hook running - * before each subtest of the current suite. - * - * ```js - * describe('tests', async () => { - * beforeEach(() => console.log('about to run a test')); - * it('is a subtest', () => { - * assert.ok('some relevant assertion here'); - * }); - * }); - * ``` - * @since v18.8.0, v16.18.0 - * @param [fn='A no-op function'] The hook function. If the hook uses callbacks, the callback function is passed as the second argument. - * @param options Configuration options for the hook. The following properties are supported: - */ - function beforeEach(fn?: HookFn, options?: HookOptions): void; - /** - * This function is used to create a hook running - * after each subtest of the current test. - * - * ```js - * describe('tests', async () => { - * afterEach(() => console.log('finished running a test')); - * it('is a subtest', () => { - * assert.ok('some relevant assertion here'); - * }); - * }); - * ``` - * @since v18.8.0, v16.18.0 - * @param [fn='A no-op function'] The hook function. If the hook uses callbacks, the callback function is passed as the second argument. - * @param options Configuration options for the hook. The following properties are supported: - */ - function afterEach(fn?: HookFn, options?: HookOptions): void; - /** - * The hook function. If the hook uses callbacks, the callback function is passed as the - * second argument. - */ - type HookFn = (s: SuiteContext, done: (result?: any) => void) => any; - /** - * Configuration options for hooks. - * @since v18.8.0 - */ - interface HookOptions { - /** - * Allows aborting an in-progress hook. - */ - signal?: AbortSignal | undefined; - /** - * A number of milliseconds the hook will fail after. If unspecified, subtests inherit this - * value from their parent. - * @default Infinity - */ - timeout?: number | undefined; - } - interface MockFunctionOptions { - /** - * The number of times that the mock will use the behavior of `implementation`. - * Once the mock function has been called `times` times, - * it will automatically restore the behavior of `original`. - * This value must be an integer greater than zero. - * @default Infinity - */ - times?: number | undefined; - } - interface MockMethodOptions extends MockFunctionOptions { - /** - * If `true`, `object[methodName]` is treated as a getter. - * This option cannot be used with the `setter` option. - */ - getter?: boolean | undefined; - /** - * If `true`, `object[methodName]` is treated as a setter. - * This option cannot be used with the `getter` option. - */ - setter?: boolean | undefined; - } - type Mock = F & { - mock: MockFunctionContext; - }; - type NoOpFunction = (...args: any[]) => undefined; - type FunctionPropertyNames = { - [K in keyof T]: T[K] extends Function ? K : never; - }[keyof T]; - /** - * The `MockTracker` class is used to manage mocking functionality. The test runner - * module provides a top level `mock` export which is a `MockTracker` instance. - * Each test also provides its own `MockTracker` instance via the test context's`mock` property. - * @since v19.1.0, v18.13.0 - */ - class MockTracker { - /** - * This function is used to create a mock function. - * - * The following example creates a mock function that increments a counter by one - * on each invocation. The `times` option is used to modify the mock behavior such - * that the first two invocations add two to the counter instead of one. - * - * ```js - * test('mocks a counting function', (t) => { - * let cnt = 0; - * - * function addOne() { - * cnt++; - * return cnt; - * } - * - * function addTwo() { - * cnt += 2; - * return cnt; - * } - * - * const fn = t.mock.fn(addOne, addTwo, { times: 2 }); - * - * assert.strictEqual(fn(), 2); - * assert.strictEqual(fn(), 4); - * assert.strictEqual(fn(), 5); - * assert.strictEqual(fn(), 6); - * }); - * ``` - * @since v19.1.0, v18.13.0 - * @param [original='A no-op function'] An optional function to create a mock on. - * @param implementation An optional function used as the mock implementation for `original`. This is useful for creating mocks that exhibit one behavior for a specified number of calls and - * then restore the behavior of `original`. - * @param options Optional configuration options for the mock function. The following properties are supported: - * @return The mocked function. The mocked function contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the - * behavior of the mocked function. - */ - fn(original?: F, options?: MockFunctionOptions): Mock; - fn( - original?: F, - implementation?: Implementation, - options?: MockFunctionOptions, - ): Mock; - /** - * This function is used to create a mock on an existing object method. The - * following example demonstrates how a mock is created on an existing object - * method. - * - * ```js - * test('spies on an object method', (t) => { - * const number = { - * value: 5, - * subtract(a) { - * return this.value - a; - * }, - * }; - * - * t.mock.method(number, 'subtract'); - * assert.strictEqual(number.subtract.mock.calls.length, 0); - * assert.strictEqual(number.subtract(3), 2); - * assert.strictEqual(number.subtract.mock.calls.length, 1); - * - * const call = number.subtract.mock.calls[0]; - * - * assert.deepStrictEqual(call.arguments, [3]); - * assert.strictEqual(call.result, 2); - * assert.strictEqual(call.error, undefined); - * assert.strictEqual(call.target, undefined); - * assert.strictEqual(call.this, number); - * }); - * ``` - * @since v19.1.0, v18.13.0 - * @param object The object whose method is being mocked. - * @param methodName The identifier of the method on `object` to mock. If `object[methodName]` is not a function, an error is thrown. - * @param implementation An optional function used as the mock implementation for `object[methodName]`. - * @param options Optional configuration options for the mock method. The following properties are supported: - * @return The mocked method. The mocked method contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the - * behavior of the mocked method. - */ - method< - MockedObject extends object, - MethodName extends FunctionPropertyNames, - >( - object: MockedObject, - methodName: MethodName, - options?: MockFunctionOptions, - ): MockedObject[MethodName] extends Function ? Mock - : never; - method< - MockedObject extends object, - MethodName extends FunctionPropertyNames, - Implementation extends Function, - >( - object: MockedObject, - methodName: MethodName, - implementation: Implementation, - options?: MockFunctionOptions, - ): MockedObject[MethodName] extends Function ? Mock - : never; - method( - object: MockedObject, - methodName: keyof MockedObject, - options: MockMethodOptions, - ): Mock; - method( - object: MockedObject, - methodName: keyof MockedObject, - implementation: Function, - options: MockMethodOptions, - ): Mock; - - /** - * This function is syntax sugar for `MockTracker.method` with `options.getter`set to `true`. - * @since v19.3.0, v18.13.0 - */ - getter< - MockedObject extends object, - MethodName extends keyof MockedObject, - >( - object: MockedObject, - methodName: MethodName, - options?: MockFunctionOptions, - ): Mock<() => MockedObject[MethodName]>; - getter< - MockedObject extends object, - MethodName extends keyof MockedObject, - Implementation extends Function, - >( - object: MockedObject, - methodName: MethodName, - implementation?: Implementation, - options?: MockFunctionOptions, - ): Mock<(() => MockedObject[MethodName]) | Implementation>; - /** - * This function is syntax sugar for `MockTracker.method` with `options.setter`set to `true`. - * @since v19.3.0, v18.13.0 - */ - setter< - MockedObject extends object, - MethodName extends keyof MockedObject, - >( - object: MockedObject, - methodName: MethodName, - options?: MockFunctionOptions, - ): Mock<(value: MockedObject[MethodName]) => void>; - setter< - MockedObject extends object, - MethodName extends keyof MockedObject, - Implementation extends Function, - >( - object: MockedObject, - methodName: MethodName, - implementation?: Implementation, - options?: MockFunctionOptions, - ): Mock<((value: MockedObject[MethodName]) => void) | Implementation>; - /** - * This function restores the default behavior of all mocks that were previously - * created by this `MockTracker` and disassociates the mocks from the`MockTracker` instance. Once disassociated, the mocks can still be used, but the`MockTracker` instance can no longer be - * used to reset their behavior or - * otherwise interact with them. - * - * After each test completes, this function is called on the test context's`MockTracker`. If the global `MockTracker` is used extensively, calling this - * function manually is recommended. - * @since v19.1.0, v18.13.0 - */ - reset(): void; - /** - * This function restores the default behavior of all mocks that were previously - * created by this `MockTracker`. Unlike `mock.reset()`, `mock.restoreAll()` does - * not disassociate the mocks from the `MockTracker` instance. - * @since v19.1.0, v18.13.0 - */ - restoreAll(): void; - timers: MockTimers; - } - const mock: MockTracker; - interface MockFunctionCall< - F extends Function, - ReturnType = F extends (...args: any) => infer T ? T - : F extends abstract new(...args: any) => infer T ? T - : unknown, - Args = F extends (...args: infer Y) => any ? Y - : F extends abstract new(...args: infer Y) => any ? Y - : unknown[], - > { - /** - * An array of the arguments passed to the mock function. - */ - arguments: Args; - /** - * If the mocked function threw then this property contains the thrown value. - */ - error: unknown | undefined; - /** - * The value returned by the mocked function. - * - * If the mocked function threw, it will be `undefined`. - */ - result: ReturnType | undefined; - /** - * An `Error` object whose stack can be used to determine the callsite of the mocked function invocation. - */ - stack: Error; - /** - * If the mocked function is a constructor, this field contains the class being constructed. - * Otherwise this will be `undefined`. - */ - target: F extends abstract new(...args: any) => any ? F : undefined; - /** - * The mocked function's `this` value. - */ - this: unknown; - } - /** - * The `MockFunctionContext` class is used to inspect or manipulate the behavior of - * mocks created via the `MockTracker` APIs. - * @since v19.1.0, v18.13.0 - */ - class MockFunctionContext { - /** - * A getter that returns a copy of the internal array used to track calls to the - * mock. Each entry in the array is an object with the following properties. - * @since v19.1.0, v18.13.0 - */ - readonly calls: Array>; - /** - * This function returns the number of times that this mock has been invoked. This - * function is more efficient than checking `ctx.calls.length` because `ctx.calls`is a getter that creates a copy of the internal call tracking array. - * @since v19.1.0, v18.13.0 - * @return The number of times that this mock has been invoked. - */ - callCount(): number; - /** - * This function is used to change the behavior of an existing mock. - * - * The following example creates a mock function using `t.mock.fn()`, calls the - * mock function, and then changes the mock implementation to a different function. - * - * ```js - * test('changes a mock behavior', (t) => { - * let cnt = 0; - * - * function addOne() { - * cnt++; - * return cnt; - * } - * - * function addTwo() { - * cnt += 2; - * return cnt; - * } - * - * const fn = t.mock.fn(addOne); - * - * assert.strictEqual(fn(), 1); - * fn.mock.mockImplementation(addTwo); - * assert.strictEqual(fn(), 3); - * assert.strictEqual(fn(), 5); - * }); - * ``` - * @since v19.1.0, v18.13.0 - * @param implementation The function to be used as the mock's new implementation. - */ - mockImplementation(implementation: Function): void; - /** - * This function is used to change the behavior of an existing mock for a single - * invocation. Once invocation `onCall` has occurred, the mock will revert to - * whatever behavior it would have used had `mockImplementationOnce()` not been - * called. - * - * The following example creates a mock function using `t.mock.fn()`, calls the - * mock function, changes the mock implementation to a different function for the - * next invocation, and then resumes its previous behavior. - * - * ```js - * test('changes a mock behavior once', (t) => { - * let cnt = 0; - * - * function addOne() { - * cnt++; - * return cnt; - * } - * - * function addTwo() { - * cnt += 2; - * return cnt; - * } - * - * const fn = t.mock.fn(addOne); - * - * assert.strictEqual(fn(), 1); - * fn.mock.mockImplementationOnce(addTwo); - * assert.strictEqual(fn(), 3); - * assert.strictEqual(fn(), 4); - * }); - * ``` - * @since v19.1.0, v18.13.0 - * @param implementation The function to be used as the mock's implementation for the invocation number specified by `onCall`. - * @param onCall The invocation number that will use `implementation`. If the specified invocation has already occurred then an exception is thrown. - */ - mockImplementationOnce(implementation: Function, onCall?: number): void; - /** - * Resets the call history of the mock function. - * @since v19.3.0, v18.13.0 - */ - resetCalls(): void; - /** - * Resets the implementation of the mock function to its original behavior. The - * mock can still be used after calling this function. - * @since v19.1.0, v18.13.0 - */ - restore(): void; - } - type Timer = "setInterval" | "setTimeout" | "setImmediate" | "Date"; - - interface MockTimersOptions { - apis: Timer[]; - now?: number | Date; - } - /** - * Mocking timers is a technique commonly used in software testing to simulate and - * control the behavior of timers, such as `setInterval` and `setTimeout`, - * without actually waiting for the specified time intervals. - * - * The MockTimers API also allows for mocking of the `Date` constructor and - * `setImmediate`/`clearImmediate` functions. - * - * The `MockTracker` provides a top-level `timers` export - * which is a `MockTimers` instance. - * @since v20.4.0 - * @experimental - */ - class MockTimers { - /** - * Enables timer mocking for the specified timers. - * - * **Note:** When you enable mocking for a specific timer, its associated - * clear function will also be implicitly mocked. - * - * **Note:** Mocking `Date` will affect the behavior of the mocked timers - * as they use the same internal clock. - * - * Example usage without setting initial time: - * - * ```js - * import { mock } from 'node:test'; - * mock.timers.enable({ apis: ['setInterval', 'Date'], now: 1234 }); - * ``` - * - * The above example enables mocking for the `Date` constructor, `setInterval` timer and - * implicitly mocks the `clearInterval` function. Only the `Date` constructor from `globalThis`, - * `setInterval` and `clearInterval` functions from `node:timers`,`node:timers/promises`, and `globalThis` will be mocked. - * - * Example usage with initial time set - * - * ```js - * import { mock } from 'node:test'; - * mock.timers.enable({ apis: ['Date'], now: 1000 }); - * ``` - * - * Example usage with initial Date object as time set - * - * ```js - * import { mock } from 'node:test'; - * mock.timers.enable({ apis: ['Date'], now: new Date() }); - * ``` - * - * Alternatively, if you call `mock.timers.enable()` without any parameters: - * - * All timers (`'setInterval'`, `'clearInterval'`, `'Date'`, `'setImmediate'`, `'clearImmediate'`, `'setTimeout'`, and `'clearTimeout'`) - * will be mocked. - * - * The `setInterval`, `clearInterval`, `setTimeout`, and `clearTimeout` functions from `node:timers`, `node:timers/promises`, - * and `globalThis` will be mocked. - * The `Date` constructor from `globalThis` will be mocked. - * - * If there is no initial epoch set, the initial date will be based on 0 in the Unix epoch. This is `January 1st, 1970, 00:00:00 UTC`. You can set an initial date by passing a now property to the `.enable()` method. This value will be used as the initial date for the mocked Date object. It can either be a positive integer, or another Date object. - * @since v20.4.0 - */ - enable(options?: MockTimersOptions): void; - /** - * You can use the `.setTime()` method to manually move the mocked date to another time. This method only accepts a positive integer. - * Note: This method will execute any mocked timers that are in the past from the new time. - * In the below example we are setting a new time for the mocked date. - * ```js - * import assert from 'node:assert'; - * import { test } from 'node:test'; - * test('sets the time of a date object', (context) => { - * // Optionally choose what to mock - * context.mock.timers.enable({ apis: ['Date'], now: 100 }); - * assert.strictEqual(Date.now(), 100); - * // Advance in time will also advance the date - * context.mock.timers.setTime(1000); - * context.mock.timers.tick(200); - * assert.strictEqual(Date.now(), 1200); - * }); - * ``` - */ - setTime(time: number): void; - /** - * This function restores the default behavior of all mocks that were previously - * created by this `MockTimers` instance and disassociates the mocks - * from the `MockTracker` instance. - * - * **Note:** After each test completes, this function is called on - * the test context's `MockTracker`. - * - * ```js - * import { mock } from 'node:test'; - * mock.timers.reset(); - * ``` - * @since v20.4.0 - */ - reset(): void; - /** - * Advances time for all mocked timers. - * - * **Note:** This diverges from how `setTimeout` in Node.js behaves and accepts - * only positive numbers. In Node.js, `setTimeout` with negative numbers is - * only supported for web compatibility reasons. - * - * The following example mocks a `setTimeout` function and - * by using `.tick` advances in - * time triggering all pending timers. - * - * ```js - * import assert from 'node:assert'; - * import { test } from 'node:test'; - * - * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { - * const fn = context.mock.fn(); - * - * context.mock.timers.enable({ apis: ['setTimeout'] }); - * - * setTimeout(fn, 9999); - * - * assert.strictEqual(fn.mock.callCount(), 0); - * - * // Advance in time - * context.mock.timers.tick(9999); - * - * assert.strictEqual(fn.mock.callCount(), 1); - * }); - * ``` - * - * Alternativelly, the `.tick` function can be called many times - * - * ```js - * import assert from 'node:assert'; - * import { test } from 'node:test'; - * - * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { - * const fn = context.mock.fn(); - * context.mock.timers.enable({ apis: ['setTimeout'] }); - * const nineSecs = 9000; - * setTimeout(fn, nineSecs); - * - * const twoSeconds = 3000; - * context.mock.timers.tick(twoSeconds); - * context.mock.timers.tick(twoSeconds); - * context.mock.timers.tick(twoSeconds); - * - * assert.strictEqual(fn.mock.callCount(), 1); - * }); - * ``` - * - * Advancing time using `.tick` will also advance the time for any `Date` object - * created after the mock was enabled (if `Date` was also set to be mocked). - * - * ```js - * import assert from 'node:assert'; - * import { test } from 'node:test'; - * - * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { - * const fn = context.mock.fn(); - * - * context.mock.timers.enable({ apis: ['setTimeout', 'Date'] }); - * setTimeout(fn, 9999); - * - * assert.strictEqual(fn.mock.callCount(), 0); - * assert.strictEqual(Date.now(), 0); - * - * // Advance in time - * context.mock.timers.tick(9999); - * assert.strictEqual(fn.mock.callCount(), 1); - * assert.strictEqual(Date.now(), 9999); - * }); - * ``` - * @since v20.4.0 - */ - tick(milliseconds: number): void; - /** - * Triggers all pending mocked timers immediately. If the `Date` object is also - * mocked, it will also advance the `Date` object to the furthest timer's time. - * - * The example below triggers all pending timers immediately, - * causing them to execute without any delay. - * - * ```js - * import assert from 'node:assert'; - * import { test } from 'node:test'; - * - * test('runAll functions following the given order', (context) => { - * context.mock.timers.enable({ apis: ['setTimeout', 'Date'] }); - * const results = []; - * setTimeout(() => results.push(1), 9999); - * - * // Notice that if both timers have the same timeout, - * // the order of execution is guaranteed - * setTimeout(() => results.push(3), 8888); - * setTimeout(() => results.push(2), 8888); - * - * assert.deepStrictEqual(results, []); - * - * context.mock.timers.runAll(); - * assert.deepStrictEqual(results, [3, 2, 1]); - * // The Date object is also advanced to the furthest timer's time - * assert.strictEqual(Date.now(), 9999); - * }); - * ``` - * - * **Note:** The `runAll()` function is specifically designed for - * triggering timers in the context of timer mocking. - * It does not have any effect on real-time system - * clocks or actual timers outside of the mocking environment. - * @since v20.4.0 - */ - runAll(): void; - /** - * Calls {@link MockTimers.reset()}. - */ - [Symbol.dispose](): void; - } - export { - after, - afterEach, - before, - beforeEach, - describe, - it, - Mock, - mock, - only, - run, - skip, - test, - test as default, - todo, - }; -} - -interface TestLocationInfo { - /** - * The column number where the test is defined, or - * `undefined` if the test was run through the REPL. - */ - column?: number; - /** - * The path of the test file, `undefined` if test is not ran through a file. - */ - file?: string; - /** - * The line number where the test is defined, or - * `undefined` if the test was run through the REPL. - */ - line?: number; -} -interface DiagnosticData extends TestLocationInfo { - /** - * The diagnostic message. - */ - message: string; - /** - * The nesting level of the test. - */ - nesting: number; -} -interface TestFail extends TestLocationInfo { - /** - * Additional execution metadata. - */ - details: { - /** - * The duration of the test in milliseconds. - */ - duration_ms: number; - /** - * The error thrown by the test. - */ - error: Error; - /** - * The type of the test, used to denote whether this is a suite. - * @since 20.0.0, 19.9.0, 18.17.0 - */ - type?: "suite"; - }; - /** - * The test name. - */ - name: string; - /** - * The nesting level of the test. - */ - nesting: number; - /** - * The ordinal number of the test. - */ - testNumber: number; - /** - * Present if `context.todo` is called. - */ - todo?: string | boolean; - /** - * Present if `context.skip` is called. - */ - skip?: string | boolean; -} -interface TestPass extends TestLocationInfo { - /** - * Additional execution metadata. - */ - details: { - /** - * The duration of the test in milliseconds. - */ - duration_ms: number; - /** - * The type of the test, used to denote whether this is a suite. - * @since 20.0.0, 19.9.0, 18.17.0 - */ - type?: "suite"; - }; - /** - * The test name. - */ - name: string; - /** - * The nesting level of the test. - */ - nesting: number; - /** - * The ordinal number of the test. - */ - testNumber: number; - /** - * Present if `context.todo` is called. - */ - todo?: string | boolean; - /** - * Present if `context.skip` is called. - */ - skip?: string | boolean; -} -interface TestPlan extends TestLocationInfo { - /** - * The nesting level of the test. - */ - nesting: number; - /** - * The number of subtests that have ran. - */ - count: number; -} -interface TestStart extends TestLocationInfo { - /** - * The test name. - */ - name: string; - /** - * The nesting level of the test. - */ - nesting: number; -} -interface TestStderr extends TestLocationInfo { - /** - * The message written to `stderr` - */ - message: string; -} -interface TestStdout extends TestLocationInfo { - /** - * The message written to `stdout` - */ - message: string; -} -interface TestEnqueue extends TestLocationInfo { - /** - * The test name - */ - name: string; - /** - * The nesting level of the test. - */ - nesting: number; -} -interface TestDequeue extends TestLocationInfo { - /** - * The test name - */ - name: string; - /** - * The nesting level of the test. - */ - nesting: number; -} - -/** - * The `node:test/reporters` module exposes the builtin-reporters for `node:test`. - * To access it: - * - * ```js - * import test from 'node:test/reporters'; - * ``` - * - * This module is only available under the `node:` scheme. The following will not - * work: - * - * ```js - * import test from 'test/reporters'; - * ``` - * @since v19.9.0 - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/test/reporters.js) - */ -declare module "node:test/reporters" { - import { Transform, TransformOptions } from "node:stream"; - - type TestEvent = - | { type: "test:diagnostic"; data: DiagnosticData } - | { type: "test:fail"; data: TestFail } - | { type: "test:pass"; data: TestPass } - | { type: "test:plan"; data: TestPlan } - | { type: "test:start"; data: TestStart } - | { type: "test:stderr"; data: TestStderr } - | { type: "test:stdout"; data: TestStdout } - | { type: "test:enqueue"; data: TestEnqueue } - | { type: "test:dequeue"; data: TestDequeue } - | { type: "test:watch:drained" }; - type TestEventGenerator = AsyncGenerator; - - /** - * The `dot` reporter outputs the test results in a compact format, - * where each passing test is represented by a `.`, - * and each failing test is represented by a `X`. - */ - function dot(source: TestEventGenerator): AsyncGenerator<"\n" | "." | "X", void>; - /** - * The `tap` reporter outputs the test results in the [TAP](https://testanything.org/) format. - */ - function tap(source: TestEventGenerator): AsyncGenerator; - /** - * The `spec` reporter outputs the test results in a human-readable format. - */ - class Spec extends Transform { - constructor(); - } - /** - * The `junit` reporter outputs test results in a jUnit XML format - */ - function junit(source: TestEventGenerator): AsyncGenerator; - class Lcov extends Transform { - constructor(opts?: TransformOptions); - } - export { dot, junit, Lcov as lcov, Spec as spec, tap, TestEvent }; -} diff --git a/node_modules/@types/node/ts4.8/timers.d.ts b/node_modules/@types/node/ts4.8/timers.d.ts deleted file mode 100644 index 039f31f7ad0e07c4a455b0db6204648fe0e3e8b4..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/timers.d.ts +++ /dev/null @@ -1,240 +0,0 @@ -/** - * The `timer` module exposes a global API for scheduling functions to - * be called at some future period of time. Because the timer functions are - * globals, there is no need to call `require('node:timers')` to use the API. - * - * The timer functions within Node.js implement a similar API as the timers API - * provided by Web Browsers but use a different internal implementation that is - * built around the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout). - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/timers.js) - */ -declare module "timers" { - import { Abortable } from "node:events"; - import { - setImmediate as setImmediatePromise, - setInterval as setIntervalPromise, - setTimeout as setTimeoutPromise, - } from "node:timers/promises"; - interface TimerOptions extends Abortable { - /** - * Set to `false` to indicate that the scheduled `Timeout` - * should not require the Node.js event loop to remain active. - * @default true - */ - ref?: boolean | undefined; - } - let setTimeout: typeof global.setTimeout; - let clearTimeout: typeof global.clearTimeout; - let setInterval: typeof global.setInterval; - let clearInterval: typeof global.clearInterval; - let setImmediate: typeof global.setImmediate; - let clearImmediate: typeof global.clearImmediate; - global { - namespace NodeJS { - // compatibility with older typings - interface Timer extends RefCounted { - hasRef(): boolean; - refresh(): this; - [Symbol.toPrimitive](): number; - } - /** - * This object is created internally and is returned from `setImmediate()`. It - * can be passed to `clearImmediate()` in order to cancel the scheduled - * actions. - * - * By default, when an immediate is scheduled, the Node.js event loop will continue - * running as long as the immediate is active. The `Immediate` object returned by `setImmediate()` exports both `immediate.ref()` and `immediate.unref()`functions that can be used to - * control this default behavior. - */ - class Immediate implements RefCounted { - /** - * When called, requests that the Node.js event loop _not_ exit so long as the`Immediate` is active. Calling `immediate.ref()` multiple times will have no - * effect. - * - * By default, all `Immediate` objects are "ref'ed", making it normally unnecessary - * to call `immediate.ref()` unless `immediate.unref()` had been called previously. - * @since v9.7.0 - * @return a reference to `immediate` - */ - ref(): this; - /** - * When called, the active `Immediate` object will not require the Node.js event - * loop to remain active. If there is no other activity keeping the event loop - * running, the process may exit before the `Immediate` object's callback is - * invoked. Calling `immediate.unref()` multiple times will have no effect. - * @since v9.7.0 - * @return a reference to `immediate` - */ - unref(): this; - /** - * If true, the `Immediate` object will keep the Node.js event loop active. - * @since v11.0.0 - */ - hasRef(): boolean; - _onImmediate: Function; // to distinguish it from the Timeout class - /** - * Cancels the immediate. This is similar to calling `clearImmediate()`. - * @since v20.5.0 - */ - [Symbol.dispose](): void; - } - /** - * This object is created internally and is returned from `setTimeout()` and `setInterval()`. It can be passed to either `clearTimeout()` or `clearInterval()` in order to cancel the - * scheduled actions. - * - * By default, when a timer is scheduled using either `setTimeout()` or `setInterval()`, the Node.js event loop will continue running as long as the - * timer is active. Each of the `Timeout` objects returned by these functions - * export both `timeout.ref()` and `timeout.unref()` functions that can be used to - * control this default behavior. - */ - class Timeout implements Timer { - /** - * When called, requests that the Node.js event loop _not_ exit so long as the`Timeout` is active. Calling `timeout.ref()` multiple times will have no effect. - * - * By default, all `Timeout` objects are "ref'ed", making it normally unnecessary - * to call `timeout.ref()` unless `timeout.unref()` had been called previously. - * @since v0.9.1 - * @return a reference to `timeout` - */ - ref(): this; - /** - * When called, the active `Timeout` object will not require the Node.js event loop - * to remain active. If there is no other activity keeping the event loop running, - * the process may exit before the `Timeout` object's callback is invoked. Calling`timeout.unref()` multiple times will have no effect. - * @since v0.9.1 - * @return a reference to `timeout` - */ - unref(): this; - /** - * If true, the `Timeout` object will keep the Node.js event loop active. - * @since v11.0.0 - */ - hasRef(): boolean; - /** - * Sets the timer's start time to the current time, and reschedules the timer to - * call its callback at the previously specified duration adjusted to the current - * time. This is useful for refreshing a timer without allocating a new - * JavaScript object. - * - * Using this on a timer that has already called its callback will reactivate the - * timer. - * @since v10.2.0 - * @return a reference to `timeout` - */ - refresh(): this; - [Symbol.toPrimitive](): number; - /** - * Cancels the timeout. - * @since v20.5.0 - */ - [Symbol.dispose](): void; - } - } - /** - * Schedules execution of a one-time `callback` after `delay` milliseconds. - * - * The `callback` will likely not be invoked in precisely `delay` milliseconds. - * Node.js makes no guarantees about the exact timing of when callbacks will fire, - * nor of their ordering. The callback will be called as close as possible to the - * time specified. - * - * When `delay` is larger than `2147483647` or less than `1`, the `delay`will be set to `1`. Non-integer delays are truncated to an integer. - * - * If `callback` is not a function, a `TypeError` will be thrown. - * - * This method has a custom variant for promises that is available using `timersPromises.setTimeout()`. - * @since v0.0.1 - * @param callback The function to call when the timer elapses. - * @param [delay=1] The number of milliseconds to wait before calling the `callback`. - * @param args Optional arguments to pass when the `callback` is called. - * @return for use with {@link clearTimeout} - */ - function setTimeout( - callback: (...args: TArgs) => void, - ms?: number, - ...args: TArgs - ): NodeJS.Timeout; - // util.promisify no rest args compability - // eslint-disable-next-line @typescript-eslint/no-invalid-void-type - function setTimeout(callback: (args: void) => void, ms?: number): NodeJS.Timeout; - namespace setTimeout { - const __promisify__: typeof setTimeoutPromise; - } - /** - * Cancels a `Timeout` object created by `setTimeout()`. - * @since v0.0.1 - * @param timeout A `Timeout` object as returned by {@link setTimeout} or the `primitive` of the `Timeout` object as a string or a number. - */ - function clearTimeout(timeoutId: NodeJS.Timeout | string | number | undefined): void; - /** - * Schedules repeated execution of `callback` every `delay` milliseconds. - * - * When `delay` is larger than `2147483647` or less than `1`, the `delay` will be - * set to `1`. Non-integer delays are truncated to an integer. - * - * If `callback` is not a function, a `TypeError` will be thrown. - * - * This method has a custom variant for promises that is available using `timersPromises.setInterval()`. - * @since v0.0.1 - * @param callback The function to call when the timer elapses. - * @param [delay=1] The number of milliseconds to wait before calling the `callback`. - * @param args Optional arguments to pass when the `callback` is called. - * @return for use with {@link clearInterval} - */ - function setInterval( - callback: (...args: TArgs) => void, - ms?: number, - ...args: TArgs - ): NodeJS.Timeout; - // util.promisify no rest args compability - // eslint-disable-next-line @typescript-eslint/no-invalid-void-type - function setInterval(callback: (args: void) => void, ms?: number): NodeJS.Timeout; - namespace setInterval { - const __promisify__: typeof setIntervalPromise; - } - /** - * Cancels a `Timeout` object created by `setInterval()`. - * @since v0.0.1 - * @param timeout A `Timeout` object as returned by {@link setInterval} or the `primitive` of the `Timeout` object as a string or a number. - */ - function clearInterval(intervalId: NodeJS.Timeout | string | number | undefined): void; - /** - * Schedules the "immediate" execution of the `callback` after I/O events' - * callbacks. - * - * When multiple calls to `setImmediate()` are made, the `callback` functions are - * queued for execution in the order in which they are created. The entire callback - * queue is processed every event loop iteration. If an immediate timer is queued - * from inside an executing callback, that timer will not be triggered until the - * next event loop iteration. - * - * If `callback` is not a function, a `TypeError` will be thrown. - * - * This method has a custom variant for promises that is available using `timersPromises.setImmediate()`. - * @since v0.9.1 - * @param callback The function to call at the end of this turn of the Node.js `Event Loop` - * @param args Optional arguments to pass when the `callback` is called. - * @return for use with {@link clearImmediate} - */ - function setImmediate( - callback: (...args: TArgs) => void, - ...args: TArgs - ): NodeJS.Immediate; - // util.promisify no rest args compability - // eslint-disable-next-line @typescript-eslint/no-invalid-void-type - function setImmediate(callback: (args: void) => void): NodeJS.Immediate; - namespace setImmediate { - const __promisify__: typeof setImmediatePromise; - } - /** - * Cancels an `Immediate` object created by `setImmediate()`. - * @since v0.9.1 - * @param immediate An `Immediate` object as returned by {@link setImmediate}. - */ - function clearImmediate(immediateId: NodeJS.Immediate | undefined): void; - function queueMicrotask(callback: () => void): void; - } -} -declare module "node:timers" { - export * from "timers"; -} diff --git a/node_modules/@types/node/ts4.8/timers/promises.d.ts b/node_modules/@types/node/ts4.8/timers/promises.d.ts deleted file mode 100644 index 5a54dc772dcbdb9974966bc3c5072a3e8636c0d4..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/timers/promises.d.ts +++ /dev/null @@ -1,93 +0,0 @@ -/** - * The `timers/promises` API provides an alternative set of timer functions - * that return `Promise` objects. The API is accessible via`require('node:timers/promises')`. - * - * ```js - * import { - * setTimeout, - * setImmediate, - * setInterval, - * } from 'timers/promises'; - * ``` - * @since v15.0.0 - */ -declare module "timers/promises" { - import { TimerOptions } from "node:timers"; - /** - * ```js - * import { - * setTimeout, - * } from 'timers/promises'; - * - * const res = await setTimeout(100, 'result'); - * - * console.log(res); // Prints 'result' - * ``` - * @since v15.0.0 - * @param [delay=1] The number of milliseconds to wait before fulfilling the promise. - * @param value A value with which the promise is fulfilled. - */ - function setTimeout(delay?: number, value?: T, options?: TimerOptions): Promise; - /** - * ```js - * import { - * setImmediate, - * } from 'timers/promises'; - * - * const res = await setImmediate('result'); - * - * console.log(res); // Prints 'result' - * ``` - * @since v15.0.0 - * @param value A value with which the promise is fulfilled. - */ - function setImmediate(value?: T, options?: TimerOptions): Promise; - /** - * Returns an async iterator that generates values in an interval of `delay` ms. - * If `ref` is `true`, you need to call `next()` of async iterator explicitly - * or implicitly to keep the event loop alive. - * - * ```js - * import { - * setInterval, - * } from 'timers/promises'; - * - * const interval = 100; - * for await (const startTime of setInterval(interval, Date.now())) { - * const now = Date.now(); - * console.log(now); - * if ((now - startTime) > 1000) - * break; - * } - * console.log(Date.now()); - * ``` - * @since v15.9.0 - */ - function setInterval(delay?: number, value?: T, options?: TimerOptions): AsyncIterable; - interface Scheduler { - /** - * ```js - * import { scheduler } from 'node:timers/promises'; - * - * await scheduler.wait(1000); // Wait one second before continuing - * ``` - * An experimental API defined by the Scheduling APIs draft specification being developed as a standard Web Platform API. - * Calling timersPromises.scheduler.wait(delay, options) is roughly equivalent to calling timersPromises.setTimeout(delay, undefined, options) except that the ref option is not supported. - * @since v16.14.0 - * @experimental - * @param [delay=1] The number of milliseconds to wait before fulfilling the promise. - */ - wait: (delay?: number, options?: TimerOptions) => Promise; - /** - * An experimental API defined by the Scheduling APIs draft specification being developed as a standard Web Platform API. - * Calling timersPromises.scheduler.yield() is equivalent to calling timersPromises.setImmediate() with no arguments. - * @since v16.14.0 - * @experimental - */ - yield: () => Promise; - } - const scheduler: Scheduler; -} -declare module "node:timers/promises" { - export * from "timers/promises"; -} diff --git a/node_modules/@types/node/ts4.8/tls.d.ts b/node_modules/@types/node/ts4.8/tls.d.ts deleted file mode 100644 index b289e841c3ce3e1e60b02eb607db1f3978358a83..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/tls.d.ts +++ /dev/null @@ -1,1210 +0,0 @@ -/** - * The `node:tls` module provides an implementation of the Transport Layer Security - * (TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL. - * The module can be accessed using: - * - * ```js - * const tls = require('node:tls'); - * ``` - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/tls.js) - */ -declare module "tls" { - import { X509Certificate } from "node:crypto"; - import * as net from "node:net"; - import * as stream from "stream"; - const CLIENT_RENEG_LIMIT: number; - const CLIENT_RENEG_WINDOW: number; - interface Certificate { - /** - * Country code. - */ - C: string; - /** - * Street. - */ - ST: string; - /** - * Locality. - */ - L: string; - /** - * Organization. - */ - O: string; - /** - * Organizational unit. - */ - OU: string; - /** - * Common name. - */ - CN: string; - } - interface PeerCertificate { - /** - * `true` if a Certificate Authority (CA), `false` otherwise. - * @since v18.13.0 - */ - ca: boolean; - /** - * The DER encoded X.509 certificate data. - */ - raw: Buffer; - /** - * The certificate subject. - */ - subject: Certificate; - /** - * The certificate issuer, described in the same terms as the `subject`. - */ - issuer: Certificate; - /** - * The date-time the certificate is valid from. - */ - valid_from: string; - /** - * The date-time the certificate is valid to. - */ - valid_to: string; - /** - * The certificate serial number, as a hex string. - */ - serialNumber: string; - /** - * The SHA-1 digest of the DER encoded certificate. - * It is returned as a `:` separated hexadecimal string. - */ - fingerprint: string; - /** - * The SHA-256 digest of the DER encoded certificate. - * It is returned as a `:` separated hexadecimal string. - */ - fingerprint256: string; - /** - * The SHA-512 digest of the DER encoded certificate. - * It is returned as a `:` separated hexadecimal string. - */ - fingerprint512: string; - /** - * The extended key usage, a set of OIDs. - */ - ext_key_usage?: string[]; - /** - * A string containing concatenated names for the subject, - * an alternative to the `subject` names. - */ - subjectaltname?: string; - /** - * An array describing the AuthorityInfoAccess, used with OCSP. - */ - infoAccess?: NodeJS.Dict; - /** - * For RSA keys: The RSA bit size. - * - * For EC keys: The key size in bits. - */ - bits?: number; - /** - * The RSA exponent, as a string in hexadecimal number notation. - */ - exponent?: string; - /** - * The RSA modulus, as a hexadecimal string. - */ - modulus?: string; - /** - * The public key. - */ - pubkey?: Buffer; - /** - * The ASN.1 name of the OID of the elliptic curve. - * Well-known curves are identified by an OID. - * While it is unusual, it is possible that the curve - * is identified by its mathematical properties, - * in which case it will not have an OID. - */ - asn1Curve?: string; - /** - * The NIST name for the elliptic curve,if it has one - * (not all well-known curves have been assigned names by NIST). - */ - nistCurve?: string; - } - interface DetailedPeerCertificate extends PeerCertificate { - /** - * The issuer certificate object. - * For self-signed certificates, this may be a circular reference. - */ - issuerCertificate: DetailedPeerCertificate; - } - interface CipherNameAndProtocol { - /** - * The cipher name. - */ - name: string; - /** - * SSL/TLS protocol version. - */ - version: string; - /** - * IETF name for the cipher suite. - */ - standardName: string; - } - interface EphemeralKeyInfo { - /** - * The supported types are 'DH' and 'ECDH'. - */ - type: string; - /** - * The name property is available only when type is 'ECDH'. - */ - name?: string | undefined; - /** - * The size of parameter of an ephemeral key exchange. - */ - size: number; - } - interface KeyObject { - /** - * Private keys in PEM format. - */ - pem: string | Buffer; - /** - * Optional passphrase. - */ - passphrase?: string | undefined; - } - interface PxfObject { - /** - * PFX or PKCS12 encoded private key and certificate chain. - */ - buf: string | Buffer; - /** - * Optional passphrase. - */ - passphrase?: string | undefined; - } - interface TLSSocketOptions extends SecureContextOptions, CommonConnectionOptions { - /** - * If true the TLS socket will be instantiated in server-mode. - * Defaults to false. - */ - isServer?: boolean | undefined; - /** - * An optional net.Server instance. - */ - server?: net.Server | undefined; - /** - * An optional Buffer instance containing a TLS session. - */ - session?: Buffer | undefined; - /** - * If true, specifies that the OCSP status request extension will be - * added to the client hello and an 'OCSPResponse' event will be - * emitted on the socket before establishing a secure communication - */ - requestOCSP?: boolean | undefined; - } - /** - * Performs transparent encryption of written data and all required TLS - * negotiation. - * - * Instances of `tls.TLSSocket` implement the duplex `Stream` interface. - * - * Methods that return TLS connection metadata (e.g.{@link TLSSocket.getPeerCertificate}) will only return data while the - * connection is open. - * @since v0.11.4 - */ - class TLSSocket extends net.Socket { - /** - * Construct a new tls.TLSSocket object from an existing TCP socket. - */ - constructor(socket: net.Socket, options?: TLSSocketOptions); - /** - * This property is `true` if the peer certificate was signed by one of the CAs - * specified when creating the `tls.TLSSocket` instance, otherwise `false`. - * @since v0.11.4 - */ - authorized: boolean; - /** - * Returns the reason why the peer's certificate was not been verified. This - * property is set only when `tlsSocket.authorized === false`. - * @since v0.11.4 - */ - authorizationError: Error; - /** - * Always returns `true`. This may be used to distinguish TLS sockets from regular`net.Socket` instances. - * @since v0.11.4 - */ - encrypted: true; - /** - * String containing the selected ALPN protocol. - * Before a handshake has completed, this value is always null. - * When a handshake is completed but not ALPN protocol was selected, tlsSocket.alpnProtocol equals false. - */ - alpnProtocol: string | false | null; - /** - * Returns an object representing the local certificate. The returned object has - * some properties corresponding to the fields of the certificate. - * - * See {@link TLSSocket.getPeerCertificate} for an example of the certificate - * structure. - * - * If there is no local certificate, an empty object will be returned. If the - * socket has been destroyed, `null` will be returned. - * @since v11.2.0 - */ - getCertificate(): PeerCertificate | object | null; - /** - * Returns an object containing information on the negotiated cipher suite. - * - * For example, a TLSv1.2 protocol with AES256-SHA cipher: - * - * ```json - * { - * "name": "AES256-SHA", - * "standardName": "TLS_RSA_WITH_AES_256_CBC_SHA", - * "version": "SSLv3" - * } - * ``` - * - * See [SSL\_CIPHER\_get\_name](https://www.openssl.org/docs/man1.1.1/man3/SSL_CIPHER_get_name.html) for more information. - * @since v0.11.4 - */ - getCipher(): CipherNameAndProtocol; - /** - * Returns an object representing the type, name, and size of parameter of - * an ephemeral key exchange in `perfect forward secrecy` on a client - * connection. It returns an empty object when the key exchange is not - * ephemeral. As this is only supported on a client socket; `null` is returned - * if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The`name` property is available only when type is `'ECDH'`. - * - * For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`. - * @since v5.0.0 - */ - getEphemeralKeyInfo(): EphemeralKeyInfo | object | null; - /** - * As the `Finished` messages are message digests of the complete handshake - * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can - * be used for external authentication procedures when the authentication - * provided by SSL/TLS is not desired or is not enough. - * - * Corresponds to the `SSL_get_finished` routine in OpenSSL and may be used - * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). - * @since v9.9.0 - * @return The latest `Finished` message that has been sent to the socket as part of a SSL/TLS handshake, or `undefined` if no `Finished` message has been sent yet. - */ - getFinished(): Buffer | undefined; - /** - * Returns an object representing the peer's certificate. If the peer does not - * provide a certificate, an empty object will be returned. If the socket has been - * destroyed, `null` will be returned. - * - * If the full certificate chain was requested, each certificate will include an`issuerCertificate` property containing an object representing its issuer's - * certificate. - * @since v0.11.4 - * @param detailed Include the full certificate chain if `true`, otherwise include just the peer's certificate. - * @return A certificate object. - */ - getPeerCertificate(detailed: true): DetailedPeerCertificate; - getPeerCertificate(detailed?: false): PeerCertificate; - getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; - /** - * As the `Finished` messages are message digests of the complete handshake - * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can - * be used for external authentication procedures when the authentication - * provided by SSL/TLS is not desired or is not enough. - * - * Corresponds to the `SSL_get_peer_finished` routine in OpenSSL and may be used - * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). - * @since v9.9.0 - * @return The latest `Finished` message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or `undefined` if there is no `Finished` message so - * far. - */ - getPeerFinished(): Buffer | undefined; - /** - * Returns a string containing the negotiated SSL/TLS protocol version of the - * current connection. The value `'unknown'` will be returned for connected - * sockets that have not completed the handshaking process. The value `null` will - * be returned for server sockets or disconnected client sockets. - * - * Protocol versions are: - * - * * `'SSLv3'` - * * `'TLSv1'` - * * `'TLSv1.1'` - * * `'TLSv1.2'` - * * `'TLSv1.3'` - * - * See the OpenSSL [`SSL_get_version`](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html) documentation for more information. - * @since v5.7.0 - */ - getProtocol(): string | null; - /** - * Returns the TLS session data or `undefined` if no session was - * negotiated. On the client, the data can be provided to the `session` option of {@link connect} to resume the connection. On the server, it may be useful - * for debugging. - * - * See `Session Resumption` for more information. - * - * Note: `getSession()` works only for TLSv1.2 and below. For TLSv1.3, applications - * must use the `'session'` event (it also works for TLSv1.2 and below). - * @since v0.11.4 - */ - getSession(): Buffer | undefined; - /** - * See [SSL\_get\_shared\_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html) for more information. - * @since v12.11.0 - * @return List of signature algorithms shared between the server and the client in the order of decreasing preference. - */ - getSharedSigalgs(): string[]; - /** - * For a client, returns the TLS session ticket if one is available, or`undefined`. For a server, always returns `undefined`. - * - * It may be useful for debugging. - * - * See `Session Resumption` for more information. - * @since v0.11.4 - */ - getTLSTicket(): Buffer | undefined; - /** - * See `Session Resumption` for more information. - * @since v0.5.6 - * @return `true` if the session was reused, `false` otherwise. - */ - isSessionReused(): boolean; - /** - * The `tlsSocket.renegotiate()` method initiates a TLS renegotiation process. - * Upon completion, the `callback` function will be passed a single argument - * that is either an `Error` (if the request failed) or `null`. - * - * This method can be used to request a peer's certificate after the secure - * connection has been established. - * - * When running as the server, the socket will be destroyed with an error after`handshakeTimeout` timeout. - * - * For TLSv1.3, renegotiation cannot be initiated, it is not supported by the - * protocol. - * @since v0.11.8 - * @param callback If `renegotiate()` returned `true`, callback is attached once to the `'secure'` event. If `renegotiate()` returned `false`, `callback` will be called in the next tick with - * an error, unless the `tlsSocket` has been destroyed, in which case `callback` will not be called at all. - * @return `true` if renegotiation was initiated, `false` otherwise. - */ - renegotiate( - options: { - rejectUnauthorized?: boolean | undefined; - requestCert?: boolean | undefined; - }, - callback: (err: Error | null) => void, - ): undefined | boolean; - /** - * The `tlsSocket.setMaxSendFragment()` method sets the maximum TLS fragment size. - * Returns `true` if setting the limit succeeded; `false` otherwise. - * - * Smaller fragment sizes decrease the buffering latency on the client: larger - * fragments are buffered by the TLS layer until the entire fragment is received - * and its integrity is verified; large fragments can span multiple roundtrips - * and their processing can be delayed due to packet loss or reordering. However, - * smaller fragments add extra TLS framing bytes and CPU overhead, which may - * decrease overall server throughput. - * @since v0.11.11 - * @param [size=16384] The maximum TLS fragment size. The maximum value is `16384`. - */ - setMaxSendFragment(size: number): boolean; - /** - * Disables TLS renegotiation for this `TLSSocket` instance. Once called, attempts - * to renegotiate will trigger an `'error'` event on the `TLSSocket`. - * @since v8.4.0 - */ - disableRenegotiation(): void; - /** - * When enabled, TLS packet trace information is written to `stderr`. This can be - * used to debug TLS connection problems. - * - * The format of the output is identical to the output of`openssl s_client -trace` or `openssl s_server -trace`. While it is produced by - * OpenSSL's `SSL_trace()` function, the format is undocumented, can change - * without notice, and should not be relied on. - * @since v12.2.0 - */ - enableTrace(): void; - /** - * Returns the peer certificate as an `X509Certificate` object. - * - * If there is no peer certificate, or the socket has been destroyed,`undefined` will be returned. - * @since v15.9.0 - */ - getPeerX509Certificate(): X509Certificate | undefined; - /** - * Returns the local certificate as an `X509Certificate` object. - * - * If there is no local certificate, or the socket has been destroyed,`undefined` will be returned. - * @since v15.9.0 - */ - getX509Certificate(): X509Certificate | undefined; - /** - * Keying material is used for validations to prevent different kind of attacks in - * network protocols, for example in the specifications of IEEE 802.1X. - * - * Example - * - * ```js - * const keyingMaterial = tlsSocket.exportKeyingMaterial( - * 128, - * 'client finished'); - * - * /* - * Example return value of keyingMaterial: - * - * - * ``` - * - * See the OpenSSL [`SSL_export_keying_material`](https://www.openssl.org/docs/man1.1.1/man3/SSL_export_keying_material.html) documentation for more - * information. - * @since v13.10.0, v12.17.0 - * @param length number of bytes to retrieve from keying material - * @param label an application specific label, typically this will be a value from the [IANA Exporter Label - * Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels). - * @param context Optionally provide a context. - * @return requested bytes of the keying material - */ - exportKeyingMaterial(length: number, label: string, context: Buffer): Buffer; - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; - addListener(event: "secureConnect", listener: () => void): this; - addListener(event: "session", listener: (session: Buffer) => void): this; - addListener(event: "keylog", listener: (line: Buffer) => void): this; - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "OCSPResponse", response: Buffer): boolean; - emit(event: "secureConnect"): boolean; - emit(event: "session", session: Buffer): boolean; - emit(event: "keylog", line: Buffer): boolean; - on(event: string, listener: (...args: any[]) => void): this; - on(event: "OCSPResponse", listener: (response: Buffer) => void): this; - on(event: "secureConnect", listener: () => void): this; - on(event: "session", listener: (session: Buffer) => void): this; - on(event: "keylog", listener: (line: Buffer) => void): this; - once(event: string, listener: (...args: any[]) => void): this; - once(event: "OCSPResponse", listener: (response: Buffer) => void): this; - once(event: "secureConnect", listener: () => void): this; - once(event: "session", listener: (session: Buffer) => void): this; - once(event: "keylog", listener: (line: Buffer) => void): this; - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; - prependListener(event: "secureConnect", listener: () => void): this; - prependListener(event: "session", listener: (session: Buffer) => void): this; - prependListener(event: "keylog", listener: (line: Buffer) => void): this; - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; - prependOnceListener(event: "secureConnect", listener: () => void): this; - prependOnceListener(event: "session", listener: (session: Buffer) => void): this; - prependOnceListener(event: "keylog", listener: (line: Buffer) => void): this; - } - interface CommonConnectionOptions { - /** - * An optional TLS context object from tls.createSecureContext() - */ - secureContext?: SecureContext | undefined; - /** - * When enabled, TLS packet trace information is written to `stderr`. This can be - * used to debug TLS connection problems. - * @default false - */ - enableTrace?: boolean | undefined; - /** - * If true the server will request a certificate from clients that - * connect and attempt to verify that certificate. Defaults to - * false. - */ - requestCert?: boolean | undefined; - /** - * An array of strings or a Buffer naming possible ALPN protocols. - * (Protocols should be ordered by their priority.) - */ - ALPNProtocols?: string[] | Uint8Array[] | Uint8Array | undefined; - /** - * SNICallback(servername, cb) A function that will be - * called if the client supports SNI TLS extension. Two arguments - * will be passed when called: servername and cb. SNICallback should - * invoke cb(null, ctx), where ctx is a SecureContext instance. - * (tls.createSecureContext(...) can be used to get a proper - * SecureContext.) If SNICallback wasn't provided the default callback - * with high-level API will be used (see below). - */ - SNICallback?: ((servername: string, cb: (err: Error | null, ctx?: SecureContext) => void) => void) | undefined; - /** - * If true the server will reject any connection which is not - * authorized with the list of supplied CAs. This option only has an - * effect if requestCert is true. - * @default true - */ - rejectUnauthorized?: boolean | undefined; - } - interface TlsOptions extends SecureContextOptions, CommonConnectionOptions, net.ServerOpts { - /** - * Abort the connection if the SSL/TLS handshake does not finish in the - * specified number of milliseconds. A 'tlsClientError' is emitted on - * the tls.Server object whenever a handshake times out. Default: - * 120000 (120 seconds). - */ - handshakeTimeout?: number | undefined; - /** - * The number of seconds after which a TLS session created by the - * server will no longer be resumable. See Session Resumption for more - * information. Default: 300. - */ - sessionTimeout?: number | undefined; - /** - * 48-bytes of cryptographically strong pseudo-random data. - */ - ticketKeys?: Buffer | undefined; - /** - * @param socket - * @param identity identity parameter sent from the client. - * @return pre-shared key that must either be - * a buffer or `null` to stop the negotiation process. Returned PSK must be - * compatible with the selected cipher's digest. - * - * When negotiating TLS-PSK (pre-shared keys), this function is called - * with the identity provided by the client. - * If the return value is `null` the negotiation process will stop and an - * "unknown_psk_identity" alert message will be sent to the other party. - * If the server wishes to hide the fact that the PSK identity was not known, - * the callback must provide some random data as `psk` to make the connection - * fail with "decrypt_error" before negotiation is finished. - * PSK ciphers are disabled by default, and using TLS-PSK thus - * requires explicitly specifying a cipher suite with the `ciphers` option. - * More information can be found in the RFC 4279. - */ - pskCallback?(socket: TLSSocket, identity: string): DataView | NodeJS.TypedArray | null; - /** - * hint to send to a client to help - * with selecting the identity during TLS-PSK negotiation. Will be ignored - * in TLS 1.3. Upon failing to set pskIdentityHint `tlsClientError` will be - * emitted with `ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED` code. - */ - pskIdentityHint?: string | undefined; - } - interface PSKCallbackNegotation { - psk: DataView | NodeJS.TypedArray; - identity: string; - } - interface ConnectionOptions extends SecureContextOptions, CommonConnectionOptions { - host?: string | undefined; - port?: number | undefined; - path?: string | undefined; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. - socket?: stream.Duplex | undefined; // Establish secure connection on a given socket rather than creating a new socket - checkServerIdentity?: typeof checkServerIdentity | undefined; - servername?: string | undefined; // SNI TLS Extension - session?: Buffer | undefined; - minDHSize?: number | undefined; - lookup?: net.LookupFunction | undefined; - timeout?: number | undefined; - /** - * When negotiating TLS-PSK (pre-shared keys), this function is called - * with optional identity `hint` provided by the server or `null` - * in case of TLS 1.3 where `hint` was removed. - * It will be necessary to provide a custom `tls.checkServerIdentity()` - * for the connection as the default one will try to check hostname/IP - * of the server against the certificate but that's not applicable for PSK - * because there won't be a certificate present. - * More information can be found in the RFC 4279. - * - * @param hint message sent from the server to help client - * decide which identity to use during negotiation. - * Always `null` if TLS 1.3 is used. - * @returns Return `null` to stop the negotiation process. `psk` must be - * compatible with the selected cipher's digest. - * `identity` must use UTF-8 encoding. - */ - pskCallback?(hint: string | null): PSKCallbackNegotation | null; - } - /** - * Accepts encrypted connections using TLS or SSL. - * @since v0.3.2 - */ - class Server extends net.Server { - constructor(secureConnectionListener?: (socket: TLSSocket) => void); - constructor(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void); - /** - * The `server.addContext()` method adds a secure context that will be used if - * the client request's SNI name matches the supplied `hostname` (or wildcard). - * - * When there are multiple matching contexts, the most recently added one is - * used. - * @since v0.5.3 - * @param hostname A SNI host name or wildcard (e.g. `'*'`) - * @param context An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc), or a TLS context object created - * with {@link createSecureContext} itself. - */ - addContext(hostname: string, context: SecureContextOptions): void; - /** - * Returns the session ticket keys. - * - * See `Session Resumption` for more information. - * @since v3.0.0 - * @return A 48-byte buffer containing the session ticket keys. - */ - getTicketKeys(): Buffer; - /** - * The `server.setSecureContext()` method replaces the secure context of an - * existing server. Existing connections to the server are not interrupted. - * @since v11.0.0 - * @param options An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc). - */ - setSecureContext(options: SecureContextOptions): void; - /** - * Sets the session ticket keys. - * - * Changes to the ticket keys are effective only for future server connections. - * Existing or currently pending server connections will use the previous keys. - * - * See `Session Resumption` for more information. - * @since v3.0.0 - * @param keys A 48-byte buffer containing the session ticket keys. - */ - setTicketKeys(keys: Buffer): void; - /** - * events.EventEmitter - * 1. tlsClientError - * 2. newSession - * 3. OCSPRequest - * 4. resumeSession - * 5. secureConnection - * 6. keylog - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; - addListener( - event: "newSession", - listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, - ): this; - addListener( - event: "OCSPRequest", - listener: ( - certificate: Buffer, - issuer: Buffer, - callback: (err: Error | null, resp: Buffer) => void, - ) => void, - ): this; - addListener( - event: "resumeSession", - listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, - ): this; - addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - addListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; - emit(event: "newSession", sessionId: Buffer, sessionData: Buffer, callback: () => void): boolean; - emit( - event: "OCSPRequest", - certificate: Buffer, - issuer: Buffer, - callback: (err: Error | null, resp: Buffer) => void, - ): boolean; - emit( - event: "resumeSession", - sessionId: Buffer, - callback: (err: Error | null, sessionData: Buffer | null) => void, - ): boolean; - emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; - emit(event: "keylog", line: Buffer, tlsSocket: TLSSocket): boolean; - on(event: string, listener: (...args: any[]) => void): this; - on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; - on(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void): this; - on( - event: "OCSPRequest", - listener: ( - certificate: Buffer, - issuer: Buffer, - callback: (err: Error | null, resp: Buffer) => void, - ) => void, - ): this; - on( - event: "resumeSession", - listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, - ): this; - on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - on(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; - once(event: string, listener: (...args: any[]) => void): this; - once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; - once( - event: "newSession", - listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, - ): this; - once( - event: "OCSPRequest", - listener: ( - certificate: Buffer, - issuer: Buffer, - callback: (err: Error | null, resp: Buffer) => void, - ) => void, - ): this; - once( - event: "resumeSession", - listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, - ): this; - once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - once(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; - prependListener( - event: "newSession", - listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, - ): this; - prependListener( - event: "OCSPRequest", - listener: ( - certificate: Buffer, - issuer: Buffer, - callback: (err: Error | null, resp: Buffer) => void, - ) => void, - ): this; - prependListener( - event: "resumeSession", - listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, - ): this; - prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - prependListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; - prependOnceListener( - event: "newSession", - listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, - ): this; - prependOnceListener( - event: "OCSPRequest", - listener: ( - certificate: Buffer, - issuer: Buffer, - callback: (err: Error | null, resp: Buffer) => void, - ) => void, - ): this; - prependOnceListener( - event: "resumeSession", - listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, - ): this; - prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - prependOnceListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; - } - /** - * @deprecated since v0.11.3 Use `tls.TLSSocket` instead. - */ - interface SecurePair { - encrypted: TLSSocket; - cleartext: TLSSocket; - } - type SecureVersion = "TLSv1.3" | "TLSv1.2" | "TLSv1.1" | "TLSv1"; - interface SecureContextOptions { - /** - * If set, this will be called when a client opens a connection using the ALPN extension. - * One argument will be passed to the callback: an object containing `servername` and `protocols` fields, - * respectively containing the server name from the SNI extension (if any) and an array of - * ALPN protocol name strings. The callback must return either one of the strings listed in `protocols`, - * which will be returned to the client as the selected ALPN protocol, or `undefined`, - * to reject the connection with a fatal alert. If a string is returned that does not match one of - * the client's ALPN protocols, an error will be thrown. - * This option cannot be used with the `ALPNProtocols` option, and setting both options will throw an error. - */ - ALPNCallback?: ((arg: { servername: string; protocols: string[] }) => string | undefined) | undefined; - /** - * Optionally override the trusted CA certificates. Default is to trust - * the well-known CAs curated by Mozilla. Mozilla's CAs are completely - * replaced when CAs are explicitly specified using this option. - */ - ca?: string | Buffer | Array | undefined; - /** - * Cert chains in PEM format. One cert chain should be provided per - * private key. Each cert chain should consist of the PEM formatted - * certificate for a provided private key, followed by the PEM - * formatted intermediate certificates (if any), in order, and not - * including the root CA (the root CA must be pre-known to the peer, - * see ca). When providing multiple cert chains, they do not have to - * be in the same order as their private keys in key. If the - * intermediate certificates are not provided, the peer will not be - * able to validate the certificate, and the handshake will fail. - */ - cert?: string | Buffer | Array | undefined; - /** - * Colon-separated list of supported signature algorithms. The list - * can contain digest algorithms (SHA256, MD5 etc.), public key - * algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g - * 'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512). - */ - sigalgs?: string | undefined; - /** - * Cipher suite specification, replacing the default. For more - * information, see modifying the default cipher suite. Permitted - * ciphers can be obtained via tls.getCiphers(). Cipher names must be - * uppercased in order for OpenSSL to accept them. - */ - ciphers?: string | undefined; - /** - * Name of an OpenSSL engine which can provide the client certificate. - */ - clientCertEngine?: string | undefined; - /** - * PEM formatted CRLs (Certificate Revocation Lists). - */ - crl?: string | Buffer | Array | undefined; - /** - * `'auto'` or custom Diffie-Hellman parameters, required for non-ECDHE perfect forward secrecy. - * If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available. - * ECDHE-based perfect forward secrecy will still be available. - */ - dhparam?: string | Buffer | undefined; - /** - * A string describing a named curve or a colon separated list of curve - * NIDs or names, for example P-521:P-384:P-256, to use for ECDH key - * agreement. Set to auto to select the curve automatically. Use - * crypto.getCurves() to obtain a list of available curve names. On - * recent releases, openssl ecparam -list_curves will also display the - * name and description of each available elliptic curve. Default: - * tls.DEFAULT_ECDH_CURVE. - */ - ecdhCurve?: string | undefined; - /** - * Attempt to use the server's cipher suite preferences instead of the - * client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be - * set in secureOptions - */ - honorCipherOrder?: boolean | undefined; - /** - * Private keys in PEM format. PEM allows the option of private keys - * being encrypted. Encrypted keys will be decrypted with - * options.passphrase. Multiple keys using different algorithms can be - * provided either as an array of unencrypted key strings or buffers, - * or an array of objects in the form {pem: [, - * passphrase: ]}. The object form can only occur in an array. - * object.passphrase is optional. Encrypted keys will be decrypted with - * object.passphrase if provided, or options.passphrase if it is not. - */ - key?: string | Buffer | Array | undefined; - /** - * Name of an OpenSSL engine to get private key from. Should be used - * together with privateKeyIdentifier. - */ - privateKeyEngine?: string | undefined; - /** - * Identifier of a private key managed by an OpenSSL engine. Should be - * used together with privateKeyEngine. Should not be set together with - * key, because both options define a private key in different ways. - */ - privateKeyIdentifier?: string | undefined; - /** - * Optionally set the maximum TLS version to allow. One - * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the - * `secureProtocol` option, use one or the other. - * **Default:** `'TLSv1.3'`, unless changed using CLI options. Using - * `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to - * `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used. - */ - maxVersion?: SecureVersion | undefined; - /** - * Optionally set the minimum TLS version to allow. One - * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the - * `secureProtocol` option, use one or the other. It is not recommended to use - * less than TLSv1.2, but it may be required for interoperability. - * **Default:** `'TLSv1.2'`, unless changed using CLI options. Using - * `--tls-v1.0` sets the default to `'TLSv1'`. Using `--tls-v1.1` sets the default to - * `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to - * 'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used. - */ - minVersion?: SecureVersion | undefined; - /** - * Shared passphrase used for a single private key and/or a PFX. - */ - passphrase?: string | undefined; - /** - * PFX or PKCS12 encoded private key and certificate chain. pfx is an - * alternative to providing key and cert individually. PFX is usually - * encrypted, if it is, passphrase will be used to decrypt it. Multiple - * PFX can be provided either as an array of unencrypted PFX buffers, - * or an array of objects in the form {buf: [, - * passphrase: ]}. The object form can only occur in an array. - * object.passphrase is optional. Encrypted PFX will be decrypted with - * object.passphrase if provided, or options.passphrase if it is not. - */ - pfx?: string | Buffer | Array | undefined; - /** - * Optionally affect the OpenSSL protocol behavior, which is not - * usually necessary. This should be used carefully if at all! Value is - * a numeric bitmask of the SSL_OP_* options from OpenSSL Options - */ - secureOptions?: number | undefined; // Value is a numeric bitmask of the `SSL_OP_*` options - /** - * Legacy mechanism to select the TLS protocol version to use, it does - * not support independent control of the minimum and maximum version, - * and does not support limiting the protocol to TLSv1.3. Use - * minVersion and maxVersion instead. The possible values are listed as - * SSL_METHODS, use the function names as strings. For example, use - * 'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow - * any TLS protocol version up to TLSv1.3. It is not recommended to use - * TLS versions less than 1.2, but it may be required for - * interoperability. Default: none, see minVersion. - */ - secureProtocol?: string | undefined; - /** - * Opaque identifier used by servers to ensure session state is not - * shared between applications. Unused by clients. - */ - sessionIdContext?: string | undefined; - /** - * 48-bytes of cryptographically strong pseudo-random data. - * See Session Resumption for more information. - */ - ticketKeys?: Buffer | undefined; - /** - * The number of seconds after which a TLS session created by the - * server will no longer be resumable. See Session Resumption for more - * information. Default: 300. - */ - sessionTimeout?: number | undefined; - } - interface SecureContext { - context: any; - } - /** - * Verifies the certificate `cert` is issued to `hostname`. - * - * Returns [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object, populating it with `reason`, `host`, and `cert` on - * failure. On success, returns [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type). - * - * This function is intended to be used in combination with the`checkServerIdentity` option that can be passed to {@link connect} and as - * such operates on a `certificate object`. For other purposes, consider using `x509.checkHost()` instead. - * - * This function can be overwritten by providing an alternative function as the`options.checkServerIdentity` option that is passed to `tls.connect()`. The - * overwriting function can call `tls.checkServerIdentity()` of course, to augment - * the checks done with additional verification. - * - * This function is only called if the certificate passed all other checks, such as - * being issued by trusted CA (`options.ca`). - * - * Earlier versions of Node.js incorrectly accepted certificates for a given`hostname` if a matching `uniformResourceIdentifier` subject alternative name - * was present (see [CVE-2021-44531](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44531)). Applications that wish to accept`uniformResourceIdentifier` subject alternative names can use - * a custom`options.checkServerIdentity` function that implements the desired behavior. - * @since v0.8.4 - * @param hostname The host name or IP address to verify the certificate against. - * @param cert A `certificate object` representing the peer's certificate. - */ - function checkServerIdentity(hostname: string, cert: PeerCertificate): Error | undefined; - /** - * Creates a new {@link Server}. The `secureConnectionListener`, if provided, is - * automatically set as a listener for the `'secureConnection'` event. - * - * The `ticketKeys` options is automatically shared between `node:cluster` module - * workers. - * - * The following illustrates a simple echo server: - * - * ```js - * const tls = require('node:tls'); - * const fs = require('node:fs'); - * - * const options = { - * key: fs.readFileSync('server-key.pem'), - * cert: fs.readFileSync('server-cert.pem'), - * - * // This is necessary only if using client certificate authentication. - * requestCert: true, - * - * // This is necessary only if the client uses a self-signed certificate. - * ca: [ fs.readFileSync('client-cert.pem') ], - * }; - * - * const server = tls.createServer(options, (socket) => { - * console.log('server connected', - * socket.authorized ? 'authorized' : 'unauthorized'); - * socket.write('welcome!\n'); - * socket.setEncoding('utf8'); - * socket.pipe(socket); - * }); - * server.listen(8000, () => { - * console.log('server bound'); - * }); - * ``` - * - * The server can be tested by connecting to it using the example client from {@link connect}. - * @since v0.3.2 - */ - function createServer(secureConnectionListener?: (socket: TLSSocket) => void): Server; - function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; - /** - * The `callback` function, if specified, will be added as a listener for the `'secureConnect'` event. - * - * `tls.connect()` returns a {@link TLSSocket} object. - * - * Unlike the `https` API, `tls.connect()` does not enable the - * SNI (Server Name Indication) extension by default, which may cause some - * servers to return an incorrect certificate or reject the connection - * altogether. To enable SNI, set the `servername` option in addition - * to `host`. - * - * The following illustrates a client for the echo server example from {@link createServer}: - * - * ```js - * // Assumes an echo server that is listening on port 8000. - * const tls = require('node:tls'); - * const fs = require('node:fs'); - * - * const options = { - * // Necessary only if the server requires client certificate authentication. - * key: fs.readFileSync('client-key.pem'), - * cert: fs.readFileSync('client-cert.pem'), - * - * // Necessary only if the server uses a self-signed certificate. - * ca: [ fs.readFileSync('server-cert.pem') ], - * - * // Necessary only if the server's cert isn't for "localhost". - * checkServerIdentity: () => { return null; }, - * }; - * - * const socket = tls.connect(8000, options, () => { - * console.log('client connected', - * socket.authorized ? 'authorized' : 'unauthorized'); - * process.stdin.pipe(socket); - * process.stdin.resume(); - * }); - * socket.setEncoding('utf8'); - * socket.on('data', (data) => { - * console.log(data); - * }); - * socket.on('end', () => { - * console.log('server ends connection'); - * }); - * ``` - * @since v0.11.3 - */ - function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; - function connect( - port: number, - host?: string, - options?: ConnectionOptions, - secureConnectListener?: () => void, - ): TLSSocket; - function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; - /** - * Creates a new secure pair object with two streams, one of which reads and writes - * the encrypted data and the other of which reads and writes the cleartext data. - * Generally, the encrypted stream is piped to/from an incoming encrypted data - * stream and the cleartext one is used as a replacement for the initial encrypted - * stream. - * - * `tls.createSecurePair()` returns a `tls.SecurePair` object with `cleartext` and`encrypted` stream properties. - * - * Using `cleartext` has the same API as {@link TLSSocket}. - * - * The `tls.createSecurePair()` method is now deprecated in favor of`tls.TLSSocket()`. For example, the code: - * - * ```js - * pair = tls.createSecurePair(// ... ); - * pair.encrypted.pipe(socket); - * socket.pipe(pair.encrypted); - * ``` - * - * can be replaced by: - * - * ```js - * secureSocket = tls.TLSSocket(socket, options); - * ``` - * - * where `secureSocket` has the same API as `pair.cleartext`. - * @since v0.3.2 - * @deprecated Since v0.11.3 - Use {@link TLSSocket} instead. - * @param context A secure context object as returned by `tls.createSecureContext()` - * @param isServer `true` to specify that this TLS connection should be opened as a server. - * @param requestCert `true` to specify whether a server should request a certificate from a connecting client. Only applies when `isServer` is `true`. - * @param rejectUnauthorized If not `false` a server automatically reject clients with invalid certificates. Only applies when `isServer` is `true`. - */ - function createSecurePair( - context?: SecureContext, - isServer?: boolean, - requestCert?: boolean, - rejectUnauthorized?: boolean, - ): SecurePair; - /** - * {@link createServer} sets the default value of the `honorCipherOrder` option - * to `true`, other APIs that create secure contexts leave it unset. - * - * {@link createServer} uses a 128 bit truncated SHA1 hash value generated - * from `process.argv` as the default value of the `sessionIdContext` option, other - * APIs that create secure contexts have no default value. - * - * The `tls.createSecureContext()` method creates a `SecureContext` object. It is - * usable as an argument to several `tls` APIs, such as `server.addContext()`, - * but has no public methods. The {@link Server} constructor and the {@link createServer} method do not support the `secureContext` option. - * - * A key is _required_ for ciphers that use certificates. Either `key` or`pfx` can be used to provide it. - * - * If the `ca` option is not given, then Node.js will default to using [Mozilla's publicly trusted list of - * CAs](https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt). - * - * Custom DHE parameters are discouraged in favor of the new `dhparam: 'auto'`option. When set to `'auto'`, well-known DHE parameters of sufficient strength - * will be selected automatically. Otherwise, if necessary, `openssl dhparam` can - * be used to create custom parameters. The key length must be greater than or - * equal to 1024 bits or else an error will be thrown. Although 1024 bits is - * permissible, use 2048 bits or larger for stronger security. - * @since v0.11.13 - */ - function createSecureContext(options?: SecureContextOptions): SecureContext; - /** - * Returns an array with the names of the supported TLS ciphers. The names are - * lower-case for historical reasons, but must be uppercased to be used in - * the `ciphers` option of {@link createSecureContext}. - * - * Not all supported ciphers are enabled by default. See `Modifying the default TLS cipher suite`. - * - * Cipher names that start with `'tls_'` are for TLSv1.3, all the others are for - * TLSv1.2 and below. - * - * ```js - * console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...] - * ``` - * @since v0.10.2 - */ - function getCiphers(): string[]; - /** - * The default curve name to use for ECDH key agreement in a tls server. - * The default value is 'auto'. See tls.createSecureContext() for further - * information. - */ - let DEFAULT_ECDH_CURVE: string; - /** - * The default value of the maxVersion option of - * tls.createSecureContext(). It can be assigned any of the supported TLS - * protocol versions, 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: - * 'TLSv1.3', unless changed using CLI options. Using --tls-max-v1.2 sets - * the default to 'TLSv1.2'. Using --tls-max-v1.3 sets the default to - * 'TLSv1.3'. If multiple of the options are provided, the highest maximum - * is used. - */ - let DEFAULT_MAX_VERSION: SecureVersion; - /** - * The default value of the minVersion option of tls.createSecureContext(). - * It can be assigned any of the supported TLS protocol versions, - * 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: 'TLSv1.2', unless - * changed using CLI options. Using --tls-min-v1.0 sets the default to - * 'TLSv1'. Using --tls-min-v1.1 sets the default to 'TLSv1.1'. Using - * --tls-min-v1.3 sets the default to 'TLSv1.3'. If multiple of the options - * are provided, the lowest minimum is used. - */ - let DEFAULT_MIN_VERSION: SecureVersion; - /** - * The default value of the ciphers option of tls.createSecureContext(). - * It can be assigned any of the supported OpenSSL ciphers. - * Defaults to the content of crypto.constants.defaultCoreCipherList, unless - * changed using CLI options using --tls-default-ciphers. - */ - let DEFAULT_CIPHERS: string; - /** - * An immutable array of strings representing the root certificates (in PEM - * format) used for verifying peer certificates. This is the default value - * of the ca option to tls.createSecureContext(). - */ - const rootCertificates: readonly string[]; -} -declare module "node:tls" { - export * from "tls"; -} diff --git a/node_modules/@types/node/ts4.8/trace_events.d.ts b/node_modules/@types/node/ts4.8/trace_events.d.ts deleted file mode 100644 index 336135959baba13c54c0d7859445290994236804..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/trace_events.d.ts +++ /dev/null @@ -1,182 +0,0 @@ -/** - * The `node:trace_events` module provides a mechanism to centralize tracing - * information generated by V8, Node.js core, and userspace code. - * - * Tracing can be enabled with the `--trace-event-categories` command-line flag - * or by using the `node:trace_events` module. The `--trace-event-categories` flag - * accepts a list of comma-separated category names. - * - * The available categories are: - * - * * `node`: An empty placeholder. - * * `node.async_hooks`: Enables capture of detailed `async_hooks` trace data. - * The `async_hooks` events have a unique `asyncId` and a special `triggerId` `triggerAsyncId` property. - * * `node.bootstrap`: Enables capture of Node.js bootstrap milestones. - * * `node.console`: Enables capture of `console.time()` and `console.count()`output. - * * `node.threadpoolwork.sync`: Enables capture of trace data for threadpool - * synchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. - * * `node.threadpoolwork.async`: Enables capture of trace data for threadpool - * asynchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. - * * `node.dns.native`: Enables capture of trace data for DNS queries. - * * `node.net.native`: Enables capture of trace data for network. - * * `node.environment`: Enables capture of Node.js Environment milestones. - * * `node.fs.sync`: Enables capture of trace data for file system sync methods. - * * `node.fs_dir.sync`: Enables capture of trace data for file system sync - * directory methods. - * * `node.fs.async`: Enables capture of trace data for file system async methods. - * * `node.fs_dir.async`: Enables capture of trace data for file system async - * directory methods. - * * `node.perf`: Enables capture of `Performance API` measurements. - * * `node.perf.usertiming`: Enables capture of only Performance API User Timing - * measures and marks. - * * `node.perf.timerify`: Enables capture of only Performance API timerify - * measurements. - * * `node.promises.rejections`: Enables capture of trace data tracking the number - * of unhandled Promise rejections and handled-after-rejections. - * * `node.vm.script`: Enables capture of trace data for the `node:vm` module's`runInNewContext()`, `runInContext()`, and `runInThisContext()` methods. - * * `v8`: The `V8` events are GC, compiling, and execution related. - * * `node.http`: Enables capture of trace data for http request / response. - * - * By default the `node`, `node.async_hooks`, and `v8` categories are enabled. - * - * ```bash - * node --trace-event-categories v8,node,node.async_hooks server.js - * ``` - * - * Prior versions of Node.js required the use of the `--trace-events-enabled`flag to enable trace events. This requirement has been removed. However, the`--trace-events-enabled` flag _may_ still be - * used and will enable the`node`, `node.async_hooks`, and `v8` trace event categories by default. - * - * ```bash - * node --trace-events-enabled - * - * # is equivalent to - * - * node --trace-event-categories v8,node,node.async_hooks - * ``` - * - * Alternatively, trace events may be enabled using the `node:trace_events` module: - * - * ```js - * const trace_events = require('node:trace_events'); - * const tracing = trace_events.createTracing({ categories: ['node.perf'] }); - * tracing.enable(); // Enable trace event capture for the 'node.perf' category - * - * // do work - * - * tracing.disable(); // Disable trace event capture for the 'node.perf' category - * ``` - * - * Running Node.js with tracing enabled will produce log files that can be opened - * in the [`chrome://tracing`](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) tab of Chrome. - * - * The logging file is by default called `node_trace.${rotation}.log`, where`${rotation}` is an incrementing log-rotation id. The filepath pattern can - * be specified with `--trace-event-file-pattern` that accepts a template - * string that supports `${rotation}` and `${pid}`: - * - * ```bash - * node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js - * ``` - * - * To guarantee that the log file is properly generated after signal events like`SIGINT`, `SIGTERM`, or `SIGBREAK`, make sure to have the appropriate handlers - * in your code, such as: - * - * ```js - * process.on('SIGINT', function onSigint() { - * console.info('Received SIGINT.'); - * process.exit(130); // Or applicable exit code depending on OS and signal - * }); - * ``` - * - * The tracing system uses the same time source - * as the one used by `process.hrtime()`. - * However the trace-event timestamps are expressed in microseconds, - * unlike `process.hrtime()` which returns nanoseconds. - * - * The features from this module are not available in `Worker` threads. - * @experimental - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/trace_events.js) - */ -declare module "trace_events" { - /** - * The `Tracing` object is used to enable or disable tracing for sets of - * categories. Instances are created using the - * `trace_events.createTracing()` method. - * - * When created, the `Tracing` object is disabled. Calling the - * `tracing.enable()` method adds the categories to the set of enabled trace - * event categories. Calling `tracing.disable()` will remove the categories - * from the set of enabled trace event categories. - */ - interface Tracing { - /** - * A comma-separated list of the trace event categories covered by this - * `Tracing` object. - */ - readonly categories: string; - /** - * Disables this `Tracing` object. - * - * Only trace event categories _not_ covered by other enabled `Tracing` - * objects and _not_ specified by the `--trace-event-categories` flag - * will be disabled. - */ - disable(): void; - /** - * Enables this `Tracing` object for the set of categories covered by - * the `Tracing` object. - */ - enable(): void; - /** - * `true` only if the `Tracing` object has been enabled. - */ - readonly enabled: boolean; - } - interface CreateTracingOptions { - /** - * An array of trace category names. Values included in the array are - * coerced to a string when possible. An error will be thrown if the - * value cannot be coerced. - */ - categories: string[]; - } - /** - * Creates and returns a `Tracing` object for the given set of `categories`. - * - * ```js - * const trace_events = require('node:trace_events'); - * const categories = ['node.perf', 'node.async_hooks']; - * const tracing = trace_events.createTracing({ categories }); - * tracing.enable(); - * // do stuff - * tracing.disable(); - * ``` - * @since v10.0.0 - * @return . - */ - function createTracing(options: CreateTracingOptions): Tracing; - /** - * Returns a comma-separated list of all currently-enabled trace event - * categories. The current set of enabled trace event categories is determined - * by the _union_ of all currently-enabled `Tracing` objects and any categories - * enabled using the `--trace-event-categories` flag. - * - * Given the file `test.js` below, the command`node --trace-event-categories node.perf test.js` will print`'node.async_hooks,node.perf'` to the console. - * - * ```js - * const trace_events = require('node:trace_events'); - * const t1 = trace_events.createTracing({ categories: ['node.async_hooks'] }); - * const t2 = trace_events.createTracing({ categories: ['node.perf'] }); - * const t3 = trace_events.createTracing({ categories: ['v8'] }); - * - * t1.enable(); - * t2.enable(); - * - * console.log(trace_events.getEnabledCategories()); - * ``` - * @since v10.0.0 - */ - function getEnabledCategories(): string | undefined; -} -declare module "node:trace_events" { - export * from "trace_events"; -} diff --git a/node_modules/@types/node/ts4.8/tty.d.ts b/node_modules/@types/node/ts4.8/tty.d.ts deleted file mode 100644 index 1c0dafd3ee4a92312faeae80995c25520d5b9918..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/tty.d.ts +++ /dev/null @@ -1,208 +0,0 @@ -/** - * The `node:tty` module provides the `tty.ReadStream` and `tty.WriteStream`classes. In most cases, it will not be necessary or possible to use this module - * directly. However, it can be accessed using: - * - * ```js - * const tty = require('node:tty'); - * ``` - * - * When Node.js detects that it is being run with a text terminal ("TTY") - * attached, `process.stdin` will, by default, be initialized as an instance of`tty.ReadStream` and both `process.stdout` and `process.stderr` will, by - * default, be instances of `tty.WriteStream`. The preferred method of determining - * whether Node.js is being run within a TTY context is to check that the value of - * the `process.stdout.isTTY` property is `true`: - * - * ```console - * $ node -p -e "Boolean(process.stdout.isTTY)" - * true - * $ node -p -e "Boolean(process.stdout.isTTY)" | cat - * false - * ``` - * - * In most cases, there should be little to no reason for an application to - * manually create instances of the `tty.ReadStream` and `tty.WriteStream`classes. - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/tty.js) - */ -declare module "tty" { - import * as net from "node:net"; - /** - * The `tty.isatty()` method returns `true` if the given `fd` is associated with - * a TTY and `false` if it is not, including whenever `fd` is not a non-negative - * integer. - * @since v0.5.8 - * @param fd A numeric file descriptor - */ - function isatty(fd: number): boolean; - /** - * Represents the readable side of a TTY. In normal circumstances `process.stdin` will be the only `tty.ReadStream` instance in a Node.js - * process and there should be no reason to create additional instances. - * @since v0.5.8 - */ - class ReadStream extends net.Socket { - constructor(fd: number, options?: net.SocketConstructorOpts); - /** - * A `boolean` that is `true` if the TTY is currently configured to operate as a - * raw device. - * - * This flag is always `false` when a process starts, even if the terminal is - * operating in raw mode. Its value will change with subsequent calls to`setRawMode`. - * @since v0.7.7 - */ - isRaw: boolean; - /** - * Allows configuration of `tty.ReadStream` so that it operates as a raw device. - * - * When in raw mode, input is always available character-by-character, not - * including modifiers. Additionally, all special processing of characters by the - * terminal is disabled, including echoing input - * characters. Ctrl+C will no longer cause a `SIGINT` when - * in this mode. - * @since v0.7.7 - * @param mode If `true`, configures the `tty.ReadStream` to operate as a raw device. If `false`, configures the `tty.ReadStream` to operate in its default mode. The `readStream.isRaw` - * property will be set to the resulting mode. - * @return The read stream instance. - */ - setRawMode(mode: boolean): this; - /** - * A `boolean` that is always `true` for `tty.ReadStream` instances. - * @since v0.5.8 - */ - isTTY: boolean; - } - /** - * -1 - to the left from cursor - * 0 - the entire line - * 1 - to the right from cursor - */ - type Direction = -1 | 0 | 1; - /** - * Represents the writable side of a TTY. In normal circumstances,`process.stdout` and `process.stderr` will be the only`tty.WriteStream` instances created for a Node.js process and there - * should be no reason to create additional instances. - * @since v0.5.8 - */ - class WriteStream extends net.Socket { - constructor(fd: number); - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "resize", listener: () => void): this; - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "resize"): boolean; - on(event: string, listener: (...args: any[]) => void): this; - on(event: "resize", listener: () => void): this; - once(event: string, listener: (...args: any[]) => void): this; - once(event: "resize", listener: () => void): this; - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "resize", listener: () => void): this; - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "resize", listener: () => void): this; - /** - * `writeStream.clearLine()` clears the current line of this `WriteStream` in a - * direction identified by `dir`. - * @since v0.7.7 - * @param callback Invoked once the operation completes. - * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. - */ - clearLine(dir: Direction, callback?: () => void): boolean; - /** - * `writeStream.clearScreenDown()` clears this `WriteStream` from the current - * cursor down. - * @since v0.7.7 - * @param callback Invoked once the operation completes. - * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. - */ - clearScreenDown(callback?: () => void): boolean; - /** - * `writeStream.cursorTo()` moves this `WriteStream`'s cursor to the specified - * position. - * @since v0.7.7 - * @param callback Invoked once the operation completes. - * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. - */ - cursorTo(x: number, y?: number, callback?: () => void): boolean; - cursorTo(x: number, callback: () => void): boolean; - /** - * `writeStream.moveCursor()` moves this `WriteStream`'s cursor _relative_ to its - * current position. - * @since v0.7.7 - * @param callback Invoked once the operation completes. - * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. - */ - moveCursor(dx: number, dy: number, callback?: () => void): boolean; - /** - * Returns: - * - * * `1` for 2, - * * `4` for 16, - * * `8` for 256, - * * `24` for 16,777,216 colors supported. - * - * Use this to determine what colors the terminal supports. Due to the nature of - * colors in terminals it is possible to either have false positives or false - * negatives. It depends on process information and the environment variables that - * may lie about what terminal is used. - * It is possible to pass in an `env` object to simulate the usage of a specific - * terminal. This can be useful to check how specific environment settings behave. - * - * To enforce a specific color support, use one of the below environment settings. - * - * * 2 colors: `FORCE_COLOR = 0` (Disables colors) - * * 16 colors: `FORCE_COLOR = 1` - * * 256 colors: `FORCE_COLOR = 2` - * * 16,777,216 colors: `FORCE_COLOR = 3` - * - * Disabling color support is also possible by using the `NO_COLOR` and`NODE_DISABLE_COLORS` environment variables. - * @since v9.9.0 - * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. - */ - getColorDepth(env?: object): number; - /** - * Returns `true` if the `writeStream` supports at least as many colors as provided - * in `count`. Minimum support is 2 (black and white). - * - * This has the same false positives and negatives as described in `writeStream.getColorDepth()`. - * - * ```js - * process.stdout.hasColors(); - * // Returns true or false depending on if `stdout` supports at least 16 colors. - * process.stdout.hasColors(256); - * // Returns true or false depending on if `stdout` supports at least 256 colors. - * process.stdout.hasColors({ TMUX: '1' }); - * // Returns true. - * process.stdout.hasColors(2 ** 24, { TMUX: '1' }); - * // Returns false (the environment setting pretends to support 2 ** 8 colors). - * ``` - * @since v11.13.0, v10.16.0 - * @param [count=16] The number of colors that are requested (minimum 2). - * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. - */ - hasColors(count?: number): boolean; - hasColors(env?: object): boolean; - hasColors(count: number, env?: object): boolean; - /** - * `writeStream.getWindowSize()` returns the size of the TTY - * corresponding to this `WriteStream`. The array is of the type`[numColumns, numRows]` where `numColumns` and `numRows` represent the number - * of columns and rows in the corresponding TTY. - * @since v0.7.7 - */ - getWindowSize(): [number, number]; - /** - * A `number` specifying the number of columns the TTY currently has. This property - * is updated whenever the `'resize'` event is emitted. - * @since v0.7.7 - */ - columns: number; - /** - * A `number` specifying the number of rows the TTY currently has. This property - * is updated whenever the `'resize'` event is emitted. - * @since v0.7.7 - */ - rows: number; - /** - * A `boolean` that is always `true`. - * @since v0.5.8 - */ - isTTY: boolean; - } -} -declare module "node:tty" { - export * from "tty"; -} diff --git a/node_modules/@types/node/ts4.8/url.d.ts b/node_modules/@types/node/ts4.8/url.d.ts deleted file mode 100644 index 20a5d85188d6ab1552230097a1ad8ba16fcec742..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/url.d.ts +++ /dev/null @@ -1,927 +0,0 @@ -/** - * The `node:url` module provides utilities for URL resolution and parsing. It can - * be accessed using: - * - * ```js - * import url from 'node:url'; - * ``` - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/url.js) - */ -declare module "url" { - import { Blob as NodeBlob } from "node:buffer"; - import { ClientRequestArgs } from "node:http"; - import { ParsedUrlQuery, ParsedUrlQueryInput } from "node:querystring"; - // Input to `url.format` - interface UrlObject { - auth?: string | null | undefined; - hash?: string | null | undefined; - host?: string | null | undefined; - hostname?: string | null | undefined; - href?: string | null | undefined; - pathname?: string | null | undefined; - protocol?: string | null | undefined; - search?: string | null | undefined; - slashes?: boolean | null | undefined; - port?: string | number | null | undefined; - query?: string | null | ParsedUrlQueryInput | undefined; - } - // Output of `url.parse` - interface Url { - auth: string | null; - hash: string | null; - host: string | null; - hostname: string | null; - href: string; - path: string | null; - pathname: string | null; - protocol: string | null; - search: string | null; - slashes: boolean | null; - port: string | null; - query: string | null | ParsedUrlQuery; - } - interface UrlWithParsedQuery extends Url { - query: ParsedUrlQuery; - } - interface UrlWithStringQuery extends Url { - query: string | null; - } - /** - * The `url.parse()` method takes a URL string, parses it, and returns a URL - * object. - * - * A `TypeError` is thrown if `urlString` is not a string. - * - * A `URIError` is thrown if the `auth` property is present but cannot be decoded. - * - * `url.parse()` uses a lenient, non-standard algorithm for parsing URL - * strings. It is prone to security issues such as [host name spoofing](https://hackerone.com/reports/678487) and incorrect handling of usernames and passwords. Do not use with untrusted - * input. CVEs are not issued for `url.parse()` vulnerabilities. Use the `WHATWG URL` API instead. - * @since v0.1.25 - * @deprecated Use the WHATWG URL API instead. - * @param urlString The URL string to parse. - * @param [parseQueryString=false] If `true`, the `query` property will always be set to an object returned by the {@link querystring} module's `parse()` method. If `false`, the `query` property - * on the returned URL object will be an unparsed, undecoded string. - * @param [slashesDenoteHost=false] If `true`, the first token after the literal string `//` and preceding the next `/` will be interpreted as the `host`. For instance, given `//foo/bar`, the - * result would be `{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`. - */ - function parse(urlString: string): UrlWithStringQuery; - function parse( - urlString: string, - parseQueryString: false | undefined, - slashesDenoteHost?: boolean, - ): UrlWithStringQuery; - function parse(urlString: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery; - function parse(urlString: string, parseQueryString: boolean, slashesDenoteHost?: boolean): Url; - /** - * The `url.format()` method returns a formatted URL string derived from`urlObject`. - * - * ```js - * const url = require('node:url'); - * url.format({ - * protocol: 'https', - * hostname: 'example.com', - * pathname: '/some/path', - * query: { - * page: 1, - * format: 'json', - * }, - * }); - * - * // => 'https://example.com/some/path?page=1&format=json' - * ``` - * - * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. - * - * The formatting process operates as follows: - * - * * A new empty string `result` is created. - * * If `urlObject.protocol` is a string, it is appended as-is to `result`. - * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. - * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII - * colon (`:`) character, the literal string `:` will be appended to `result`. - * * If either of the following conditions is true, then the literal string `//`will be appended to `result`: - * * `urlObject.slashes` property is true; - * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or`file`; - * * If the value of the `urlObject.auth` property is truthy, and either`urlObject.host` or `urlObject.hostname` are not `undefined`, the value of`urlObject.auth` will be coerced into a string - * and appended to `result`followed by the literal string `@`. - * * If the `urlObject.host` property is `undefined` then: - * * If the `urlObject.hostname` is a string, it is appended to `result`. - * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, - * an `Error` is thrown. - * * If the `urlObject.port` property value is truthy, and `urlObject.hostname`is not `undefined`: - * * The literal string `:` is appended to `result`, and - * * The value of `urlObject.port` is coerced to a string and appended to`result`. - * * Otherwise, if the `urlObject.host` property value is truthy, the value of`urlObject.host` is coerced to a string and appended to `result`. - * * If the `urlObject.pathname` property is a string that is not an empty string: - * * If the `urlObject.pathname`_does not start_ with an ASCII forward slash - * (`/`), then the literal string `'/'` is appended to `result`. - * * The value of `urlObject.pathname` is appended to `result`. - * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. - * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result`followed by the output of calling the - * `querystring` module's `stringify()`method passing the value of `urlObject.query`. - * * Otherwise, if `urlObject.search` is a string: - * * If the value of `urlObject.search`_does not start_ with the ASCII question - * mark (`?`) character, the literal string `?` is appended to `result`. - * * The value of `urlObject.search` is appended to `result`. - * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. - * * If the `urlObject.hash` property is a string: - * * If the value of `urlObject.hash`_does not start_ with the ASCII hash (`#`) - * character, the literal string `#` is appended to `result`. - * * The value of `urlObject.hash` is appended to `result`. - * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a - * string, an `Error` is thrown. - * * `result` is returned. - * @since v0.1.25 - * @legacy Use the WHATWG URL API instead. - * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. - */ - function format(urlObject: URL, options?: URLFormatOptions): string; - /** - * The `url.format()` method returns a formatted URL string derived from`urlObject`. - * - * ```js - * const url = require('url'); - * url.format({ - * protocol: 'https', - * hostname: 'example.com', - * pathname: '/some/path', - * query: { - * page: 1, - * format: 'json' - * } - * }); - * - * // => 'https://example.com/some/path?page=1&format=json' - * ``` - * - * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. - * - * The formatting process operates as follows: - * - * * A new empty string `result` is created. - * * If `urlObject.protocol` is a string, it is appended as-is to `result`. - * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. - * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII - * colon (`:`) character, the literal string `:` will be appended to `result`. - * * If either of the following conditions is true, then the literal string `//`will be appended to `result`: - * * `urlObject.slashes` property is true; - * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or`file`; - * * If the value of the `urlObject.auth` property is truthy, and either`urlObject.host` or `urlObject.hostname` are not `undefined`, the value of`urlObject.auth` will be coerced into a string - * and appended to `result`followed by the literal string `@`. - * * If the `urlObject.host` property is `undefined` then: - * * If the `urlObject.hostname` is a string, it is appended to `result`. - * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, - * an `Error` is thrown. - * * If the `urlObject.port` property value is truthy, and `urlObject.hostname`is not `undefined`: - * * The literal string `:` is appended to `result`, and - * * The value of `urlObject.port` is coerced to a string and appended to`result`. - * * Otherwise, if the `urlObject.host` property value is truthy, the value of`urlObject.host` is coerced to a string and appended to `result`. - * * If the `urlObject.pathname` property is a string that is not an empty string: - * * If the `urlObject.pathname`_does not start_ with an ASCII forward slash - * (`/`), then the literal string `'/'` is appended to `result`. - * * The value of `urlObject.pathname` is appended to `result`. - * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. - * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result`followed by the output of calling the - * `querystring` module's `stringify()`method passing the value of `urlObject.query`. - * * Otherwise, if `urlObject.search` is a string: - * * If the value of `urlObject.search`_does not start_ with the ASCII question - * mark (`?`) character, the literal string `?` is appended to `result`. - * * The value of `urlObject.search` is appended to `result`. - * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. - * * If the `urlObject.hash` property is a string: - * * If the value of `urlObject.hash`_does not start_ with the ASCII hash (`#`) - * character, the literal string `#` is appended to `result`. - * * The value of `urlObject.hash` is appended to `result`. - * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a - * string, an `Error` is thrown. - * * `result` is returned. - * @since v0.1.25 - * @legacy Use the WHATWG URL API instead. - * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. - */ - function format(urlObject: UrlObject | string): string; - /** - * The `url.resolve()` method resolves a target URL relative to a base URL in a - * manner similar to that of a web browser resolving an anchor tag. - * - * ```js - * const url = require('node:url'); - * url.resolve('/one/two/three', 'four'); // '/one/two/four' - * url.resolve('http://example.com/', '/one'); // 'http://example.com/one' - * url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' - * ``` - * - * To achieve the same result using the WHATWG URL API: - * - * ```js - * function resolve(from, to) { - * const resolvedUrl = new URL(to, new URL(from, 'resolve://')); - * if (resolvedUrl.protocol === 'resolve:') { - * // `from` is a relative URL. - * const { pathname, search, hash } = resolvedUrl; - * return pathname + search + hash; - * } - * return resolvedUrl.toString(); - * } - * - * resolve('/one/two/three', 'four'); // '/one/two/four' - * resolve('http://example.com/', '/one'); // 'http://example.com/one' - * resolve('http://example.com/one', '/two'); // 'http://example.com/two' - * ``` - * @since v0.1.25 - * @legacy Use the WHATWG URL API instead. - * @param from The base URL to use if `to` is a relative URL. - * @param to The target URL to resolve. - */ - function resolve(from: string, to: string): string; - /** - * Returns the [Punycode](https://tools.ietf.org/html/rfc5891#section-4.4) ASCII serialization of the `domain`. If `domain` is an - * invalid domain, the empty string is returned. - * - * It performs the inverse operation to {@link domainToUnicode}. - * - * ```js - * import url from 'node:url'; - * - * console.log(url.domainToASCII('español.com')); - * // Prints xn--espaol-zwa.com - * console.log(url.domainToASCII('中文.com')); - * // Prints xn--fiq228c.com - * console.log(url.domainToASCII('xn--iñvalid.com')); - * // Prints an empty string - * ``` - * @since v7.4.0, v6.13.0 - */ - function domainToASCII(domain: string): string; - /** - * Returns the Unicode serialization of the `domain`. If `domain` is an invalid - * domain, the empty string is returned. - * - * It performs the inverse operation to {@link domainToASCII}. - * - * ```js - * import url from 'node:url'; - * - * console.log(url.domainToUnicode('xn--espaol-zwa.com')); - * // Prints español.com - * console.log(url.domainToUnicode('xn--fiq228c.com')); - * // Prints 中文.com - * console.log(url.domainToUnicode('xn--iñvalid.com')); - * // Prints an empty string - * ``` - * @since v7.4.0, v6.13.0 - */ - function domainToUnicode(domain: string): string; - /** - * This function ensures the correct decodings of percent-encoded characters as - * well as ensuring a cross-platform valid absolute path string. - * - * ```js - * import { fileURLToPath } from 'node:url'; - * - * const __filename = fileURLToPath(import.meta.url); - * - * new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/ - * fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows) - * - * new URL('file://nas/foo.txt').pathname; // Incorrect: /foo.txt - * fileURLToPath('file://nas/foo.txt'); // Correct: \\nas\foo.txt (Windows) - * - * new URL('file:///你好.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt - * fileURLToPath('file:///你好.txt'); // Correct: /你好.txt (POSIX) - * - * new URL('file:///hello world').pathname; // Incorrect: /hello%20world - * fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX) - * ``` - * @since v10.12.0 - * @param url The file URL string or URL object to convert to a path. - * @return The fully-resolved platform-specific Node.js file path. - */ - function fileURLToPath(url: string | URL): string; - /** - * This function ensures that `path` is resolved absolutely, and that the URL - * control characters are correctly encoded when converting into a File URL. - * - * ```js - * import { pathToFileURL } from 'node:url'; - * - * new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1 - * pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX) - * - * new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c - * pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSIX) - * ``` - * @since v10.12.0 - * @param path The path to convert to a File URL. - * @return The file URL object. - */ - function pathToFileURL(path: string): URL; - /** - * This utility function converts a URL object into an ordinary options object as - * expected by the `http.request()` and `https.request()` APIs. - * - * ```js - * import { urlToHttpOptions } from 'node:url'; - * const myURL = new URL('https://a:b@測試?abc#foo'); - * - * console.log(urlToHttpOptions(myURL)); - * /* - * { - * protocol: 'https:', - * hostname: 'xn--g6w251d', - * hash: '#foo', - * search: '?abc', - * pathname: '/', - * path: '/?abc', - * href: 'https://a:b@xn--g6w251d/?abc#foo', - * auth: 'a:b' - * } - * - * ``` - * @since v15.7.0, v14.18.0 - * @param url The `WHATWG URL` object to convert to an options object. - * @return Options object - */ - function urlToHttpOptions(url: URL): ClientRequestArgs; - interface URLFormatOptions { - auth?: boolean | undefined; - fragment?: boolean | undefined; - search?: boolean | undefined; - unicode?: boolean | undefined; - } - /** - * Browser-compatible `URL` class, implemented by following the WHATWG URL - * Standard. [Examples of parsed URLs](https://url.spec.whatwg.org/#example-url-parsing) may be found in the Standard itself. - * The `URL` class is also available on the global object. - * - * In accordance with browser conventions, all properties of `URL` objects - * are implemented as getters and setters on the class prototype, rather than as - * data properties on the object itself. Thus, unlike `legacy urlObject` s, - * using the `delete` keyword on any properties of `URL` objects (e.g. `delete myURL.protocol`, `delete myURL.pathname`, etc) has no effect but will still - * return `true`. - * @since v7.0.0, v6.13.0 - */ - class URL { - /** - * Creates a `'blob:nodedata:...'` URL string that represents the given `Blob` object and can be used to retrieve the `Blob` later. - * - * ```js - * const { - * Blob, - * resolveObjectURL, - * } = require('node:buffer'); - * - * const blob = new Blob(['hello']); - * const id = URL.createObjectURL(blob); - * - * // later... - * - * const otherBlob = resolveObjectURL(id); - * console.log(otherBlob.size); - * ``` - * - * The data stored by the registered `Blob` will be retained in memory until`URL.revokeObjectURL()` is called to remove it. - * - * `Blob` objects are registered within the current thread. If using Worker - * Threads, `Blob` objects registered within one Worker will not be available - * to other workers or the main thread. - * @since v16.7.0 - * @experimental - */ - static createObjectURL(blob: NodeBlob): string; - /** - * Removes the stored `Blob` identified by the given ID. Attempting to revoke a - * ID that isn't registered will silently fail. - * @since v16.7.0 - * @experimental - * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. - */ - static revokeObjectURL(objectUrl: string): void; - /** - * Checks if an `input` relative to the `base` can be parsed to a `URL`. - * - * ```js - * const isValid = URL.canParse('/foo', 'https://example.org/'); // true - * - * const isNotValid = URL.canParse('/foo'); // false - * ``` - * @since v19.9.0 - * @param input The absolute or relative input URL to parse. If `input` is relative, then `base` is required. If `input` is absolute, the `base` is ignored. If `input` is not a string, it is - * `converted to a string` first. - * @param base The base URL to resolve against if the `input` is not absolute. If `base` is not a string, it is `converted to a string` first. - */ - static canParse(input: string, base?: string): boolean; - constructor(input: string, base?: string | URL); - /** - * Gets and sets the fragment portion of the URL. - * - * ```js - * const myURL = new URL('https://example.org/foo#bar'); - * console.log(myURL.hash); - * // Prints #bar - * - * myURL.hash = 'baz'; - * console.log(myURL.href); - * // Prints https://example.org/foo#baz - * ``` - * - * Invalid URL characters included in the value assigned to the `hash` property - * are `percent-encoded`. The selection of which characters to - * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. - */ - hash: string; - /** - * Gets and sets the host portion of the URL. - * - * ```js - * const myURL = new URL('https://example.org:81/foo'); - * console.log(myURL.host); - * // Prints example.org:81 - * - * myURL.host = 'example.com:82'; - * console.log(myURL.href); - * // Prints https://example.com:82/foo - * ``` - * - * Invalid host values assigned to the `host` property are ignored. - */ - host: string; - /** - * Gets and sets the host name portion of the URL. The key difference between`url.host` and `url.hostname` is that `url.hostname` does _not_ include the - * port. - * - * ```js - * const myURL = new URL('https://example.org:81/foo'); - * console.log(myURL.hostname); - * // Prints example.org - * - * // Setting the hostname does not change the port - * myURL.hostname = 'example.com'; - * console.log(myURL.href); - * // Prints https://example.com:81/foo - * - * // Use myURL.host to change the hostname and port - * myURL.host = 'example.org:82'; - * console.log(myURL.href); - * // Prints https://example.org:82/foo - * ``` - * - * Invalid host name values assigned to the `hostname` property are ignored. - */ - hostname: string; - /** - * Gets and sets the serialized URL. - * - * ```js - * const myURL = new URL('https://example.org/foo'); - * console.log(myURL.href); - * // Prints https://example.org/foo - * - * myURL.href = 'https://example.com/bar'; - * console.log(myURL.href); - * // Prints https://example.com/bar - * ``` - * - * Getting the value of the `href` property is equivalent to calling {@link toString}. - * - * Setting the value of this property to a new value is equivalent to creating a - * new `URL` object using `new URL(value)`. Each of the `URL`object's properties will be modified. - * - * If the value assigned to the `href` property is not a valid URL, a `TypeError`will be thrown. - */ - href: string; - /** - * Gets the read-only serialization of the URL's origin. - * - * ```js - * const myURL = new URL('https://example.org/foo/bar?baz'); - * console.log(myURL.origin); - * // Prints https://example.org - * ``` - * - * ```js - * const idnURL = new URL('https://測試'); - * console.log(idnURL.origin); - * // Prints https://xn--g6w251d - * - * console.log(idnURL.hostname); - * // Prints xn--g6w251d - * ``` - */ - readonly origin: string; - /** - * Gets and sets the password portion of the URL. - * - * ```js - * const myURL = new URL('https://abc:xyz@example.com'); - * console.log(myURL.password); - * // Prints xyz - * - * myURL.password = '123'; - * console.log(myURL.href); - * // Prints https://abc:123@example.com/ - * ``` - * - * Invalid URL characters included in the value assigned to the `password` property - * are `percent-encoded`. The selection of which characters to - * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. - */ - password: string; - /** - * Gets and sets the path portion of the URL. - * - * ```js - * const myURL = new URL('https://example.org/abc/xyz?123'); - * console.log(myURL.pathname); - * // Prints /abc/xyz - * - * myURL.pathname = '/abcdef'; - * console.log(myURL.href); - * // Prints https://example.org/abcdef?123 - * ``` - * - * Invalid URL characters included in the value assigned to the `pathname`property are `percent-encoded`. The selection of which characters - * to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. - */ - pathname: string; - /** - * Gets and sets the port portion of the URL. - * - * The port value may be a number or a string containing a number in the range`0` to `65535` (inclusive). Setting the value to the default port of the`URL` objects given `protocol` will - * result in the `port` value becoming - * the empty string (`''`). - * - * The port value can be an empty string in which case the port depends on - * the protocol/scheme: - * - * - * - * Upon assigning a value to the port, the value will first be converted to a - * string using `.toString()`. - * - * If that string is invalid but it begins with a number, the leading number is - * assigned to `port`. - * If the number lies outside the range denoted above, it is ignored. - * - * ```js - * const myURL = new URL('https://example.org:8888'); - * console.log(myURL.port); - * // Prints 8888 - * - * // Default ports are automatically transformed to the empty string - * // (HTTPS protocol's default port is 443) - * myURL.port = '443'; - * console.log(myURL.port); - * // Prints the empty string - * console.log(myURL.href); - * // Prints https://example.org/ - * - * myURL.port = 1234; - * console.log(myURL.port); - * // Prints 1234 - * console.log(myURL.href); - * // Prints https://example.org:1234/ - * - * // Completely invalid port strings are ignored - * myURL.port = 'abcd'; - * console.log(myURL.port); - * // Prints 1234 - * - * // Leading numbers are treated as a port number - * myURL.port = '5678abcd'; - * console.log(myURL.port); - * // Prints 5678 - * - * // Non-integers are truncated - * myURL.port = 1234.5678; - * console.log(myURL.port); - * // Prints 1234 - * - * // Out-of-range numbers which are not represented in scientific notation - * // will be ignored. - * myURL.port = 1e10; // 10000000000, will be range-checked as described below - * console.log(myURL.port); - * // Prints 1234 - * ``` - * - * Numbers which contain a decimal point, - * such as floating-point numbers or numbers in scientific notation, - * are not an exception to this rule. - * Leading numbers up to the decimal point will be set as the URL's port, - * assuming they are valid: - * - * ```js - * myURL.port = 4.567e21; - * console.log(myURL.port); - * // Prints 4 (because it is the leading number in the string '4.567e21') - * ``` - */ - port: string; - /** - * Gets and sets the protocol portion of the URL. - * - * ```js - * const myURL = new URL('https://example.org'); - * console.log(myURL.protocol); - * // Prints https: - * - * myURL.protocol = 'ftp'; - * console.log(myURL.href); - * // Prints ftp://example.org/ - * ``` - * - * Invalid URL protocol values assigned to the `protocol` property are ignored. - */ - protocol: string; - /** - * Gets and sets the serialized query portion of the URL. - * - * ```js - * const myURL = new URL('https://example.org/abc?123'); - * console.log(myURL.search); - * // Prints ?123 - * - * myURL.search = 'abc=xyz'; - * console.log(myURL.href); - * // Prints https://example.org/abc?abc=xyz - * ``` - * - * Any invalid URL characters appearing in the value assigned the `search`property will be `percent-encoded`. The selection of which - * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. - */ - search: string; - /** - * Gets the `URLSearchParams` object representing the query parameters of the - * URL. This property is read-only but the `URLSearchParams` object it provides - * can be used to mutate the URL instance; to replace the entirety of query - * parameters of the URL, use the {@link search} setter. See `URLSearchParams` documentation for details. - * - * Use care when using `.searchParams` to modify the `URL` because, - * per the WHATWG specification, the `URLSearchParams` object uses - * different rules to determine which characters to percent-encode. For - * instance, the `URL` object will not percent encode the ASCII tilde (`~`) - * character, while `URLSearchParams` will always encode it: - * - * ```js - * const myURL = new URL('https://example.org/abc?foo=~bar'); - * - * console.log(myURL.search); // prints ?foo=~bar - * - * // Modify the URL via searchParams... - * myURL.searchParams.sort(); - * - * console.log(myURL.search); // prints ?foo=%7Ebar - * ``` - */ - readonly searchParams: URLSearchParams; - /** - * Gets and sets the username portion of the URL. - * - * ```js - * const myURL = new URL('https://abc:xyz@example.com'); - * console.log(myURL.username); - * // Prints abc - * - * myURL.username = '123'; - * console.log(myURL.href); - * // Prints https://123:xyz@example.com/ - * ``` - * - * Any invalid URL characters appearing in the value assigned the `username`property will be `percent-encoded`. The selection of which - * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. - */ - username: string; - /** - * The `toString()` method on the `URL` object returns the serialized URL. The - * value returned is equivalent to that of {@link href} and {@link toJSON}. - */ - toString(): string; - /** - * The `toJSON()` method on the `URL` object returns the serialized URL. The - * value returned is equivalent to that of {@link href} and {@link toString}. - * - * This method is automatically called when an `URL` object is serialized - * with [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). - * - * ```js - * const myURLs = [ - * new URL('https://www.example.com'), - * new URL('https://test.example.org'), - * ]; - * console.log(JSON.stringify(myURLs)); - * // Prints ["https://www.example.com/","https://test.example.org/"] - * ``` - */ - toJSON(): string; - } - /** - * The `URLSearchParams` API provides read and write access to the query of a`URL`. The `URLSearchParams` class can also be used standalone with one of the - * four following constructors. - * The `URLSearchParams` class is also available on the global object. - * - * The WHATWG `URLSearchParams` interface and the `querystring` module have - * similar purpose, but the purpose of the `querystring` module is more - * general, as it allows the customization of delimiter characters (`&` and `=`). - * On the other hand, this API is designed purely for URL query strings. - * - * ```js - * const myURL = new URL('https://example.org/?abc=123'); - * console.log(myURL.searchParams.get('abc')); - * // Prints 123 - * - * myURL.searchParams.append('abc', 'xyz'); - * console.log(myURL.href); - * // Prints https://example.org/?abc=123&abc=xyz - * - * myURL.searchParams.delete('abc'); - * myURL.searchParams.set('a', 'b'); - * console.log(myURL.href); - * // Prints https://example.org/?a=b - * - * const newSearchParams = new URLSearchParams(myURL.searchParams); - * // The above is equivalent to - * // const newSearchParams = new URLSearchParams(myURL.search); - * - * newSearchParams.append('a', 'c'); - * console.log(myURL.href); - * // Prints https://example.org/?a=b - * console.log(newSearchParams.toString()); - * // Prints a=b&a=c - * - * // newSearchParams.toString() is implicitly called - * myURL.search = newSearchParams; - * console.log(myURL.href); - * // Prints https://example.org/?a=b&a=c - * newSearchParams.delete('a'); - * console.log(myURL.href); - * // Prints https://example.org/?a=b&a=c - * ``` - * @since v7.5.0, v6.13.0 - */ - class URLSearchParams implements Iterable<[string, string]> { - constructor( - init?: - | URLSearchParams - | string - | Record - | Iterable<[string, string]> - | ReadonlyArray<[string, string]>, - ); - /** - * Append a new name-value pair to the query string. - */ - append(name: string, value: string): void; - /** - * If `value` is provided, removes all name-value pairs - * where name is `name` and value is `value`.. - * - * If `value` is not provided, removes all name-value pairs whose name is `name`. - */ - delete(name: string, value?: string): void; - /** - * Returns an ES6 `Iterator` over each of the name-value pairs in the query. - * Each item of the iterator is a JavaScript `Array`. The first item of the `Array`is the `name`, the second item of the `Array` is the `value`. - * - * Alias for `urlSearchParams[@@iterator]()`. - */ - entries(): IterableIterator<[string, string]>; - /** - * Iterates over each name-value pair in the query and invokes the given function. - * - * ```js - * const myURL = new URL('https://example.org/?a=b&c=d'); - * myURL.searchParams.forEach((value, name, searchParams) => { - * console.log(name, value, myURL.searchParams === searchParams); - * }); - * // Prints: - * // a b true - * // c d true - * ``` - * @param fn Invoked for each name-value pair in the query - * @param thisArg To be used as `this` value for when `fn` is called - */ - forEach( - callback: (this: TThis, value: string, name: string, searchParams: URLSearchParams) => void, - thisArg?: TThis, - ): void; - /** - * Returns the value of the first name-value pair whose name is `name`. If there - * are no such pairs, `null` is returned. - * @return or `null` if there is no name-value pair with the given `name`. - */ - get(name: string): string | null; - /** - * Returns the values of all name-value pairs whose name is `name`. If there are - * no such pairs, an empty array is returned. - */ - getAll(name: string): string[]; - /** - * Checks if the `URLSearchParams` object contains key-value pair(s) based on`name` and an optional `value` argument. - * - * If `value` is provided, returns `true` when name-value pair with - * same `name` and `value` exists. - * - * If `value` is not provided, returns `true` if there is at least one name-value - * pair whose name is `name`. - */ - has(name: string, value?: string): boolean; - /** - * Returns an ES6 `Iterator` over the names of each name-value pair. - * - * ```js - * const params = new URLSearchParams('foo=bar&foo=baz'); - * for (const name of params.keys()) { - * console.log(name); - * } - * // Prints: - * // foo - * // foo - * ``` - */ - keys(): IterableIterator; - /** - * Sets the value in the `URLSearchParams` object associated with `name` to`value`. If there are any pre-existing name-value pairs whose names are `name`, - * set the first such pair's value to `value` and remove all others. If not, - * append the name-value pair to the query string. - * - * ```js - * const params = new URLSearchParams(); - * params.append('foo', 'bar'); - * params.append('foo', 'baz'); - * params.append('abc', 'def'); - * console.log(params.toString()); - * // Prints foo=bar&foo=baz&abc=def - * - * params.set('foo', 'def'); - * params.set('xyz', 'opq'); - * console.log(params.toString()); - * // Prints foo=def&abc=def&xyz=opq - * ``` - */ - set(name: string, value: string): void; - /** - * The total number of parameter entries. - * @since v19.8.0 - */ - readonly size: number; - /** - * Sort all existing name-value pairs in-place by their names. Sorting is done - * with a [stable sorting algorithm](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability), so relative order between name-value pairs - * with the same name is preserved. - * - * This method can be used, in particular, to increase cache hits. - * - * ```js - * const params = new URLSearchParams('query[]=abc&type=search&query[]=123'); - * params.sort(); - * console.log(params.toString()); - * // Prints query%5B%5D=abc&query%5B%5D=123&type=search - * ``` - * @since v7.7.0, v6.13.0 - */ - sort(): void; - /** - * Returns the search parameters serialized as a string, with characters - * percent-encoded where necessary. - */ - toString(): string; - /** - * Returns an ES6 `Iterator` over the values of each name-value pair. - */ - values(): IterableIterator; - [Symbol.iterator](): IterableIterator<[string, string]>; - } - import { URL as _URL, URLSearchParams as _URLSearchParams } from "url"; - global { - interface URLSearchParams extends _URLSearchParams {} - interface URL extends _URL {} - interface Global { - URL: typeof _URL; - URLSearchParams: typeof _URLSearchParams; - } - /** - * `URL` class is a global reference for `require('url').URL` - * https://nodejs.org/api/url.html#the-whatwg-url-api - * @since v10.0.0 - */ - var URL: typeof globalThis extends { - onmessage: any; - URL: infer T; - } ? T - : typeof _URL; - /** - * `URLSearchParams` class is a global reference for `require('url').URLSearchParams` - * https://nodejs.org/api/url.html#class-urlsearchparams - * @since v10.0.0 - */ - var URLSearchParams: typeof globalThis extends { - onmessage: any; - URLSearchParams: infer T; - } ? T - : typeof _URLSearchParams; - } -} -declare module "node:url" { - export * from "url"; -} diff --git a/node_modules/@types/node/ts4.8/util.d.ts b/node_modules/@types/node/ts4.8/util.d.ts deleted file mode 100644 index ac269ec1b8bada35e04922d725cd9bd3371eaa4b..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/util.d.ts +++ /dev/null @@ -1,2183 +0,0 @@ -/** - * The `node:util` module supports the needs of Node.js internal APIs. Many of the - * utilities are useful for application and module developers as well. To access - * it: - * - * ```js - * const util = require('node:util'); - * ``` - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/util.js) - */ -declare module "util" { - import * as types from "node:util/types"; - export interface InspectOptions { - /** - * If `true`, object's non-enumerable symbols and properties are included in the formatted result. - * `WeakMap` and `WeakSet` entries are also included as well as user defined prototype properties (excluding method properties). - * @default false - */ - showHidden?: boolean | undefined; - /** - * Specifies the number of times to recurse while formatting object. - * This is useful for inspecting large objects. - * To recurse up to the maximum call stack size pass `Infinity` or `null`. - * @default 2 - */ - depth?: number | null | undefined; - /** - * If `true`, the output is styled with ANSI color codes. Colors are customizable. - */ - colors?: boolean | undefined; - /** - * If `false`, `[util.inspect.custom](depth, opts, inspect)` functions are not invoked. - * @default true - */ - customInspect?: boolean | undefined; - /** - * If `true`, `Proxy` inspection includes the target and handler objects. - * @default false - */ - showProxy?: boolean | undefined; - /** - * Specifies the maximum number of `Array`, `TypedArray`, `WeakMap`, and `WeakSet` elements - * to include when formatting. Set to `null` or `Infinity` to show all elements. - * Set to `0` or negative to show no elements. - * @default 100 - */ - maxArrayLength?: number | null | undefined; - /** - * Specifies the maximum number of characters to - * include when formatting. Set to `null` or `Infinity` to show all elements. - * Set to `0` or negative to show no characters. - * @default 10000 - */ - maxStringLength?: number | null | undefined; - /** - * The length at which input values are split across multiple lines. - * Set to `Infinity` to format the input as a single line - * (in combination with `compact` set to `true` or any number >= `1`). - * @default 80 - */ - breakLength?: number | undefined; - /** - * Setting this to `false` causes each object key - * to be displayed on a new line. It will also add new lines to text that is - * longer than `breakLength`. If set to a number, the most `n` inner elements - * are united on a single line as long as all properties fit into - * `breakLength`. Short array elements are also grouped together. Note that no - * text will be reduced below 16 characters, no matter the `breakLength` size. - * For more information, see the example below. - * @default true - */ - compact?: boolean | number | undefined; - /** - * If set to `true` or a function, all properties of an object, and `Set` and `Map` - * entries are sorted in the resulting string. - * If set to `true` the default sort is used. - * If set to a function, it is used as a compare function. - */ - sorted?: boolean | ((a: string, b: string) => number) | undefined; - /** - * If set to `true`, getters are going to be - * inspected as well. If set to `'get'` only getters without setter are going - * to be inspected. If set to `'set'` only getters having a corresponding - * setter are going to be inspected. This might cause side effects depending on - * the getter function. - * @default false - */ - getters?: "get" | "set" | boolean | undefined; - /** - * If set to `true`, an underscore is used to separate every three digits in all bigints and numbers. - * @default false - */ - numericSeparator?: boolean | undefined; - } - export type Style = - | "special" - | "number" - | "bigint" - | "boolean" - | "undefined" - | "null" - | "string" - | "symbol" - | "date" - | "regexp" - | "module"; - export type CustomInspectFunction = (depth: number, options: InspectOptionsStylized) => any; // TODO: , inspect: inspect - export interface InspectOptionsStylized extends InspectOptions { - stylize(text: string, styleType: Style): string; - } - /** - * The `util.format()` method returns a formatted string using the first argument - * as a `printf`\-like format string which can contain zero or more format - * specifiers. Each specifier is replaced with the converted value from the - * corresponding argument. Supported specifiers are: - * - * If a specifier does not have a corresponding argument, it is not replaced: - * - * ```js - * util.format('%s:%s', 'foo'); - * // Returns: 'foo:%s' - * ``` - * - * Values that are not part of the format string are formatted using`util.inspect()` if their type is not `string`. - * - * If there are more arguments passed to the `util.format()` method than the - * number of specifiers, the extra arguments are concatenated to the returned - * string, separated by spaces: - * - * ```js - * util.format('%s:%s', 'foo', 'bar', 'baz'); - * // Returns: 'foo:bar baz' - * ``` - * - * If the first argument does not contain a valid format specifier, `util.format()`returns a string that is the concatenation of all arguments separated by spaces: - * - * ```js - * util.format(1, 2, 3); - * // Returns: '1 2 3' - * ``` - * - * If only one argument is passed to `util.format()`, it is returned as it is - * without any formatting: - * - * ```js - * util.format('%% %s'); - * // Returns: '%% %s' - * ``` - * - * `util.format()` is a synchronous method that is intended as a debugging tool. - * Some input values can have a significant performance overhead that can block the - * event loop. Use this function with care and never in a hot code path. - * @since v0.5.3 - * @param format A `printf`-like format string. - */ - export function format(format?: any, ...param: any[]): string; - /** - * This function is identical to {@link format}, except in that it takes - * an `inspectOptions` argument which specifies options that are passed along to {@link inspect}. - * - * ```js - * util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 }); - * // Returns 'See object { foo: 42 }', where `42` is colored as a number - * // when printed to a terminal. - * ``` - * @since v10.0.0 - */ - export function formatWithOptions(inspectOptions: InspectOptions, format?: any, ...param: any[]): string; - /** - * Returns the string name for a numeric error code that comes from a Node.js API. - * The mapping between error codes and error names is platform-dependent. - * See `Common System Errors` for the names of common errors. - * - * ```js - * fs.access('file/that/does/not/exist', (err) => { - * const name = util.getSystemErrorName(err.errno); - * console.error(name); // ENOENT - * }); - * ``` - * @since v9.7.0 - */ - export function getSystemErrorName(err: number): string; - /** - * Returns a Map of all system error codes available from the Node.js API. - * The mapping between error codes and error names is platform-dependent. - * See `Common System Errors` for the names of common errors. - * - * ```js - * fs.access('file/that/does/not/exist', (err) => { - * const errorMap = util.getSystemErrorMap(); - * const name = errorMap.get(err.errno); - * console.error(name); // ENOENT - * }); - * ``` - * @since v16.0.0, v14.17.0 - */ - export function getSystemErrorMap(): Map; - /** - * The `util.log()` method prints the given `string` to `stdout` with an included - * timestamp. - * - * ```js - * const util = require('node:util'); - * - * util.log('Timestamped message.'); - * ``` - * @since v0.3.0 - * @deprecated Since v6.0.0 - Use a third party module instead. - */ - export function log(string: string): void; - /** - * Returns the `string` after replacing any surrogate code points - * (or equivalently, any unpaired surrogate code units) with the - * Unicode "replacement character" U+FFFD. - * @since v16.8.0, v14.18.0 - */ - export function toUSVString(string: string): string; - /** - * Creates and returns an `AbortController` instance whose `AbortSignal` is marked - * as transferable and can be used with `structuredClone()` or `postMessage()`. - * @since v18.11.0 - * @experimental - * @returns A transferable AbortController - */ - export function transferableAbortController(): AbortController; - /** - * Marks the given `AbortSignal` as transferable so that it can be used with`structuredClone()` and `postMessage()`. - * - * ```js - * const signal = transferableAbortSignal(AbortSignal.timeout(100)); - * const channel = new MessageChannel(); - * channel.port2.postMessage(signal, [signal]); - * ``` - * @since v18.11.0 - * @experimental - * @param signal The AbortSignal - * @returns The same AbortSignal - */ - export function transferableAbortSignal(signal: AbortSignal): AbortSignal; - /** - * Listens to abort event on the provided `signal` and - * returns a promise that is fulfilled when the `signal` is - * aborted. If the passed `resource` is garbage collected before the `signal` is - * aborted, the returned promise shall remain pending indefinitely. - * - * ```js - * import { aborted } from 'node:util'; - * - * const dependent = obtainSomethingAbortable(); - * - * aborted(dependent.signal, dependent).then(() => { - * // Do something when dependent is aborted. - * }); - * - * dependent.on('event', () => { - * dependent.abort(); - * }); - * ``` - * @since v19.7.0 - * @experimental - * @param resource Any non-null entity, reference to which is held weakly. - */ - export function aborted(signal: AbortSignal, resource: any): Promise; - /** - * The `util.inspect()` method returns a string representation of `object` that is - * intended for debugging. The output of `util.inspect` may change at any time - * and should not be depended upon programmatically. Additional `options` may be - * passed that alter the result.`util.inspect()` will use the constructor's name and/or `@@toStringTag` to make - * an identifiable tag for an inspected value. - * - * ```js - * class Foo { - * get [Symbol.toStringTag]() { - * return 'bar'; - * } - * } - * - * class Bar {} - * - * const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } }); - * - * util.inspect(new Foo()); // 'Foo [bar] {}' - * util.inspect(new Bar()); // 'Bar {}' - * util.inspect(baz); // '[foo] {}' - * ``` - * - * Circular references point to their anchor by using a reference index: - * - * ```js - * const { inspect } = require('node:util'); - * - * const obj = {}; - * obj.a = [obj]; - * obj.b = {}; - * obj.b.inner = obj.b; - * obj.b.obj = obj; - * - * console.log(inspect(obj)); - * // { - * // a: [ [Circular *1] ], - * // b: { inner: [Circular *2], obj: [Circular *1] } - * // } - * ``` - * - * The following example inspects all properties of the `util` object: - * - * ```js - * const util = require('node:util'); - * - * console.log(util.inspect(util, { showHidden: true, depth: null })); - * ``` - * - * The following example highlights the effect of the `compact` option: - * - * ```js - * const util = require('node:util'); - * - * const o = { - * a: [1, 2, [[ - * 'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit, sed do ' + - * 'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.', - * 'test', - * 'foo']], 4], - * b: new Map([['za', 1], ['zb', 'test']]), - * }; - * console.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 })); - * - * // { a: - * // [ 1, - * // 2, - * // [ [ 'Lorem ipsum dolor sit amet,\nconsectetur [...]', // A long line - * // 'test', - * // 'foo' ] ], - * // 4 ], - * // b: Map(2) { 'za' => 1, 'zb' => 'test' } } - * - * // Setting `compact` to false or an integer creates more reader friendly output. - * console.log(util.inspect(o, { compact: false, depth: 5, breakLength: 80 })); - * - * // { - * // a: [ - * // 1, - * // 2, - * // [ - * // [ - * // 'Lorem ipsum dolor sit amet,\n' + - * // 'consectetur adipiscing elit, sed do eiusmod \n' + - * // 'tempor incididunt ut labore et dolore magna aliqua.', - * // 'test', - * // 'foo' - * // ] - * // ], - * // 4 - * // ], - * // b: Map(2) { - * // 'za' => 1, - * // 'zb' => 'test' - * // } - * // } - * - * // Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a - * // single line. - * ``` - * - * The `showHidden` option allows [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) and - * [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) entries to be - * inspected. If there are more entries than `maxArrayLength`, there is no - * guarantee which entries are displayed. That means retrieving the same [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) entries twice may - * result in different output. Furthermore, entries - * with no remaining strong references may be garbage collected at any time. - * - * ```js - * const { inspect } = require('node:util'); - * - * const obj = { a: 1 }; - * const obj2 = { b: 2 }; - * const weakSet = new WeakSet([obj, obj2]); - * - * console.log(inspect(weakSet, { showHidden: true })); - * // WeakSet { { a: 1 }, { b: 2 } } - * ``` - * - * The `sorted` option ensures that an object's property insertion order does not - * impact the result of `util.inspect()`. - * - * ```js - * const { inspect } = require('node:util'); - * const assert = require('node:assert'); - * - * const o1 = { - * b: [2, 3, 1], - * a: '`a` comes before `b`', - * c: new Set([2, 3, 1]), - * }; - * console.log(inspect(o1, { sorted: true })); - * // { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } } - * console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) })); - * // { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' } - * - * const o2 = { - * c: new Set([2, 1, 3]), - * a: '`a` comes before `b`', - * b: [2, 3, 1], - * }; - * assert.strict.equal( - * inspect(o1, { sorted: true }), - * inspect(o2, { sorted: true }), - * ); - * ``` - * - * The `numericSeparator` option adds an underscore every three digits to all - * numbers. - * - * ```js - * const { inspect } = require('node:util'); - * - * const thousand = 1_000; - * const million = 1_000_000; - * const bigNumber = 123_456_789n; - * const bigDecimal = 1_234.123_45; - * - * console.log(inspect(thousand, { numericSeparator: true })); - * // 1_000 - * console.log(inspect(million, { numericSeparator: true })); - * // 1_000_000 - * console.log(inspect(bigNumber, { numericSeparator: true })); - * // 123_456_789n - * console.log(inspect(bigDecimal, { numericSeparator: true })); - * // 1_234.123_45 - * ``` - * - * `util.inspect()` is a synchronous method intended for debugging. Its maximum - * output length is approximately 128 MiB. Inputs that result in longer output will - * be truncated. - * @since v0.3.0 - * @param object Any JavaScript primitive or `Object`. - * @return The representation of `object`. - */ - export function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; - export function inspect(object: any, options?: InspectOptions): string; - export namespace inspect { - let colors: NodeJS.Dict<[number, number]>; - let styles: { - [K in Style]: string; - }; - let defaultOptions: InspectOptions; - /** - * Allows changing inspect settings from the repl. - */ - let replDefaults: InspectOptions; - /** - * That can be used to declare custom inspect functions. - */ - const custom: unique symbol; - } - /** - * Alias for [`Array.isArray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray). - * - * Returns `true` if the given `object` is an `Array`. Otherwise, returns `false`. - * - * ```js - * const util = require('node:util'); - * - * util.isArray([]); - * // Returns: true - * util.isArray(new Array()); - * // Returns: true - * util.isArray({}); - * // Returns: false - * ``` - * @since v0.6.0 - * @deprecated Since v4.0.0 - Use `isArray` instead. - */ - export function isArray(object: unknown): object is unknown[]; - /** - * Returns `true` if the given `object` is a `RegExp`. Otherwise, returns `false`. - * - * ```js - * const util = require('node:util'); - * - * util.isRegExp(/some regexp/); - * // Returns: true - * util.isRegExp(new RegExp('another regexp')); - * // Returns: true - * util.isRegExp({}); - * // Returns: false - * ``` - * @since v0.6.0 - * @deprecated Since v4.0.0 - Deprecated - */ - export function isRegExp(object: unknown): object is RegExp; - /** - * Returns `true` if the given `object` is a `Date`. Otherwise, returns `false`. - * - * ```js - * const util = require('node:util'); - * - * util.isDate(new Date()); - * // Returns: true - * util.isDate(Date()); - * // false (without 'new' returns a String) - * util.isDate({}); - * // Returns: false - * ``` - * @since v0.6.0 - * @deprecated Since v4.0.0 - Use {@link types.isDate} instead. - */ - export function isDate(object: unknown): object is Date; - /** - * Returns `true` if the given `object` is an `Error`. Otherwise, returns`false`. - * - * ```js - * const util = require('node:util'); - * - * util.isError(new Error()); - * // Returns: true - * util.isError(new TypeError()); - * // Returns: true - * util.isError({ name: 'Error', message: 'an error occurred' }); - * // Returns: false - * ``` - * - * This method relies on `Object.prototype.toString()` behavior. It is - * possible to obtain an incorrect result when the `object` argument manipulates`@@toStringTag`. - * - * ```js - * const util = require('node:util'); - * const obj = { name: 'Error', message: 'an error occurred' }; - * - * util.isError(obj); - * // Returns: false - * obj[Symbol.toStringTag] = 'Error'; - * util.isError(obj); - * // Returns: true - * ``` - * @since v0.6.0 - * @deprecated Since v4.0.0 - Use {@link types.isNativeError} instead. - */ - export function isError(object: unknown): object is Error; - /** - * Usage of `util.inherits()` is discouraged. Please use the ES6 `class` and`extends` keywords to get language level inheritance support. Also note - * that the two styles are [semantically incompatible](https://github.com/nodejs/node/issues/4179). - * - * Inherit the prototype methods from one [constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor) into another. The - * prototype of `constructor` will be set to a new object created from`superConstructor`. - * - * This mainly adds some input validation on top of`Object.setPrototypeOf(constructor.prototype, superConstructor.prototype)`. - * As an additional convenience, `superConstructor` will be accessible - * through the `constructor.super_` property. - * - * ```js - * const util = require('node:util'); - * const EventEmitter = require('node:events'); - * - * function MyStream() { - * EventEmitter.call(this); - * } - * - * util.inherits(MyStream, EventEmitter); - * - * MyStream.prototype.write = function(data) { - * this.emit('data', data); - * }; - * - * const stream = new MyStream(); - * - * console.log(stream instanceof EventEmitter); // true - * console.log(MyStream.super_ === EventEmitter); // true - * - * stream.on('data', (data) => { - * console.log(`Received data: "${data}"`); - * }); - * stream.write('It works!'); // Received data: "It works!" - * ``` - * - * ES6 example using `class` and `extends`: - * - * ```js - * const EventEmitter = require('node:events'); - * - * class MyStream extends EventEmitter { - * write(data) { - * this.emit('data', data); - * } - * } - * - * const stream = new MyStream(); - * - * stream.on('data', (data) => { - * console.log(`Received data: "${data}"`); - * }); - * stream.write('With ES6'); - * ``` - * @since v0.3.0 - * @legacy Use ES2015 class syntax and `extends` keyword instead. - */ - export function inherits(constructor: unknown, superConstructor: unknown): void; - export type DebugLoggerFunction = (msg: string, ...param: unknown[]) => void; - export interface DebugLogger extends DebugLoggerFunction { - enabled: boolean; - } - /** - * The `util.debuglog()` method is used to create a function that conditionally - * writes debug messages to `stderr` based on the existence of the `NODE_DEBUG`environment variable. If the `section` name appears within the value of that - * environment variable, then the returned function operates similar to `console.error()`. If not, then the returned function is a no-op. - * - * ```js - * const util = require('node:util'); - * const debuglog = util.debuglog('foo'); - * - * debuglog('hello from foo [%d]', 123); - * ``` - * - * If this program is run with `NODE_DEBUG=foo` in the environment, then - * it will output something like: - * - * ```console - * FOO 3245: hello from foo [123] - * ``` - * - * where `3245` is the process id. If it is not run with that - * environment variable set, then it will not print anything. - * - * The `section` supports wildcard also: - * - * ```js - * const util = require('node:util'); - * const debuglog = util.debuglog('foo-bar'); - * - * debuglog('hi there, it\'s foo-bar [%d]', 2333); - * ``` - * - * if it is run with `NODE_DEBUG=foo*` in the environment, then it will output - * something like: - * - * ```console - * FOO-BAR 3257: hi there, it's foo-bar [2333] - * ``` - * - * Multiple comma-separated `section` names may be specified in the `NODE_DEBUG`environment variable: `NODE_DEBUG=fs,net,tls`. - * - * The optional `callback` argument can be used to replace the logging function - * with a different function that doesn't have any initialization or - * unnecessary wrapping. - * - * ```js - * const util = require('node:util'); - * let debuglog = util.debuglog('internals', (debug) => { - * // Replace with a logging function that optimizes out - * // testing if the section is enabled - * debuglog = debug; - * }); - * ``` - * @since v0.11.3 - * @param section A string identifying the portion of the application for which the `debuglog` function is being created. - * @param callback A callback invoked the first time the logging function is called with a function argument that is a more optimized logging function. - * @return The logging function - */ - export function debuglog(section: string, callback?: (fn: DebugLoggerFunction) => void): DebugLogger; - export const debug: typeof debuglog; - /** - * Returns `true` if the given `object` is a `Boolean`. Otherwise, returns `false`. - * - * ```js - * const util = require('node:util'); - * - * util.isBoolean(1); - * // Returns: false - * util.isBoolean(0); - * // Returns: false - * util.isBoolean(false); - * // Returns: true - * ``` - * @since v0.11.5 - * @deprecated Since v4.0.0 - Use `typeof value === 'boolean'` instead. - */ - export function isBoolean(object: unknown): object is boolean; - /** - * Returns `true` if the given `object` is a `Buffer`. Otherwise, returns `false`. - * - * ```js - * const util = require('node:util'); - * - * util.isBuffer({ length: 0 }); - * // Returns: false - * util.isBuffer([]); - * // Returns: false - * util.isBuffer(Buffer.from('hello world')); - * // Returns: true - * ``` - * @since v0.11.5 - * @deprecated Since v4.0.0 - Use `isBuffer` instead. - */ - export function isBuffer(object: unknown): object is Buffer; - /** - * Returns `true` if the given `object` is a `Function`. Otherwise, returns`false`. - * - * ```js - * const util = require('node:util'); - * - * function Foo() {} - * const Bar = () => {}; - * - * util.isFunction({}); - * // Returns: false - * util.isFunction(Foo); - * // Returns: true - * util.isFunction(Bar); - * // Returns: true - * ``` - * @since v0.11.5 - * @deprecated Since v4.0.0 - Use `typeof value === 'function'` instead. - */ - export function isFunction(object: unknown): boolean; - /** - * Returns `true` if the given `object` is strictly `null`. Otherwise, returns`false`. - * - * ```js - * const util = require('node:util'); - * - * util.isNull(0); - * // Returns: false - * util.isNull(undefined); - * // Returns: false - * util.isNull(null); - * // Returns: true - * ``` - * @since v0.11.5 - * @deprecated Since v4.0.0 - Use `value === null` instead. - */ - export function isNull(object: unknown): object is null; - /** - * Returns `true` if the given `object` is `null` or `undefined`. Otherwise, - * returns `false`. - * - * ```js - * const util = require('node:util'); - * - * util.isNullOrUndefined(0); - * // Returns: false - * util.isNullOrUndefined(undefined); - * // Returns: true - * util.isNullOrUndefined(null); - * // Returns: true - * ``` - * @since v0.11.5 - * @deprecated Since v4.0.0 - Use `value === undefined || value === null` instead. - */ - export function isNullOrUndefined(object: unknown): object is null | undefined; - /** - * Returns `true` if the given `object` is a `Number`. Otherwise, returns `false`. - * - * ```js - * const util = require('node:util'); - * - * util.isNumber(false); - * // Returns: false - * util.isNumber(Infinity); - * // Returns: true - * util.isNumber(0); - * // Returns: true - * util.isNumber(NaN); - * // Returns: true - * ``` - * @since v0.11.5 - * @deprecated Since v4.0.0 - Use `typeof value === 'number'` instead. - */ - export function isNumber(object: unknown): object is number; - /** - * Returns `true` if the given `object` is strictly an `Object`**and** not a`Function` (even though functions are objects in JavaScript). - * Otherwise, returns `false`. - * - * ```js - * const util = require('node:util'); - * - * util.isObject(5); - * // Returns: false - * util.isObject(null); - * // Returns: false - * util.isObject({}); - * // Returns: true - * util.isObject(() => {}); - * // Returns: false - * ``` - * @since v0.11.5 - * @deprecated Since v4.0.0 - Use `value !== null && typeof value === 'object'` instead. - */ - export function isObject(object: unknown): boolean; - /** - * Returns `true` if the given `object` is a primitive type. Otherwise, returns`false`. - * - * ```js - * const util = require('node:util'); - * - * util.isPrimitive(5); - * // Returns: true - * util.isPrimitive('foo'); - * // Returns: true - * util.isPrimitive(false); - * // Returns: true - * util.isPrimitive(null); - * // Returns: true - * util.isPrimitive(undefined); - * // Returns: true - * util.isPrimitive({}); - * // Returns: false - * util.isPrimitive(() => {}); - * // Returns: false - * util.isPrimitive(/^$/); - * // Returns: false - * util.isPrimitive(new Date()); - * // Returns: false - * ``` - * @since v0.11.5 - * @deprecated Since v4.0.0 - Use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. - */ - export function isPrimitive(object: unknown): boolean; - /** - * Returns `true` if the given `object` is a `string`. Otherwise, returns `false`. - * - * ```js - * const util = require('node:util'); - * - * util.isString(''); - * // Returns: true - * util.isString('foo'); - * // Returns: true - * util.isString(String('foo')); - * // Returns: true - * util.isString(5); - * // Returns: false - * ``` - * @since v0.11.5 - * @deprecated Since v4.0.0 - Use `typeof value === 'string'` instead. - */ - export function isString(object: unknown): object is string; - /** - * Returns `true` if the given `object` is a `Symbol`. Otherwise, returns `false`. - * - * ```js - * const util = require('node:util'); - * - * util.isSymbol(5); - * // Returns: false - * util.isSymbol('foo'); - * // Returns: false - * util.isSymbol(Symbol('foo')); - * // Returns: true - * ``` - * @since v0.11.5 - * @deprecated Since v4.0.0 - Use `typeof value === 'symbol'` instead. - */ - export function isSymbol(object: unknown): object is symbol; - /** - * Returns `true` if the given `object` is `undefined`. Otherwise, returns `false`. - * - * ```js - * const util = require('node:util'); - * - * const foo = undefined; - * util.isUndefined(5); - * // Returns: false - * util.isUndefined(foo); - * // Returns: true - * util.isUndefined(null); - * // Returns: false - * ``` - * @since v0.11.5 - * @deprecated Since v4.0.0 - Use `value === undefined` instead. - */ - export function isUndefined(object: unknown): object is undefined; - /** - * The `util.deprecate()` method wraps `fn` (which may be a function or class) in - * such a way that it is marked as deprecated. - * - * ```js - * const util = require('node:util'); - * - * exports.obsoleteFunction = util.deprecate(() => { - * // Do something here. - * }, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.'); - * ``` - * - * When called, `util.deprecate()` will return a function that will emit a`DeprecationWarning` using the `'warning'` event. The warning will - * be emitted and printed to `stderr` the first time the returned function is - * called. After the warning is emitted, the wrapped function is called without - * emitting a warning. - * - * If the same optional `code` is supplied in multiple calls to `util.deprecate()`, - * the warning will be emitted only once for that `code`. - * - * ```js - * const util = require('node:util'); - * - * const fn1 = util.deprecate(someFunction, someMessage, 'DEP0001'); - * const fn2 = util.deprecate(someOtherFunction, someOtherMessage, 'DEP0001'); - * fn1(); // Emits a deprecation warning with code DEP0001 - * fn2(); // Does not emit a deprecation warning because it has the same code - * ``` - * - * If either the `--no-deprecation` or `--no-warnings` command-line flags are - * used, or if the `process.noDeprecation` property is set to `true`_prior_ to - * the first deprecation warning, the `util.deprecate()` method does nothing. - * - * If the `--trace-deprecation` or `--trace-warnings` command-line flags are set, - * or the `process.traceDeprecation` property is set to `true`, a warning and a - * stack trace are printed to `stderr` the first time the deprecated function is - * called. - * - * If the `--throw-deprecation` command-line flag is set, or the`process.throwDeprecation` property is set to `true`, then an exception will be - * thrown when the deprecated function is called. - * - * The `--throw-deprecation` command-line flag and `process.throwDeprecation`property take precedence over `--trace-deprecation` and`process.traceDeprecation`. - * @since v0.8.0 - * @param fn The function that is being deprecated. - * @param msg A warning message to display when the deprecated function is invoked. - * @param code A deprecation code. See the `list of deprecated APIs` for a list of codes. - * @return The deprecated function wrapped to emit a warning. - */ - export function deprecate(fn: T, msg: string, code?: string): T; - /** - * Returns `true` if there is deep strict equality between `val1` and `val2`. - * Otherwise, returns `false`. - * - * See `assert.deepStrictEqual()` for more information about deep strict - * equality. - * @since v9.0.0 - */ - export function isDeepStrictEqual(val1: unknown, val2: unknown): boolean; - /** - * Returns `str` with any ANSI escape codes removed. - * - * ```js - * console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m')); - * // Prints "value" - * ``` - * @since v16.11.0 - */ - export function stripVTControlCharacters(str: string): string; - /** - * Takes an `async` function (or a function that returns a `Promise`) and returns a - * function following the error-first callback style, i.e. taking - * an `(err, value) => ...` callback as the last argument. In the callback, the - * first argument will be the rejection reason (or `null` if the `Promise`resolved), and the second argument will be the resolved value. - * - * ```js - * const util = require('node:util'); - * - * async function fn() { - * return 'hello world'; - * } - * const callbackFunction = util.callbackify(fn); - * - * callbackFunction((err, ret) => { - * if (err) throw err; - * console.log(ret); - * }); - * ``` - * - * Will print: - * - * ```text - * hello world - * ``` - * - * The callback is executed asynchronously, and will have a limited stack trace. - * If the callback throws, the process will emit an `'uncaughtException'` event, and if not handled will exit. - * - * Since `null` has a special meaning as the first argument to a callback, if a - * wrapped function rejects a `Promise` with a falsy value as a reason, the value - * is wrapped in an `Error` with the original value stored in a field named`reason`. - * - * ```js - * function fn() { - * return Promise.reject(null); - * } - * const callbackFunction = util.callbackify(fn); - * - * callbackFunction((err, ret) => { - * // When the Promise was rejected with `null` it is wrapped with an Error and - * // the original value is stored in `reason`. - * err && Object.hasOwn(err, 'reason') && err.reason === null; // true - * }); - * ``` - * @since v8.2.0 - * @param fn An `async` function - * @return a callback style function - */ - export function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; - export function callbackify( - fn: () => Promise, - ): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; - export function callbackify( - fn: (arg1: T1) => Promise, - ): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; - export function callbackify( - fn: (arg1: T1) => Promise, - ): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; - export function callbackify( - fn: (arg1: T1, arg2: T2) => Promise, - ): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; - export function callbackify( - fn: (arg1: T1, arg2: T2) => Promise, - ): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - export function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3) => Promise, - ): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; - export function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3) => Promise, - ): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - export function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; - export function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise, - ): ( - arg1: T1, - arg2: T2, - arg3: T3, - arg4: T4, - callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, - ) => void; - export function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; - export function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, - ): ( - arg1: T1, - arg2: T2, - arg3: T3, - arg4: T4, - arg5: T5, - callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, - ) => void; - export function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, - ): ( - arg1: T1, - arg2: T2, - arg3: T3, - arg4: T4, - arg5: T5, - arg6: T6, - callback: (err: NodeJS.ErrnoException) => void, - ) => void; - export function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, - ): ( - arg1: T1, - arg2: T2, - arg3: T3, - arg4: T4, - arg5: T5, - arg6: T6, - callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, - ) => void; - export interface CustomPromisifyLegacy extends Function { - __promisify__: TCustom; - } - export interface CustomPromisifySymbol extends Function { - [promisify.custom]: TCustom; - } - export type CustomPromisify = - | CustomPromisifySymbol - | CustomPromisifyLegacy; - /** - * Takes a function following the common error-first callback style, i.e. taking - * an `(err, value) => ...` callback as the last argument, and returns a version - * that returns promises. - * - * ```js - * const util = require('node:util'); - * const fs = require('node:fs'); - * - * const stat = util.promisify(fs.stat); - * stat('.').then((stats) => { - * // Do something with `stats` - * }).catch((error) => { - * // Handle the error. - * }); - * ``` - * - * Or, equivalently using `async function`s: - * - * ```js - * const util = require('node:util'); - * const fs = require('node:fs'); - * - * const stat = util.promisify(fs.stat); - * - * async function callStat() { - * const stats = await stat('.'); - * console.log(`This directory is owned by ${stats.uid}`); - * } - * - * callStat(); - * ``` - * - * If there is an `original[util.promisify.custom]` property present, `promisify`will return its value, see `Custom promisified functions`. - * - * `promisify()` assumes that `original` is a function taking a callback as its - * final argument in all cases. If `original` is not a function, `promisify()`will throw an error. If `original` is a function but its last argument is not - * an error-first callback, it will still be passed an error-first - * callback as its last argument. - * - * Using `promisify()` on class methods or other methods that use `this` may not - * work as expected unless handled specially: - * - * ```js - * const util = require('node:util'); - * - * class Foo { - * constructor() { - * this.a = 42; - * } - * - * bar(callback) { - * callback(null, this.a); - * } - * } - * - * const foo = new Foo(); - * - * const naiveBar = util.promisify(foo.bar); - * // TypeError: Cannot read property 'a' of undefined - * // naiveBar().then(a => console.log(a)); - * - * naiveBar.call(foo).then((a) => console.log(a)); // '42' - * - * const bindBar = naiveBar.bind(foo); - * bindBar().then((a) => console.log(a)); // '42' - * ``` - * @since v8.0.0 - */ - export function promisify(fn: CustomPromisify): TCustom; - export function promisify( - fn: (callback: (err: any, result: TResult) => void) => void, - ): () => Promise; - export function promisify(fn: (callback: (err?: any) => void) => void): () => Promise; - export function promisify( - fn: (arg1: T1, callback: (err: any, result: TResult) => void) => void, - ): (arg1: T1) => Promise; - export function promisify(fn: (arg1: T1, callback: (err?: any) => void) => void): (arg1: T1) => Promise; - export function promisify( - fn: (arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void, - ): (arg1: T1, arg2: T2) => Promise; - export function promisify( - fn: (arg1: T1, arg2: T2, callback: (err?: any) => void) => void, - ): (arg1: T1, arg2: T2) => Promise; - export function promisify( - fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void, - ): (arg1: T1, arg2: T2, arg3: T3) => Promise; - export function promisify( - fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void, - ): (arg1: T1, arg2: T2, arg3: T3) => Promise; - export function promisify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; - export function promisify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; - export function promisify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; - export function promisify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; - export function promisify(fn: Function): Function; - export namespace promisify { - /** - * That can be used to declare custom promisified variants of functions. - */ - const custom: unique symbol; - } - /** - * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextDecoder` API. - * - * ```js - * const decoder = new TextDecoder(); - * const u8arr = new Uint8Array([72, 101, 108, 108, 111]); - * console.log(decoder.decode(u8arr)); // Hello - * ``` - * @since v8.3.0 - */ - export class TextDecoder { - /** - * The encoding supported by the `TextDecoder` instance. - */ - readonly encoding: string; - /** - * The value will be `true` if decoding errors result in a `TypeError` being - * thrown. - */ - readonly fatal: boolean; - /** - * The value will be `true` if the decoding result will include the byte order - * mark. - */ - readonly ignoreBOM: boolean; - constructor( - encoding?: string, - options?: { - fatal?: boolean | undefined; - ignoreBOM?: boolean | undefined; - }, - ); - /** - * Decodes the `input` and returns a string. If `options.stream` is `true`, any - * incomplete byte sequences occurring at the end of the `input` are buffered - * internally and emitted after the next call to `textDecoder.decode()`. - * - * If `textDecoder.fatal` is `true`, decoding errors that occur will result in a`TypeError` being thrown. - * @param input An `ArrayBuffer`, `DataView`, or `TypedArray` instance containing the encoded data. - */ - decode( - input?: NodeJS.ArrayBufferView | ArrayBuffer | null, - options?: { - stream?: boolean | undefined; - }, - ): string; - } - export interface EncodeIntoResult { - /** - * The read Unicode code units of input. - */ - read: number; - /** - * The written UTF-8 bytes of output. - */ - written: number; - } - export { types }; - - //// TextEncoder/Decoder - /** - * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextEncoder` API. All - * instances of `TextEncoder` only support UTF-8 encoding. - * - * ```js - * const encoder = new TextEncoder(); - * const uint8array = encoder.encode('this is some data'); - * ``` - * - * The `TextEncoder` class is also available on the global object. - * @since v8.3.0 - */ - export class TextEncoder { - /** - * The encoding supported by the `TextEncoder` instance. Always set to `'utf-8'`. - */ - readonly encoding: string; - /** - * UTF-8 encodes the `input` string and returns a `Uint8Array` containing the - * encoded bytes. - * @param [input='an empty string'] The text to encode. - */ - encode(input?: string): Uint8Array; - /** - * UTF-8 encodes the `src` string to the `dest` Uint8Array and returns an object - * containing the read Unicode code units and written UTF-8 bytes. - * - * ```js - * const encoder = new TextEncoder(); - * const src = 'this is some data'; - * const dest = new Uint8Array(10); - * const { read, written } = encoder.encodeInto(src, dest); - * ``` - * @param src The text to encode. - * @param dest The array to hold the encode result. - */ - encodeInto(src: string, dest: Uint8Array): EncodeIntoResult; - } - import { TextDecoder as _TextDecoder, TextEncoder as _TextEncoder } from "util"; - global { - /** - * `TextDecoder` class is a global reference for `require('util').TextDecoder` - * https://nodejs.org/api/globals.html#textdecoder - * @since v11.0.0 - */ - var TextDecoder: typeof globalThis extends { - onmessage: any; - TextDecoder: infer TextDecoder; - } ? TextDecoder - : typeof _TextDecoder; - /** - * `TextEncoder` class is a global reference for `require('util').TextEncoder` - * https://nodejs.org/api/globals.html#textencoder - * @since v11.0.0 - */ - var TextEncoder: typeof globalThis extends { - onmessage: any; - TextEncoder: infer TextEncoder; - } ? TextEncoder - : typeof _TextEncoder; - } - - //// parseArgs - /** - * Provides a higher level API for command-line argument parsing than interacting - * with `process.argv` directly. Takes a specification for the expected arguments - * and returns a structured object with the parsed options and positionals. - * - * ```js - * import { parseArgs } from 'node:util'; - * const args = ['-f', '--bar', 'b']; - * const options = { - * foo: { - * type: 'boolean', - * short: 'f', - * }, - * bar: { - * type: 'string', - * }, - * }; - * const { - * values, - * positionals, - * } = parseArgs({ args, options }); - * console.log(values, positionals); - * // Prints: [Object: null prototype] { foo: true, bar: 'b' } [] - * ``` - * @since v18.3.0, v16.17.0 - * @param config Used to provide arguments for parsing and to configure the parser. `config` supports the following properties: - * @return The parsed command line arguments: - */ - export function parseArgs(config?: T): ParsedResults; - interface ParseArgsOptionConfig { - /** - * Type of argument. - */ - type: "string" | "boolean"; - /** - * Whether this option can be provided multiple times. - * If `true`, all values will be collected in an array. - * If `false`, values for the option are last-wins. - * @default false. - */ - multiple?: boolean | undefined; - /** - * A single character alias for the option. - */ - short?: string | undefined; - /** - * The default option value when it is not set by args. - * It must be of the same type as the the `type` property. - * When `multiple` is `true`, it must be an array. - * @since v18.11.0 - */ - default?: string | boolean | string[] | boolean[] | undefined; - } - interface ParseArgsOptionsConfig { - [longOption: string]: ParseArgsOptionConfig; - } - export interface ParseArgsConfig { - /** - * Array of argument strings. - */ - args?: string[] | undefined; - /** - * Used to describe arguments known to the parser. - */ - options?: ParseArgsOptionsConfig | undefined; - /** - * Should an error be thrown when unknown arguments are encountered, - * or when arguments are passed that do not match the `type` configured in `options`. - * @default true - */ - strict?: boolean | undefined; - /** - * Whether this command accepts positional arguments. - */ - allowPositionals?: boolean | undefined; - /** - * Return the parsed tokens. This is useful for extending the built-in behavior, - * from adding additional checks through to reprocessing the tokens in different ways. - * @default false - */ - tokens?: boolean | undefined; - } - /* - IfDefaultsTrue and IfDefaultsFalse are helpers to handle default values for missing boolean properties. - TypeScript does not have exact types for objects: https://github.com/microsoft/TypeScript/issues/12936 - This means it is impossible to distinguish between "field X is definitely not present" and "field X may or may not be present". - But we expect users to generally provide their config inline or `as const`, which means TS will always know whether a given field is present. - So this helper treats "not definitely present" (i.e., not `extends boolean`) as being "definitely not present", i.e. it should have its default value. - This is technically incorrect but is a much nicer UX for the common case. - The IfDefaultsTrue version is for things which default to true; the IfDefaultsFalse version is for things which default to false. - */ - type IfDefaultsTrue = T extends true ? IfTrue - : T extends false ? IfFalse - : IfTrue; - - // we put the `extends false` condition first here because `undefined` compares like `any` when `strictNullChecks: false` - type IfDefaultsFalse = T extends false ? IfFalse - : T extends true ? IfTrue - : IfFalse; - - type ExtractOptionValue = IfDefaultsTrue< - T["strict"], - O["type"] extends "string" ? string : O["type"] extends "boolean" ? boolean : string | boolean, - string | boolean - >; - - type ParsedValues = - & IfDefaultsTrue - & (T["options"] extends ParseArgsOptionsConfig ? { - -readonly [LongOption in keyof T["options"]]: IfDefaultsFalse< - T["options"][LongOption]["multiple"], - undefined | Array>, - undefined | ExtractOptionValue - >; - } - : {}); - - type ParsedPositionals = IfDefaultsTrue< - T["strict"], - IfDefaultsFalse, - IfDefaultsTrue - >; - - type PreciseTokenForOptions< - K extends string, - O extends ParseArgsOptionConfig, - > = O["type"] extends "string" ? { - kind: "option"; - index: number; - name: K; - rawName: string; - value: string; - inlineValue: boolean; - } - : O["type"] extends "boolean" ? { - kind: "option"; - index: number; - name: K; - rawName: string; - value: undefined; - inlineValue: undefined; - } - : OptionToken & { name: K }; - - type TokenForOptions< - T extends ParseArgsConfig, - K extends keyof T["options"] = keyof T["options"], - > = K extends unknown - ? T["options"] extends ParseArgsOptionsConfig ? PreciseTokenForOptions - : OptionToken - : never; - - type ParsedOptionToken = IfDefaultsTrue, OptionToken>; - - type ParsedPositionalToken = IfDefaultsTrue< - T["strict"], - IfDefaultsFalse, - IfDefaultsTrue - >; - - type ParsedTokens = Array< - ParsedOptionToken | ParsedPositionalToken | { kind: "option-terminator"; index: number } - >; - - type PreciseParsedResults = IfDefaultsFalse< - T["tokens"], - { - values: ParsedValues; - positionals: ParsedPositionals; - tokens: ParsedTokens; - }, - { - values: ParsedValues; - positionals: ParsedPositionals; - } - >; - - type OptionToken = - | { kind: "option"; index: number; name: string; rawName: string; value: string; inlineValue: boolean } - | { - kind: "option"; - index: number; - name: string; - rawName: string; - value: undefined; - inlineValue: undefined; - }; - - type Token = - | OptionToken - | { kind: "positional"; index: number; value: string } - | { kind: "option-terminator"; index: number }; - - // If ParseArgsConfig extends T, then the user passed config constructed elsewhere. - // So we can't rely on the `"not definitely present" implies "definitely not present"` assumption mentioned above. - type ParsedResults = ParseArgsConfig extends T ? { - values: { - [longOption: string]: undefined | string | boolean | Array; - }; - positionals: string[]; - tokens?: Token[]; - } - : PreciseParsedResults; - - /** - * An implementation of [the MIMEType class](https://bmeck.github.io/node-proposal-mime-api/). - * - * In accordance with browser conventions, all properties of `MIMEType` objects - * are implemented as getters and setters on the class prototype, rather than as - * data properties on the object itself. - * - * A MIME string is a structured string containing multiple meaningful - * components. When parsed, a `MIMEType` object is returned containing - * properties for each of these components. - * @since v19.1.0, v18.13.0 - * @experimental - */ - export class MIMEType { - /** - * Creates a new MIMEType object by parsing the input. - * - * A `TypeError` will be thrown if the `input` is not a valid MIME. - * Note that an effort will be made to coerce the given values into strings. - * @param input The input MIME to parse. - */ - constructor(input: string | { toString: () => string }); - - /** - * Gets and sets the type portion of the MIME. - * - * ```js - * import { MIMEType } from 'node:util'; - * - * const myMIME = new MIMEType('text/javascript'); - * console.log(myMIME.type); - * // Prints: text - * myMIME.type = 'application'; - * console.log(myMIME.type); - * // Prints: application - * console.log(String(myMIME)); - * // Prints: application/javascript - * ``` - */ - type: string; - /** - * Gets and sets the subtype portion of the MIME. - * - * ```js - * import { MIMEType } from 'node:util'; - * - * const myMIME = new MIMEType('text/ecmascript'); - * console.log(myMIME.subtype); - * // Prints: ecmascript - * myMIME.subtype = 'javascript'; - * console.log(myMIME.subtype); - * // Prints: javascript - * console.log(String(myMIME)); - * // Prints: text/javascript - * ``` - */ - subtype: string; - /** - * Gets the essence of the MIME. This property is read only. - * Use `mime.type` or `mime.subtype` to alter the MIME. - * - * ```js - * import { MIMEType } from 'node:util'; - * - * const myMIME = new MIMEType('text/javascript;key=value'); - * console.log(myMIME.essence); - * // Prints: text/javascript - * myMIME.type = 'application'; - * console.log(myMIME.essence); - * // Prints: application/javascript - * console.log(String(myMIME)); - * // Prints: application/javascript;key=value - * ``` - */ - readonly essence: string; - /** - * Gets the `MIMEParams` object representing the - * parameters of the MIME. This property is read-only. See `MIMEParams` documentation for details. - */ - readonly params: MIMEParams; - /** - * The `toString()` method on the `MIMEType` object returns the serialized MIME. - * - * Because of the need for standard compliance, this method does not allow users - * to customize the serialization process of the MIME. - */ - toString(): string; - } - /** - * The `MIMEParams` API provides read and write access to the parameters of a`MIMEType`. - * @since v19.1.0, v18.13.0 - */ - export class MIMEParams { - /** - * Remove all name-value pairs whose name is `name`. - */ - delete(name: string): void; - /** - * Returns an iterator over each of the name-value pairs in the parameters. - * Each item of the iterator is a JavaScript `Array`. The first item of the array - * is the `name`, the second item of the array is the `value`. - */ - entries(): IterableIterator<[string, string]>; - /** - * Returns the value of the first name-value pair whose name is `name`. If there - * are no such pairs, `null` is returned. - * @return or `null` if there is no name-value pair with the given `name`. - */ - get(name: string): string | null; - /** - * Returns `true` if there is at least one name-value pair whose name is `name`. - */ - has(name: string): boolean; - /** - * Returns an iterator over the names of each name-value pair. - * - * ```js - * import { MIMEType } from 'node:util'; - * - * const { params } = new MIMEType('text/plain;foo=0;bar=1'); - * for (const name of params.keys()) { - * console.log(name); - * } - * // Prints: - * // foo - * // bar - * ``` - */ - keys(): IterableIterator; - /** - * Sets the value in the `MIMEParams` object associated with `name` to`value`. If there are any pre-existing name-value pairs whose names are `name`, - * set the first such pair's value to `value`. - * - * ```js - * import { MIMEType } from 'node:util'; - * - * const { params } = new MIMEType('text/plain;foo=0;bar=1'); - * params.set('foo', 'def'); - * params.set('baz', 'xyz'); - * console.log(params.toString()); - * // Prints: foo=def;bar=1;baz=xyz - * ``` - */ - set(name: string, value: string): void; - /** - * Returns an iterator over the values of each name-value pair. - */ - values(): IterableIterator; - /** - * Returns an iterator over each of the name-value pairs in the parameters. - */ - [Symbol.iterator]: typeof MIMEParams.prototype.entries; - } -} -declare module "util/types" { - import { KeyObject, webcrypto } from "node:crypto"; - /** - * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) or - * [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. - * - * See also `util.types.isArrayBuffer()` and `util.types.isSharedArrayBuffer()`. - * - * ```js - * util.types.isAnyArrayBuffer(new ArrayBuffer()); // Returns true - * util.types.isAnyArrayBuffer(new SharedArrayBuffer()); // Returns true - * ``` - * @since v10.0.0 - */ - function isAnyArrayBuffer(object: unknown): object is ArrayBufferLike; - /** - * Returns `true` if the value is an `arguments` object. - * - * ```js - * function foo() { - * util.types.isArgumentsObject(arguments); // Returns true - * } - * ``` - * @since v10.0.0 - */ - function isArgumentsObject(object: unknown): object is IArguments; - /** - * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instance. - * This does _not_ include [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instances. Usually, it is - * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. - * - * ```js - * util.types.isArrayBuffer(new ArrayBuffer()); // Returns true - * util.types.isArrayBuffer(new SharedArrayBuffer()); // Returns false - * ``` - * @since v10.0.0 - */ - function isArrayBuffer(object: unknown): object is ArrayBuffer; - /** - * Returns `true` if the value is an instance of one of the [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) views, such as typed - * array objects or [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView). Equivalent to - * [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). - * - * ```js - * util.types.isArrayBufferView(new Int8Array()); // true - * util.types.isArrayBufferView(Buffer.from('hello world')); // true - * util.types.isArrayBufferView(new DataView(new ArrayBuffer(16))); // true - * util.types.isArrayBufferView(new ArrayBuffer()); // false - * ``` - * @since v10.0.0 - */ - function isArrayBufferView(object: unknown): object is NodeJS.ArrayBufferView; - /** - * Returns `true` if the value is an [async function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). - * This only reports back what the JavaScript engine is seeing; - * in particular, the return value may not match the original source code if - * a transpilation tool was used. - * - * ```js - * util.types.isAsyncFunction(function foo() {}); // Returns false - * util.types.isAsyncFunction(async function foo() {}); // Returns true - * ``` - * @since v10.0.0 - */ - function isAsyncFunction(object: unknown): boolean; - /** - * Returns `true` if the value is a `BigInt64Array` instance. - * - * ```js - * util.types.isBigInt64Array(new BigInt64Array()); // Returns true - * util.types.isBigInt64Array(new BigUint64Array()); // Returns false - * ``` - * @since v10.0.0 - */ - function isBigInt64Array(value: unknown): value is BigInt64Array; - /** - * Returns `true` if the value is a `BigUint64Array` instance. - * - * ```js - * util.types.isBigUint64Array(new BigInt64Array()); // Returns false - * util.types.isBigUint64Array(new BigUint64Array()); // Returns true - * ``` - * @since v10.0.0 - */ - function isBigUint64Array(value: unknown): value is BigUint64Array; - /** - * Returns `true` if the value is a boolean object, e.g. created - * by `new Boolean()`. - * - * ```js - * util.types.isBooleanObject(false); // Returns false - * util.types.isBooleanObject(true); // Returns false - * util.types.isBooleanObject(new Boolean(false)); // Returns true - * util.types.isBooleanObject(new Boolean(true)); // Returns true - * util.types.isBooleanObject(Boolean(false)); // Returns false - * util.types.isBooleanObject(Boolean(true)); // Returns false - * ``` - * @since v10.0.0 - */ - function isBooleanObject(object: unknown): object is Boolean; - /** - * Returns `true` if the value is any boxed primitive object, e.g. created - * by `new Boolean()`, `new String()` or `Object(Symbol())`. - * - * For example: - * - * ```js - * util.types.isBoxedPrimitive(false); // Returns false - * util.types.isBoxedPrimitive(new Boolean(false)); // Returns true - * util.types.isBoxedPrimitive(Symbol('foo')); // Returns false - * util.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true - * util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true - * ``` - * @since v10.11.0 - */ - function isBoxedPrimitive(object: unknown): object is String | Number | BigInt | Boolean | Symbol; - /** - * Returns `true` if the value is a built-in [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) instance. - * - * ```js - * const ab = new ArrayBuffer(20); - * util.types.isDataView(new DataView(ab)); // Returns true - * util.types.isDataView(new Float64Array()); // Returns false - * ``` - * - * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). - * @since v10.0.0 - */ - function isDataView(object: unknown): object is DataView; - /** - * Returns `true` if the value is a built-in [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) instance. - * - * ```js - * util.types.isDate(new Date()); // Returns true - * ``` - * @since v10.0.0 - */ - function isDate(object: unknown): object is Date; - /** - * Returns `true` if the value is a native `External` value. - * - * A native `External` value is a special type of object that contains a - * raw C++ pointer (`void*`) for access from native code, and has no other - * properties. Such objects are created either by Node.js internals or native - * addons. In JavaScript, they are [frozen](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) objects with a`null` prototype. - * - * ```c - * #include - * #include - * napi_value result; - * static napi_value MyNapi(napi_env env, napi_callback_info info) { - * int* raw = (int*) malloc(1024); - * napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result); - * if (status != napi_ok) { - * napi_throw_error(env, NULL, "napi_create_external failed"); - * return NULL; - * } - * return result; - * } - * ... - * DECLARE_NAPI_PROPERTY("myNapi", MyNapi) - * ... - * ``` - * - * ```js - * const native = require('napi_addon.node'); - * const data = native.myNapi(); - * util.types.isExternal(data); // returns true - * util.types.isExternal(0); // returns false - * util.types.isExternal(new String('foo')); // returns false - * ``` - * - * For further information on `napi_create_external`, refer to `napi_create_external()`. - * @since v10.0.0 - */ - function isExternal(object: unknown): boolean; - /** - * Returns `true` if the value is a built-in [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array) instance. - * - * ```js - * util.types.isFloat32Array(new ArrayBuffer()); // Returns false - * util.types.isFloat32Array(new Float32Array()); // Returns true - * util.types.isFloat32Array(new Float64Array()); // Returns false - * ``` - * @since v10.0.0 - */ - function isFloat32Array(object: unknown): object is Float32Array; - /** - * Returns `true` if the value is a built-in [`Float64Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array) instance. - * - * ```js - * util.types.isFloat64Array(new ArrayBuffer()); // Returns false - * util.types.isFloat64Array(new Uint8Array()); // Returns false - * util.types.isFloat64Array(new Float64Array()); // Returns true - * ``` - * @since v10.0.0 - */ - function isFloat64Array(object: unknown): object is Float64Array; - /** - * Returns `true` if the value is a generator function. - * This only reports back what the JavaScript engine is seeing; - * in particular, the return value may not match the original source code if - * a transpilation tool was used. - * - * ```js - * util.types.isGeneratorFunction(function foo() {}); // Returns false - * util.types.isGeneratorFunction(function* foo() {}); // Returns true - * ``` - * @since v10.0.0 - */ - function isGeneratorFunction(object: unknown): object is GeneratorFunction; - /** - * Returns `true` if the value is a generator object as returned from a - * built-in generator function. - * This only reports back what the JavaScript engine is seeing; - * in particular, the return value may not match the original source code if - * a transpilation tool was used. - * - * ```js - * function* foo() {} - * const generator = foo(); - * util.types.isGeneratorObject(generator); // Returns true - * ``` - * @since v10.0.0 - */ - function isGeneratorObject(object: unknown): object is Generator; - /** - * Returns `true` if the value is a built-in [`Int8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array) instance. - * - * ```js - * util.types.isInt8Array(new ArrayBuffer()); // Returns false - * util.types.isInt8Array(new Int8Array()); // Returns true - * util.types.isInt8Array(new Float64Array()); // Returns false - * ``` - * @since v10.0.0 - */ - function isInt8Array(object: unknown): object is Int8Array; - /** - * Returns `true` if the value is a built-in [`Int16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array) instance. - * - * ```js - * util.types.isInt16Array(new ArrayBuffer()); // Returns false - * util.types.isInt16Array(new Int16Array()); // Returns true - * util.types.isInt16Array(new Float64Array()); // Returns false - * ``` - * @since v10.0.0 - */ - function isInt16Array(object: unknown): object is Int16Array; - /** - * Returns `true` if the value is a built-in [`Int32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array) instance. - * - * ```js - * util.types.isInt32Array(new ArrayBuffer()); // Returns false - * util.types.isInt32Array(new Int32Array()); // Returns true - * util.types.isInt32Array(new Float64Array()); // Returns false - * ``` - * @since v10.0.0 - */ - function isInt32Array(object: unknown): object is Int32Array; - /** - * Returns `true` if the value is a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. - * - * ```js - * util.types.isMap(new Map()); // Returns true - * ``` - * @since v10.0.0 - */ - function isMap( - object: T | {}, - ): object is T extends ReadonlyMap ? (unknown extends T ? never : ReadonlyMap) - : Map; - /** - * Returns `true` if the value is an iterator returned for a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. - * - * ```js - * const map = new Map(); - * util.types.isMapIterator(map.keys()); // Returns true - * util.types.isMapIterator(map.values()); // Returns true - * util.types.isMapIterator(map.entries()); // Returns true - * util.types.isMapIterator(map[Symbol.iterator]()); // Returns true - * ``` - * @since v10.0.0 - */ - function isMapIterator(object: unknown): boolean; - /** - * Returns `true` if the value is an instance of a [Module Namespace Object](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects). - * - * ```js - * import * as ns from './a.js'; - * - * util.types.isModuleNamespaceObject(ns); // Returns true - * ``` - * @since v10.0.0 - */ - function isModuleNamespaceObject(value: unknown): boolean; - /** - * Returns `true` if the value was returned by the constructor of a [built-in `Error` type](https://tc39.es/ecma262/#sec-error-objects). - * - * ```js - * console.log(util.types.isNativeError(new Error())); // true - * console.log(util.types.isNativeError(new TypeError())); // true - * console.log(util.types.isNativeError(new RangeError())); // true - * ``` - * - * Subclasses of the native error types are also native errors: - * - * ```js - * class MyError extends Error {} - * console.log(util.types.isNativeError(new MyError())); // true - * ``` - * - * A value being `instanceof` a native error class is not equivalent to `isNativeError()`returning `true` for that value. `isNativeError()` returns `true` for errors - * which come from a different [realm](https://tc39.es/ecma262/#realm) while `instanceof Error` returns `false`for these errors: - * - * ```js - * const vm = require('node:vm'); - * const context = vm.createContext({}); - * const myError = vm.runInContext('new Error()', context); - * console.log(util.types.isNativeError(myError)); // true - * console.log(myError instanceof Error); // false - * ``` - * - * Conversely, `isNativeError()` returns `false` for all objects which were not - * returned by the constructor of a native error. That includes values - * which are `instanceof` native errors: - * - * ```js - * const myError = { __proto__: Error.prototype }; - * console.log(util.types.isNativeError(myError)); // false - * console.log(myError instanceof Error); // true - * ``` - * @since v10.0.0 - */ - function isNativeError(object: unknown): object is Error; - /** - * Returns `true` if the value is a number object, e.g. created - * by `new Number()`. - * - * ```js - * util.types.isNumberObject(0); // Returns false - * util.types.isNumberObject(new Number(0)); // Returns true - * ``` - * @since v10.0.0 - */ - function isNumberObject(object: unknown): object is Number; - /** - * Returns `true` if the value is a built-in [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). - * - * ```js - * util.types.isPromise(Promise.resolve(42)); // Returns true - * ``` - * @since v10.0.0 - */ - function isPromise(object: unknown): object is Promise; - /** - * Returns `true` if the value is a [`Proxy`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) instance. - * - * ```js - * const target = {}; - * const proxy = new Proxy(target, {}); - * util.types.isProxy(target); // Returns false - * util.types.isProxy(proxy); // Returns true - * ``` - * @since v10.0.0 - */ - function isProxy(object: unknown): boolean; - /** - * Returns `true` if the value is a regular expression object. - * - * ```js - * util.types.isRegExp(/abc/); // Returns true - * util.types.isRegExp(new RegExp('abc')); // Returns true - * ``` - * @since v10.0.0 - */ - function isRegExp(object: unknown): object is RegExp; - /** - * Returns `true` if the value is a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. - * - * ```js - * util.types.isSet(new Set()); // Returns true - * ``` - * @since v10.0.0 - */ - function isSet( - object: T | {}, - ): object is T extends ReadonlySet ? (unknown extends T ? never : ReadonlySet) : Set; - /** - * Returns `true` if the value is an iterator returned for a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. - * - * ```js - * const set = new Set(); - * util.types.isSetIterator(set.keys()); // Returns true - * util.types.isSetIterator(set.values()); // Returns true - * util.types.isSetIterator(set.entries()); // Returns true - * util.types.isSetIterator(set[Symbol.iterator]()); // Returns true - * ``` - * @since v10.0.0 - */ - function isSetIterator(object: unknown): boolean; - /** - * Returns `true` if the value is a built-in [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. - * This does _not_ include [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instances. Usually, it is - * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. - * - * ```js - * util.types.isSharedArrayBuffer(new ArrayBuffer()); // Returns false - * util.types.isSharedArrayBuffer(new SharedArrayBuffer()); // Returns true - * ``` - * @since v10.0.0 - */ - function isSharedArrayBuffer(object: unknown): object is SharedArrayBuffer; - /** - * Returns `true` if the value is a string object, e.g. created - * by `new String()`. - * - * ```js - * util.types.isStringObject('foo'); // Returns false - * util.types.isStringObject(new String('foo')); // Returns true - * ``` - * @since v10.0.0 - */ - function isStringObject(object: unknown): object is String; - /** - * Returns `true` if the value is a symbol object, created - * by calling `Object()` on a `Symbol` primitive. - * - * ```js - * const symbol = Symbol('foo'); - * util.types.isSymbolObject(symbol); // Returns false - * util.types.isSymbolObject(Object(symbol)); // Returns true - * ``` - * @since v10.0.0 - */ - function isSymbolObject(object: unknown): object is Symbol; - /** - * Returns `true` if the value is a built-in [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) instance. - * - * ```js - * util.types.isTypedArray(new ArrayBuffer()); // Returns false - * util.types.isTypedArray(new Uint8Array()); // Returns true - * util.types.isTypedArray(new Float64Array()); // Returns true - * ``` - * - * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). - * @since v10.0.0 - */ - function isTypedArray(object: unknown): object is NodeJS.TypedArray; - /** - * Returns `true` if the value is a built-in [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) instance. - * - * ```js - * util.types.isUint8Array(new ArrayBuffer()); // Returns false - * util.types.isUint8Array(new Uint8Array()); // Returns true - * util.types.isUint8Array(new Float64Array()); // Returns false - * ``` - * @since v10.0.0 - */ - function isUint8Array(object: unknown): object is Uint8Array; - /** - * Returns `true` if the value is a built-in [`Uint8ClampedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray) instance. - * - * ```js - * util.types.isUint8ClampedArray(new ArrayBuffer()); // Returns false - * util.types.isUint8ClampedArray(new Uint8ClampedArray()); // Returns true - * util.types.isUint8ClampedArray(new Float64Array()); // Returns false - * ``` - * @since v10.0.0 - */ - function isUint8ClampedArray(object: unknown): object is Uint8ClampedArray; - /** - * Returns `true` if the value is a built-in [`Uint16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array) instance. - * - * ```js - * util.types.isUint16Array(new ArrayBuffer()); // Returns false - * util.types.isUint16Array(new Uint16Array()); // Returns true - * util.types.isUint16Array(new Float64Array()); // Returns false - * ``` - * @since v10.0.0 - */ - function isUint16Array(object: unknown): object is Uint16Array; - /** - * Returns `true` if the value is a built-in [`Uint32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array) instance. - * - * ```js - * util.types.isUint32Array(new ArrayBuffer()); // Returns false - * util.types.isUint32Array(new Uint32Array()); // Returns true - * util.types.isUint32Array(new Float64Array()); // Returns false - * ``` - * @since v10.0.0 - */ - function isUint32Array(object: unknown): object is Uint32Array; - /** - * Returns `true` if the value is a built-in [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) instance. - * - * ```js - * util.types.isWeakMap(new WeakMap()); // Returns true - * ``` - * @since v10.0.0 - */ - function isWeakMap(object: unknown): object is WeakMap; - /** - * Returns `true` if the value is a built-in [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) instance. - * - * ```js - * util.types.isWeakSet(new WeakSet()); // Returns true - * ``` - * @since v10.0.0 - */ - function isWeakSet(object: unknown): object is WeakSet; - /** - * Returns `true` if `value` is a `KeyObject`, `false` otherwise. - * @since v16.2.0 - */ - function isKeyObject(object: unknown): object is KeyObject; - /** - * Returns `true` if `value` is a `CryptoKey`, `false` otherwise. - * @since v16.2.0 - */ - function isCryptoKey(object: unknown): object is webcrypto.CryptoKey; -} -declare module "node:util" { - export * from "util"; -} -declare module "node:util/types" { - export * from "util/types"; -} diff --git a/node_modules/@types/node/ts4.8/v8.d.ts b/node_modules/@types/node/ts4.8/v8.d.ts deleted file mode 100644 index 6790e7621f31a39604697ac17c56a129674f6db1..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/v8.d.ts +++ /dev/null @@ -1,635 +0,0 @@ -/** - * The `node:v8` module exposes APIs that are specific to the version of [V8](https://developers.google.com/v8/) built into the Node.js binary. It can be accessed using: - * - * ```js - * const v8 = require('node:v8'); - * ``` - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/v8.js) - */ -declare module "v8" { - import { Readable } from "node:stream"; - interface HeapSpaceInfo { - space_name: string; - space_size: number; - space_used_size: number; - space_available_size: number; - physical_space_size: number; - } - // ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */ - type DoesZapCodeSpaceFlag = 0 | 1; - interface HeapInfo { - total_heap_size: number; - total_heap_size_executable: number; - total_physical_size: number; - total_available_size: number; - used_heap_size: number; - heap_size_limit: number; - malloced_memory: number; - peak_malloced_memory: number; - does_zap_garbage: DoesZapCodeSpaceFlag; - number_of_native_contexts: number; - number_of_detached_contexts: number; - total_global_handles_size: number; - used_global_handles_size: number; - external_memory: number; - } - interface HeapCodeStatistics { - code_and_metadata_size: number; - bytecode_and_metadata_size: number; - external_script_source_size: number; - } - /** - * Returns an integer representing a version tag derived from the V8 version, - * command-line flags, and detected CPU features. This is useful for determining - * whether a `vm.Script` `cachedData` buffer is compatible with this instance - * of V8. - * - * ```js - * console.log(v8.cachedDataVersionTag()); // 3947234607 - * // The value returned by v8.cachedDataVersionTag() is derived from the V8 - * // version, command-line flags, and detected CPU features. Test that the value - * // does indeed update when flags are toggled. - * v8.setFlagsFromString('--allow_natives_syntax'); - * console.log(v8.cachedDataVersionTag()); // 183726201 - * ``` - * @since v8.0.0 - */ - function cachedDataVersionTag(): number; - /** - * Returns an object with the following properties: - * - * `does_zap_garbage` is a 0/1 boolean, which signifies whether the`--zap_code_space` option is enabled or not. This makes V8 overwrite heap - * garbage with a bit pattern. The RSS footprint (resident set size) gets bigger - * because it continuously touches all heap pages and that makes them less likely - * to get swapped out by the operating system. - * - * `number_of_native_contexts` The value of native\_context is the number of the - * top-level contexts currently active. Increase of this number over time indicates - * a memory leak. - * - * `number_of_detached_contexts` The value of detached\_context is the number - * of contexts that were detached and not yet garbage collected. This number - * being non-zero indicates a potential memory leak. - * - * `total_global_handles_size` The value of total\_global\_handles\_size is the - * total memory size of V8 global handles. - * - * `used_global_handles_size` The value of used\_global\_handles\_size is the - * used memory size of V8 global handles. - * - * `external_memory` The value of external\_memory is the memory size of array - * buffers and external strings. - * - * ```js - * { - * total_heap_size: 7326976, - * total_heap_size_executable: 4194304, - * total_physical_size: 7326976, - * total_available_size: 1152656, - * used_heap_size: 3476208, - * heap_size_limit: 1535115264, - * malloced_memory: 16384, - * peak_malloced_memory: 1127496, - * does_zap_garbage: 0, - * number_of_native_contexts: 1, - * number_of_detached_contexts: 0, - * total_global_handles_size: 8192, - * used_global_handles_size: 3296, - * external_memory: 318824 - * } - * ``` - * @since v1.0.0 - */ - function getHeapStatistics(): HeapInfo; - /** - * Returns statistics about the V8 heap spaces, i.e. the segments which make up - * the V8 heap. Neither the ordering of heap spaces, nor the availability of a - * heap space can be guaranteed as the statistics are provided via the - * V8[`GetHeapSpaceStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#ac673576f24fdc7a33378f8f57e1d13a4) function and may change from one V8 version to the - * next. - * - * The value returned is an array of objects containing the following properties: - * - * ```json - * [ - * { - * "space_name": "new_space", - * "space_size": 2063872, - * "space_used_size": 951112, - * "space_available_size": 80824, - * "physical_space_size": 2063872 - * }, - * { - * "space_name": "old_space", - * "space_size": 3090560, - * "space_used_size": 2493792, - * "space_available_size": 0, - * "physical_space_size": 3090560 - * }, - * { - * "space_name": "code_space", - * "space_size": 1260160, - * "space_used_size": 644256, - * "space_available_size": 960, - * "physical_space_size": 1260160 - * }, - * { - * "space_name": "map_space", - * "space_size": 1094160, - * "space_used_size": 201608, - * "space_available_size": 0, - * "physical_space_size": 1094160 - * }, - * { - * "space_name": "large_object_space", - * "space_size": 0, - * "space_used_size": 0, - * "space_available_size": 1490980608, - * "physical_space_size": 0 - * } - * ] - * ``` - * @since v6.0.0 - */ - function getHeapSpaceStatistics(): HeapSpaceInfo[]; - /** - * The `v8.setFlagsFromString()` method can be used to programmatically set - * V8 command-line flags. This method should be used with care. Changing settings - * after the VM has started may result in unpredictable behavior, including - * crashes and data loss; or it may simply do nothing. - * - * The V8 options available for a version of Node.js may be determined by running`node --v8-options`. - * - * Usage: - * - * ```js - * // Print GC events to stdout for one minute. - * const v8 = require('node:v8'); - * v8.setFlagsFromString('--trace_gc'); - * setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3); - * ``` - * @since v1.0.0 - */ - function setFlagsFromString(flags: string): void; - /** - * Generates a snapshot of the current V8 heap and returns a Readable - * Stream that may be used to read the JSON serialized representation. - * This JSON stream format is intended to be used with tools such as - * Chrome DevTools. The JSON schema is undocumented and specific to the - * V8 engine. Therefore, the schema may change from one version of V8 to the next. - * - * Creating a heap snapshot requires memory about twice the size of the heap at - * the time the snapshot is created. This results in the risk of OOM killers - * terminating the process. - * - * Generating a snapshot is a synchronous operation which blocks the event loop - * for a duration depending on the heap size. - * - * ```js - * // Print heap snapshot to the console - * const v8 = require('node:v8'); - * const stream = v8.getHeapSnapshot(); - * stream.pipe(process.stdout); - * ``` - * @since v11.13.0 - * @return A Readable containing the V8 heap snapshot. - */ - function getHeapSnapshot(): Readable; - /** - * Generates a snapshot of the current V8 heap and writes it to a JSON - * file. This file is intended to be used with tools such as Chrome - * DevTools. The JSON schema is undocumented and specific to the V8 - * engine, and may change from one version of V8 to the next. - * - * A heap snapshot is specific to a single V8 isolate. When using `worker threads`, a heap snapshot generated from the main thread will - * not contain any information about the workers, and vice versa. - * - * Creating a heap snapshot requires memory about twice the size of the heap at - * the time the snapshot is created. This results in the risk of OOM killers - * terminating the process. - * - * Generating a snapshot is a synchronous operation which blocks the event loop - * for a duration depending on the heap size. - * - * ```js - * const { writeHeapSnapshot } = require('node:v8'); - * const { - * Worker, - * isMainThread, - * parentPort, - * } = require('node:worker_threads'); - * - * if (isMainThread) { - * const worker = new Worker(__filename); - * - * worker.once('message', (filename) => { - * console.log(`worker heapdump: ${filename}`); - * // Now get a heapdump for the main thread. - * console.log(`main thread heapdump: ${writeHeapSnapshot()}`); - * }); - * - * // Tell the worker to create a heapdump. - * worker.postMessage('heapdump'); - * } else { - * parentPort.once('message', (message) => { - * if (message === 'heapdump') { - * // Generate a heapdump for the worker - * // and return the filename to the parent. - * parentPort.postMessage(writeHeapSnapshot()); - * } - * }); - * } - * ``` - * @since v11.13.0 - * @param filename The file path where the V8 heap snapshot is to be saved. If not specified, a file name with the pattern `'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'` will be - * generated, where `{pid}` will be the PID of the Node.js process, `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from the main Node.js thread or the id of a - * worker thread. - * @return The filename where the snapshot was saved. - */ - function writeHeapSnapshot(filename?: string): string; - /** - * Get statistics about code and its metadata in the heap, see - * V8[`GetHeapCodeAndMetadataStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#a6079122af17612ef54ef3348ce170866) API. Returns an object with the - * following properties: - * - * ```js - * { - * code_and_metadata_size: 212208, - * bytecode_and_metadata_size: 161368, - * external_script_source_size: 1410794, - * cpu_profiler_metadata_size: 0, - * } - * ``` - * @since v12.8.0 - */ - function getHeapCodeStatistics(): HeapCodeStatistics; - /** - * @since v8.0.0 - */ - class Serializer { - /** - * Writes out a header, which includes the serialization format version. - */ - writeHeader(): void; - /** - * Serializes a JavaScript value and adds the serialized representation to the - * internal buffer. - * - * This throws an error if `value` cannot be serialized. - */ - writeValue(val: any): boolean; - /** - * Returns the stored internal buffer. This serializer should not be used once - * the buffer is released. Calling this method results in undefined behavior - * if a previous write has failed. - */ - releaseBuffer(): Buffer; - /** - * Marks an `ArrayBuffer` as having its contents transferred out of band. - * Pass the corresponding `ArrayBuffer` in the deserializing context to `deserializer.transferArrayBuffer()`. - * @param id A 32-bit unsigned integer. - * @param arrayBuffer An `ArrayBuffer` instance. - */ - transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; - /** - * Write a raw 32-bit unsigned integer. - * For use inside of a custom `serializer._writeHostObject()`. - */ - writeUint32(value: number): void; - /** - * Write a raw 64-bit unsigned integer, split into high and low 32-bit parts. - * For use inside of a custom `serializer._writeHostObject()`. - */ - writeUint64(hi: number, lo: number): void; - /** - * Write a JS `number` value. - * For use inside of a custom `serializer._writeHostObject()`. - */ - writeDouble(value: number): void; - /** - * Write raw bytes into the serializer's internal buffer. The deserializer - * will require a way to compute the length of the buffer. - * For use inside of a custom `serializer._writeHostObject()`. - */ - writeRawBytes(buffer: NodeJS.TypedArray): void; - } - /** - * A subclass of `Serializer` that serializes `TypedArray`(in particular `Buffer`) and `DataView` objects as host objects, and only - * stores the part of their underlying `ArrayBuffer`s that they are referring to. - * @since v8.0.0 - */ - class DefaultSerializer extends Serializer {} - /** - * @since v8.0.0 - */ - class Deserializer { - constructor(data: NodeJS.TypedArray); - /** - * Reads and validates a header (including the format version). - * May, for example, reject an invalid or unsupported wire format. In that case, - * an `Error` is thrown. - */ - readHeader(): boolean; - /** - * Deserializes a JavaScript value from the buffer and returns it. - */ - readValue(): any; - /** - * Marks an `ArrayBuffer` as having its contents transferred out of band. - * Pass the corresponding `ArrayBuffer` in the serializing context to `serializer.transferArrayBuffer()` (or return the `id` from `serializer._getSharedArrayBufferId()` in the case of - * `SharedArrayBuffer`s). - * @param id A 32-bit unsigned integer. - * @param arrayBuffer An `ArrayBuffer` instance. - */ - transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; - /** - * Reads the underlying wire format version. Likely mostly to be useful to - * legacy code reading old wire format versions. May not be called before`.readHeader()`. - */ - getWireFormatVersion(): number; - /** - * Read a raw 32-bit unsigned integer and return it. - * For use inside of a custom `deserializer._readHostObject()`. - */ - readUint32(): number; - /** - * Read a raw 64-bit unsigned integer and return it as an array `[hi, lo]`with two 32-bit unsigned integer entries. - * For use inside of a custom `deserializer._readHostObject()`. - */ - readUint64(): [number, number]; - /** - * Read a JS `number` value. - * For use inside of a custom `deserializer._readHostObject()`. - */ - readDouble(): number; - /** - * Read raw bytes from the deserializer's internal buffer. The `length` parameter - * must correspond to the length of the buffer that was passed to `serializer.writeRawBytes()`. - * For use inside of a custom `deserializer._readHostObject()`. - */ - readRawBytes(length: number): Buffer; - } - /** - * A subclass of `Deserializer` corresponding to the format written by `DefaultSerializer`. - * @since v8.0.0 - */ - class DefaultDeserializer extends Deserializer {} - /** - * Uses a `DefaultSerializer` to serialize `value` into a buffer. - * - * `ERR_BUFFER_TOO_LARGE` will be thrown when trying to - * serialize a huge object which requires buffer - * larger than `buffer.constants.MAX_LENGTH`. - * @since v8.0.0 - */ - function serialize(value: any): Buffer; - /** - * Uses a `DefaultDeserializer` with default options to read a JS value - * from a buffer. - * @since v8.0.0 - * @param buffer A buffer returned by {@link serialize}. - */ - function deserialize(buffer: NodeJS.TypedArray): any; - /** - * The `v8.takeCoverage()` method allows the user to write the coverage started by `NODE_V8_COVERAGE` to disk on demand. This method can be invoked multiple - * times during the lifetime of the process. Each time the execution counter will - * be reset and a new coverage report will be written to the directory specified - * by `NODE_V8_COVERAGE`. - * - * When the process is about to exit, one last coverage will still be written to - * disk unless {@link stopCoverage} is invoked before the process exits. - * @since v15.1.0, v14.18.0, v12.22.0 - */ - function takeCoverage(): void; - /** - * The `v8.stopCoverage()` method allows the user to stop the coverage collection - * started by `NODE_V8_COVERAGE`, so that V8 can release the execution count - * records and optimize code. This can be used in conjunction with {@link takeCoverage} if the user wants to collect the coverage on demand. - * @since v15.1.0, v14.18.0, v12.22.0 - */ - function stopCoverage(): void; - /** - * This API collects GC data in current thread. - * @since v19.6.0, v18.15.0 - */ - class GCProfiler { - /** - * Start collecting GC data. - * @since v19.6.0, v18.15.0 - */ - start(): void; - /** - * Stop collecting GC data and return an object.The content of object - * is as follows. - * - * ```json - * { - * "version": 1, - * "startTime": 1674059033862, - * "statistics": [ - * { - * "gcType": "Scavenge", - * "beforeGC": { - * "heapStatistics": { - * "totalHeapSize": 5005312, - * "totalHeapSizeExecutable": 524288, - * "totalPhysicalSize": 5226496, - * "totalAvailableSize": 4341325216, - * "totalGlobalHandlesSize": 8192, - * "usedGlobalHandlesSize": 2112, - * "usedHeapSize": 4883840, - * "heapSizeLimit": 4345298944, - * "mallocedMemory": 254128, - * "externalMemory": 225138, - * "peakMallocedMemory": 181760 - * }, - * "heapSpaceStatistics": [ - * { - * "spaceName": "read_only_space", - * "spaceSize": 0, - * "spaceUsedSize": 0, - * "spaceAvailableSize": 0, - * "physicalSpaceSize": 0 - * } - * ] - * }, - * "cost": 1574.14, - * "afterGC": { - * "heapStatistics": { - * "totalHeapSize": 6053888, - * "totalHeapSizeExecutable": 524288, - * "totalPhysicalSize": 5500928, - * "totalAvailableSize": 4341101384, - * "totalGlobalHandlesSize": 8192, - * "usedGlobalHandlesSize": 2112, - * "usedHeapSize": 4059096, - * "heapSizeLimit": 4345298944, - * "mallocedMemory": 254128, - * "externalMemory": 225138, - * "peakMallocedMemory": 181760 - * }, - * "heapSpaceStatistics": [ - * { - * "spaceName": "read_only_space", - * "spaceSize": 0, - * "spaceUsedSize": 0, - * "spaceAvailableSize": 0, - * "physicalSpaceSize": 0 - * } - * ] - * } - * } - * ], - * "endTime": 1674059036865 - * } - * ``` - * - * Here's an example. - * - * ```js - * const { GCProfiler } = require('v8'); - * const profiler = new GCProfiler(); - * profiler.start(); - * setTimeout(() => { - * console.log(profiler.stop()); - * }, 1000); - * ``` - * @since v19.6.0, v18.15.0 - */ - stop(): GCProfilerResult; - } - interface GCProfilerResult { - version: number; - startTime: number; - endTime: number; - statistics: Array<{ - gcType: string; - cost: number; - beforeGC: { - heapStatistics: HeapStatistics; - heapSpaceStatistics: HeapSpaceStatistics[]; - }; - afterGC: { - heapStatistics: HeapStatistics; - heapSpaceStatistics: HeapSpaceStatistics[]; - }; - }>; - } - interface HeapStatistics { - totalHeapSize: number; - totalHeapSizeExecutable: number; - totalPhysicalSize: number; - totalAvailableSize: number; - totalGlobalHandlesSize: number; - usedGlobalHandlesSize: number; - usedHeapSize: number; - heapSizeLimit: number; - mallocedMemory: number; - externalMemory: number; - peakMallocedMemory: number; - } - interface HeapSpaceStatistics { - spaceName: string; - spaceSize: number; - spaceUsedSize: number; - spaceAvailableSize: number; - physicalSpaceSize: number; - } - /** - * Called when a promise is constructed. This does not mean that corresponding before/after events will occur, only that the possibility exists. This will - * happen if a promise is created without ever getting a continuation. - * @since v17.1.0, v16.14.0 - * @param promise The promise being created. - * @param parent The promise continued from, if applicable. - */ - interface Init { - (promise: Promise, parent: Promise): void; - } - /** - * Called before a promise continuation executes. This can be in the form of `then()`, `catch()`, or `finally()` handlers or an await resuming. - * - * The before callback will be called 0 to N times. The before callback will typically be called 0 times if no continuation was ever made for the promise. - * The before callback may be called many times in the case where many continuations have been made from the same promise. - * @since v17.1.0, v16.14.0 - */ - interface Before { - (promise: Promise): void; - } - /** - * Called immediately after a promise continuation executes. This may be after a `then()`, `catch()`, or `finally()` handler or before an await after another await. - * @since v17.1.0, v16.14.0 - */ - interface After { - (promise: Promise): void; - } - /** - * Called when the promise receives a resolution or rejection value. This may occur synchronously in the case of {@link Promise.resolve()} or - * {@link Promise.reject()}. - * @since v17.1.0, v16.14.0 - */ - interface Settled { - (promise: Promise): void; - } - /** - * Key events in the lifetime of a promise have been categorized into four areas: creation of a promise, before/after a continuation handler is called or - * around an await, and when the promise resolves or rejects. - * - * Because promises are asynchronous resources whose lifecycle is tracked via the promise hooks mechanism, the `init()`, `before()`, `after()`, and - * `settled()` callbacks must not be async functions as they create more promises which would produce an infinite loop. - * @since v17.1.0, v16.14.0 - */ - interface HookCallbacks { - init?: Init; - before?: Before; - after?: After; - settled?: Settled; - } - interface PromiseHooks { - /** - * The `init` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. - * @since v17.1.0, v16.14.0 - * @param init The {@link Init | `init` callback} to call when a promise is created. - * @return Call to stop the hook. - */ - onInit: (init: Init) => Function; - /** - * The `settled` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. - * @since v17.1.0, v16.14.0 - * @param settled The {@link Settled | `settled` callback} to call when a promise is created. - * @return Call to stop the hook. - */ - onSettled: (settled: Settled) => Function; - /** - * The `before` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. - * @since v17.1.0, v16.14.0 - * @param before The {@link Before | `before` callback} to call before a promise continuation executes. - * @return Call to stop the hook. - */ - onBefore: (before: Before) => Function; - /** - * The `after` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. - * @since v17.1.0, v16.14.0 - * @param after The {@link After | `after` callback} to call after a promise continuation executes. - * @return Call to stop the hook. - */ - onAfter: (after: After) => Function; - /** - * Registers functions to be called for different lifetime events of each promise. - * The callbacks `init()`/`before()`/`after()`/`settled()` are called for the respective events during a promise's lifetime. - * All callbacks are optional. For example, if only promise creation needs to be tracked, then only the init callback needs to be passed. - * The hook callbacks must be plain functions. Providing async functions will throw as it would produce an infinite microtask loop. - * @since v17.1.0, v16.14.0 - * @param callbacks The {@link HookCallbacks | Hook Callbacks} to register - * @return Used for disabling hooks - */ - createHook: (callbacks: HookCallbacks) => Function; - } - /** - * The `promiseHooks` interface can be used to track promise lifecycle events. - * @since v17.1.0, v16.14.0 - */ - const promiseHooks: PromiseHooks; -} -declare module "node:v8" { - export * from "v8"; -} diff --git a/node_modules/@types/node/ts4.8/vm.d.ts b/node_modules/@types/node/ts4.8/vm.d.ts deleted file mode 100644 index 3a310ccb325e032e07407a7676601b301a942038..0000000000000000000000000000000000000000 --- a/node_modules/@types/node/ts4.8/vm.d.ts +++ /dev/null @@ -1,903 +0,0 @@ -/** - * The `node:vm` module enables compiling and running code within V8 Virtual - * Machine contexts. - * - * **The `node:vm` module is not a security** - * **mechanism. Do not use it to run untrusted code.** - * - * JavaScript code can be compiled and run immediately or - * compiled, saved, and run later. - * - * A common use case is to run the code in a different V8 Context. This means - * invoked code has a different global object than the invoking code. - * - * One can provide the context by `contextifying` an - * object. The invoked code treats any property in the context like a - * global variable. Any changes to global variables caused by the invoked - * code are reflected in the context object. - * - * ```js - * const vm = require('node:vm'); - * - * const x = 1; - * - * const context = { x: 2 }; - * vm.createContext(context); // Contextify the object. - * - * const code = 'x += 40; var y = 17;'; - * // `x` and `y` are global variables in the context. - * // Initially, x has the value 2 because that is the value of context.x. - * vm.runInContext(code, context); - * - * console.log(context.x); // 42 - * console.log(context.y); // 17 - * - * console.log(x); // 1; y is not defined. - * ``` - * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/vm.js) - */ -declare module "vm" { - import { ImportAttributes } from "node:module"; - interface Context extends NodeJS.Dict {} - interface BaseOptions { - /** - * Specifies the filename used in stack traces produced by this script. - * Default: `''`. - */ - filename?: string | undefined; - /** - * Specifies the line number offset that is displayed in stack traces produced by this script. - * Default: `0`. - */ - lineOffset?: number | undefined; - /** - * Specifies the column number offset that is displayed in stack traces produced by this script. - * @default 0 - */ - columnOffset?: number | undefined; - } - interface ScriptOptions extends BaseOptions { - /** - * V8's code cache data for the supplied source. - */ - cachedData?: Buffer | NodeJS.ArrayBufferView | undefined; - /** @deprecated in favor of `script.createCachedData()` */ - produceCachedData?: boolean | undefined; - /** - * Called during evaluation of this module when `import()` is called. - * If this option is not specified, calls to `import()` will reject with `ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`. - */ - importModuleDynamically?: - | ((specifier: string, script: Script, importAttributes: ImportAttributes) => Module) - | undefined; - } - interface RunningScriptOptions extends BaseOptions { - /** - * When `true`, if an `Error` occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. - * Default: `true`. - */ - displayErrors?: boolean | undefined; - /** - * Specifies the number of milliseconds to execute code before terminating execution. - * If execution is terminated, an `Error` will be thrown. This value must be a strictly positive integer. - */ - timeout?: number | undefined; - /** - * If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. - * Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. - * If execution is terminated, an `Error` will be thrown. - * Default: `false`. - */ - breakOnSigint?: boolean | undefined; - } - interface RunningScriptInNewContextOptions extends RunningScriptOptions { - /** - * Human-readable name of the newly created context. - */ - contextName?: CreateContextOptions["name"]; - /** - * Origin corresponding to the newly created context for display purposes. The origin should be formatted like a URL, - * but with only the scheme, host, and port (if necessary), like the value of the `url.origin` property of a `URL` object. - * Most notably, this string should omit the trailing slash, as that denotes a path. - */ - contextOrigin?: CreateContextOptions["origin"]; - contextCodeGeneration?: CreateContextOptions["codeGeneration"]; - /** - * If set to `afterEvaluate`, microtasks will be run immediately after the script has run. - */ - microtaskMode?: CreateContextOptions["microtaskMode"]; - } - interface RunningCodeOptions extends RunningScriptOptions { - cachedData?: ScriptOptions["cachedData"]; - importModuleDynamically?: ScriptOptions["importModuleDynamically"]; - } - interface RunningCodeInNewContextOptions extends RunningScriptInNewContextOptions { - cachedData?: ScriptOptions["cachedData"]; - importModuleDynamically?: ScriptOptions["importModuleDynamically"]; - } - interface CompileFunctionOptions extends BaseOptions { - /** - * Provides an optional data with V8's code cache data for the supplied source. - */ - cachedData?: Buffer | undefined; - /** - * Specifies whether to produce new cache data. - * Default: `false`, - */ - produceCachedData?: boolean | undefined; - /** - * The sandbox/context in which the said function should be compiled in. - */ - parsingContext?: Context | undefined; - /** - * An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling - */ - contextExtensions?: Object[] | undefined; - } - interface CreateContextOptions { - /** - * Human-readable name of the newly created context. - * @default 'VM Context i' Where i is an ascending numerical index of the created context. - */ - name?: string | undefined; - /** - * Corresponds to the newly created context for display purposes. - * The origin should be formatted like a `URL`, but with only the scheme, host, and port (if necessary), - * like the value of the `url.origin` property of a URL object. - * Most notably, this string should omit the trailing slash, as that denotes a path. - * @default '' - */ - origin?: string | undefined; - codeGeneration?: - | { - /** - * If set to false any calls to eval or function constructors (Function, GeneratorFunction, etc) - * will throw an EvalError. - * @default true - */ - strings?: boolean | undefined; - /** - * If set to false any attempt to compile a WebAssembly module will throw a WebAssembly.CompileError. - * @default true - */ - wasm?: boolean | undefined; - } - | undefined; - /** - * If set to `afterEvaluate`, microtasks will be run immediately after the script has run. - */ - microtaskMode?: "afterEvaluate" | undefined; - } - type MeasureMemoryMode = "summary" | "detailed"; - interface MeasureMemoryOptions { - /** - * @default 'summary' - */ - mode?: MeasureMemoryMode | undefined; - /** - * @default 'default' - */ - execution?: "default" | "eager" | undefined; - } - interface MemoryMeasurement { - total: { - jsMemoryEstimate: number; - jsMemoryRange: [number, number]; - }; - } - /** - * Instances of the `vm.Script` class contain precompiled scripts that can be - * executed in specific contexts. - * @since v0.3.1 - */ - class Script { - constructor(code: string, options?: ScriptOptions | string); - /** - * Runs the compiled code contained by the `vm.Script` object within the given`contextifiedObject` and returns the result. Running code does not have access - * to local scope. - * - * The following example compiles code that increments a global variable, sets - * the value of another global variable, then execute the code multiple times. - * The globals are contained in the `context` object. - * - * ```js - * const vm = require('node:vm'); - * - * const context = { - * animal: 'cat', - * count: 2, - * }; - * - * const script = new vm.Script('count += 1; name = "kitty";'); - * - * vm.createContext(context); - * for (let i = 0; i < 10; ++i) { - * script.runInContext(context); - * } - * - * console.log(context); - * // Prints: { animal: 'cat', count: 12, name: 'kitty' } - * ``` - * - * Using the `timeout` or `breakOnSigint` options will result in new event loops - * and corresponding threads being started, which have a non-zero performance - * overhead. - * @since v0.3.1 - * @param contextifiedObject A `contextified` object as returned by the `vm.createContext()` method. - * @return the result of the very last statement executed in the script. - */ - runInContext(contextifiedObject: Context, options?: RunningScriptOptions): any; - /** - * First contextifies the given `contextObject`, runs the compiled code contained - * by the `vm.Script` object within the created context, and returns the result. - * Running code does not have access to local scope. - * - * The following example compiles code that sets a global variable, then executes - * the code multiple times in different contexts. The globals are set on and - * contained within each individual `context`. - * - * ```js - * const vm = require('node:vm'); - * - * const script = new vm.Script('globalVar = "set"'); - * - * const contexts = [{}, {}, {}]; - * contexts.forEach((context) => { - * script.runInNewContext(context); - * }); - * - * console.log(contexts); - * // Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }] - * ``` - * @since v0.3.1 - * @param contextObject An object that will be `contextified`. If `undefined`, a new object will be created. - * @return the result of the very last statement executed in the script. - */ - runInNewContext(contextObject?: Context, options?: RunningScriptInNewContextOptions): any; - /** - * Runs the compiled code contained by the `vm.Script` within the context of the - * current `global` object. Running code does not have access to local scope, but _does_ have access to the current `global` object. - * - * The following example compiles code that increments a `global` variable then - * executes that code multiple times: - * - * ```js - * const vm = require('node:vm'); - * - * global.globalVar = 0; - * - * const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' }); - * - * for (let i = 0; i < 1000; ++i) { - * script.runInThisContext(); - * } - * - * console.log(globalVar); - * - * // 1000 - * ``` - * @since v0.3.1 - * @return the result of the very last statement executed in the script. - */ - runInThisContext(options?: RunningScriptOptions): any; - /** - * Creates a code cache that can be used with the `Script` constructor's`cachedData` option. Returns a `Buffer`. This method may be called at any - * time and any number of times. - * - * The code cache of the `Script` doesn't contain any JavaScript observable - * states. The code cache is safe to be saved along side the script source and - * used to construct new `Script` instances multiple times. - * - * Functions in the `Script` source can be marked as lazily compiled and they are - * not compiled at construction of the `Script`. These functions are going to be - * compiled when they are invoked the first time. The code cache serializes the - * metadata that V8 currently knows about the `Script` that it can use to speed up - * future compilations. - * - * ```js - * const script = new vm.Script(` - * function add(a, b) { - * return a + b; - * } - * - * const x = add(1, 2); - * `); - * - * const cacheWithoutAdd = script.createCachedData(); - * // In `cacheWithoutAdd` the function `add()` is marked for full compilation - * // upon invocation. - * - * script.runInThisContext(); - * - * const cacheWithAdd = script.createCachedData(); - * // `cacheWithAdd` contains fully compiled function `add()`. - * ``` - * @since v10.6.0 - */ - createCachedData(): Buffer; - /** @deprecated in favor of `script.createCachedData()` */ - cachedDataProduced?: boolean | undefined; - /** - * When `cachedData` is supplied to create the `vm.Script`, this value will be set - * to either `true` or `false` depending on acceptance of the data by V8\. - * Otherwise the value is `undefined`. - * @since v5.7.0 - */ - cachedDataRejected?: boolean | undefined; - cachedData?: Buffer | undefined; - /** - * When the script is compiled from a source that contains a source map magic - * comment, this property will be set to the URL of the source map. - * - * ```js - * import vm from 'node:vm'; - * - * const script = new vm.Script(` - * function myFunc() {} - * //# sourceMappingURL=sourcemap.json - * `); - * - * console.log(script.sourceMapURL); - * // Prints: sourcemap.json - * ``` - * @since v19.1.0, v18.13.0 - */ - sourceMapURL?: string | undefined; - } - /** - * If given a `contextObject`, the `vm.createContext()` method will `prepare - * that object` so that it can be used in calls to {@link runInContext} or `script.runInContext()`. Inside such scripts, - * the `contextObject` will be the global object, retaining all of its existing - * properties but also having the built-in objects and functions any standard [global object](https://es5.github.io/#x15.1) has. Outside of scripts run by the vm module, global variables - * will remain unchanged. - * - * ```js - * const vm = require('node:vm'); - * - * global.globalVar = 3; - * - * const context = { globalVar: 1 }; - * vm.createContext(context); - * - * vm.runInContext('globalVar *= 2;', context); - * - * console.log(context); - * // Prints: { globalVar: 2 } - * - * console.log(global.globalVar); - * // Prints: 3 - * ``` - * - * If `contextObject` is omitted (or passed explicitly as `undefined`), a new, - * empty `contextified` object will be returned. - * - * The `vm.createContext()` method is primarily useful for creating a single - * context that can be used to run multiple scripts. For instance, if emulating a - * web browser, the method can be used to create a single context representing a - * window's global object, then run all ` + +``` + +## API + +### parser(args, opts={}) + +Parses command line arguments returning a simple mapping of keys and values. + +**expects:** + +* `args`: a string or array of strings representing the options to parse. +* `opts`: provide a set of hints indicating how `args` should be parsed: + * `opts.alias`: an object representing the set of aliases for a key: `{alias: {foo: ['f']}}`. + * `opts.array`: indicate that keys should be parsed as an array: `{array: ['foo', 'bar']}`.
+ Indicate that keys should be parsed as an array and coerced to booleans / numbers:
+ `{array: [{ key: 'foo', boolean: true }, {key: 'bar', number: true}]}`. + * `opts.boolean`: arguments should be parsed as booleans: `{boolean: ['x', 'y']}`. + * `opts.coerce`: provide a custom synchronous function that returns a coerced value from the argument provided + (or throws an error). For arrays the function is called only once for the entire array:
+ `{coerce: {foo: function (arg) {return modifiedArg}}}`. + * `opts.config`: indicate a key that represents a path to a configuration file (this file will be loaded and parsed). + * `opts.configObjects`: configuration objects to parse, their properties will be set as arguments:
+ `{configObjects: [{'x': 5, 'y': 33}, {'z': 44}]}`. + * `opts.configuration`: provide configuration options to the yargs-parser (see: [configuration](#configuration)). + * `opts.count`: indicate a key that should be used as a counter, e.g., `-vvv` = `{v: 3}`. + * `opts.default`: provide default values for keys: `{default: {x: 33, y: 'hello world!'}}`. + * `opts.envPrefix`: environment variables (`process.env`) with the prefix provided should be parsed. + * `opts.narg`: specify that a key requires `n` arguments: `{narg: {x: 2}}`. + * `opts.normalize`: `path.normalize()` will be applied to values set to this key. + * `opts.number`: keys should be treated as numbers. + * `opts.string`: keys should be treated as strings (even if they resemble a number `-x 33`). + +**returns:** + +* `obj`: an object representing the parsed value of `args` + * `key/value`: key value pairs for each argument and their aliases. + * `_`: an array representing the positional arguments. + * [optional] `--`: an array with arguments after the end-of-options flag `--`. + +### require('yargs-parser').detailed(args, opts={}) + +Parses a command line string, returning detailed information required by the +yargs engine. + +**expects:** + +* `args`: a string or array of strings representing options to parse. +* `opts`: provide a set of hints indicating how `args`, inputs are identical to `require('yargs-parser')(args, opts={})`. + +**returns:** + +* `argv`: an object representing the parsed value of `args` + * `key/value`: key value pairs for each argument and their aliases. + * `_`: an array representing the positional arguments. + * [optional] `--`: an array with arguments after the end-of-options flag `--`. +* `error`: populated with an error object if an exception occurred during parsing. +* `aliases`: the inferred list of aliases built by combining lists in `opts.alias`. +* `newAliases`: any new aliases added via camel-case expansion: + * `boolean`: `{ fooBar: true }` +* `defaulted`: any new argument created by `opts.default`, no aliases included. + * `boolean`: `{ foo: true }` +* `configuration`: given by default settings and `opts.configuration`. + + + +### Configuration + +The yargs-parser applies several automated transformations on the keys provided +in `args`. These features can be turned on and off using the `configuration` field +of `opts`. + +```js +var parsed = parser(['--no-dice'], { + configuration: { + 'boolean-negation': false + } +}) +``` + +### short option groups + +* default: `true`. +* key: `short-option-groups`. + +Should a group of short-options be treated as boolean flags? + +```console +$ node example.js -abc +{ _: [], a: true, b: true, c: true } +``` + +_if disabled:_ + +```console +$ node example.js -abc +{ _: [], abc: true } +``` + +### camel-case expansion + +* default: `true`. +* key: `camel-case-expansion`. + +Should hyphenated arguments be expanded into camel-case aliases? + +```console +$ node example.js --foo-bar +{ _: [], 'foo-bar': true, fooBar: true } +``` + +_if disabled:_ + +```console +$ node example.js --foo-bar +{ _: [], 'foo-bar': true } +``` + +### dot-notation + +* default: `true` +* key: `dot-notation` + +Should keys that contain `.` be treated as objects? + +```console +$ node example.js --foo.bar +{ _: [], foo: { bar: true } } +``` + +_if disabled:_ + +```console +$ node example.js --foo.bar +{ _: [], "foo.bar": true } +``` + +### parse numbers + +* default: `true` +* key: `parse-numbers` + +Should keys that look like numbers be treated as such? + +```console +$ node example.js --foo=99.3 +{ _: [], foo: 99.3 } +``` + +_if disabled:_ + +```console +$ node example.js --foo=99.3 +{ _: [], foo: "99.3" } +``` + +### parse positional numbers + +* default: `true` +* key: `parse-positional-numbers` + +Should positional keys that look like numbers be treated as such. + +```console +$ node example.js 99.3 +{ _: [99.3] } +``` + +_if disabled:_ + +```console +$ node example.js 99.3 +{ _: ['99.3'] } +``` + +### boolean negation + +* default: `true` +* key: `boolean-negation` + +Should variables prefixed with `--no` be treated as negations? + +```console +$ node example.js --no-foo +{ _: [], foo: false } +``` + +_if disabled:_ + +```console +$ node example.js --no-foo +{ _: [], "no-foo": true } +``` + +### combine arrays + +* default: `false` +* key: `combine-arrays` + +Should arrays be combined when provided by both command line arguments and +a configuration file. + +### duplicate arguments array + +* default: `true` +* key: `duplicate-arguments-array` + +Should arguments be coerced into an array when duplicated: + +```console +$ node example.js -x 1 -x 2 +{ _: [], x: [1, 2] } +``` + +_if disabled:_ + +```console +$ node example.js -x 1 -x 2 +{ _: [], x: 2 } +``` + +### flatten duplicate arrays + +* default: `true` +* key: `flatten-duplicate-arrays` + +Should array arguments be coerced into a single array when duplicated: + +```console +$ node example.js -x 1 2 -x 3 4 +{ _: [], x: [1, 2, 3, 4] } +``` + +_if disabled:_ + +```console +$ node example.js -x 1 2 -x 3 4 +{ _: [], x: [[1, 2], [3, 4]] } +``` + +### greedy arrays + +* default: `true` +* key: `greedy-arrays` + +Should arrays consume more than one positional argument following their flag. + +```console +$ node example --arr 1 2 +{ _: [], arr: [1, 2] } +``` + +_if disabled:_ + +```console +$ node example --arr 1 2 +{ _: [2], arr: [1] } +``` + +**Note: in `v18.0.0` we are considering defaulting greedy arrays to `false`.** + +### nargs eats options + +* default: `false` +* key: `nargs-eats-options` + +Should nargs consume dash options as well as positional arguments. + +### negation prefix + +* default: `no-` +* key: `negation-prefix` + +The prefix to use for negated boolean variables. + +```console +$ node example.js --no-foo +{ _: [], foo: false } +``` + +_if set to `quux`:_ + +```console +$ node example.js --quuxfoo +{ _: [], foo: false } +``` + +### populate -- + +* default: `false`. +* key: `populate--` + +Should unparsed flags be stored in `--` or `_`. + +_If disabled:_ + +```console +$ node example.js a -b -- x y +{ _: [ 'a', 'x', 'y' ], b: true } +``` + +_If enabled:_ + +```console +$ node example.js a -b -- x y +{ _: [ 'a' ], '--': [ 'x', 'y' ], b: true } +``` + +### set placeholder key + +* default: `false`. +* key: `set-placeholder-key`. + +Should a placeholder be added for keys not set via the corresponding CLI argument? + +_If disabled:_ + +```console +$ node example.js -a 1 -c 2 +{ _: [], a: 1, c: 2 } +``` + +_If enabled:_ + +```console +$ node example.js -a 1 -c 2 +{ _: [], a: 1, b: undefined, c: 2 } +``` + +### halt at non-option + +* default: `false`. +* key: `halt-at-non-option`. + +Should parsing stop at the first positional argument? This is similar to how e.g. `ssh` parses its command line. + +_If disabled:_ + +```console +$ node example.js -a run b -x y +{ _: [ 'b' ], a: 'run', x: 'y' } +``` + +_If enabled:_ + +```console +$ node example.js -a run b -x y +{ _: [ 'b', '-x', 'y' ], a: 'run' } +``` + +### strip aliased + +* default: `false` +* key: `strip-aliased` + +Should aliases be removed before returning results? + +_If disabled:_ + +```console +$ node example.js --test-field 1 +{ _: [], 'test-field': 1, testField: 1, 'test-alias': 1, testAlias: 1 } +``` + +_If enabled:_ + +```console +$ node example.js --test-field 1 +{ _: [], 'test-field': 1, testField: 1 } +``` + +### strip dashed + +* default: `false` +* key: `strip-dashed` + +Should dashed keys be removed before returning results? This option has no effect if +`camel-case-expansion` is disabled. + +_If disabled:_ + +```console +$ node example.js --test-field 1 +{ _: [], 'test-field': 1, testField: 1 } +``` + +_If enabled:_ + +```console +$ node example.js --test-field 1 +{ _: [], testField: 1 } +``` + +### unknown options as args + +* default: `false` +* key: `unknown-options-as-args` + +Should unknown options be treated like regular arguments? An unknown option is one that is not +configured in `opts`. + +_If disabled_ + +```console +$ node example.js --unknown-option --known-option 2 --string-option --unknown-option2 +{ _: [], unknownOption: true, knownOption: 2, stringOption: '', unknownOption2: true } +``` + +_If enabled_ + +```console +$ node example.js --unknown-option --known-option 2 --string-option --unknown-option2 +{ _: ['--unknown-option'], knownOption: 2, stringOption: '--unknown-option2' } +``` + +## Supported Node.js Versions + +Libraries in this ecosystem make a best effort to track +[Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a +post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). + +## Special Thanks + +The yargs project evolves from optimist and minimist. It owes its +existence to a lot of James Halliday's hard work. Thanks [substack](https://github.com/substack) **beep** **boop** \o/ + +## License + +ISC diff --git a/node_modules/yargs-parser/browser.js b/node_modules/yargs-parser/browser.js new file mode 100644 index 0000000000000000000000000000000000000000..241202c7e2bb27983e2648a8524a8f3a52d21667 --- /dev/null +++ b/node_modules/yargs-parser/browser.js @@ -0,0 +1,29 @@ +// Main entrypoint for ESM web browser environments. Avoids using Node.js +// specific libraries, such as "path". +// +// TODO: figure out reasonable web equivalents for "resolve", "normalize", etc. +import { camelCase, decamelize, looksLikeNumber } from './build/lib/string-utils.js' +import { YargsParser } from './build/lib/yargs-parser.js' +const parser = new YargsParser({ + cwd: () => { return '' }, + format: (str, arg) => { return str.replace('%s', arg) }, + normalize: (str) => { return str }, + resolve: (str) => { return str }, + require: () => { + throw Error('loading config from files not currently supported in browser') + }, + env: () => {} +}) + +const yargsParser = function Parser (args, opts) { + const result = parser.parse(args.slice(), opts) + return result.argv +} +yargsParser.detailed = function (args, opts) { + return parser.parse(args.slice(), opts) +} +yargsParser.camelCase = camelCase +yargsParser.decamelize = decamelize +yargsParser.looksLikeNumber = looksLikeNumber + +export default yargsParser diff --git a/node_modules/yargs-parser/build/index.cjs b/node_modules/yargs-parser/build/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..cf6f50f66e666f920a02cd19e4bcc9096b576d9a --- /dev/null +++ b/node_modules/yargs-parser/build/index.cjs @@ -0,0 +1,1050 @@ +'use strict'; + +var util = require('util'); +var path = require('path'); +var fs = require('fs'); + +function camelCase(str) { + const isCamelCase = str !== str.toLowerCase() && str !== str.toUpperCase(); + if (!isCamelCase) { + str = str.toLowerCase(); + } + if (str.indexOf('-') === -1 && str.indexOf('_') === -1) { + return str; + } + else { + let camelcase = ''; + let nextChrUpper = false; + const leadingHyphens = str.match(/^-+/); + for (let i = leadingHyphens ? leadingHyphens[0].length : 0; i < str.length; i++) { + let chr = str.charAt(i); + if (nextChrUpper) { + nextChrUpper = false; + chr = chr.toUpperCase(); + } + if (i !== 0 && (chr === '-' || chr === '_')) { + nextChrUpper = true; + } + else if (chr !== '-' && chr !== '_') { + camelcase += chr; + } + } + return camelcase; + } +} +function decamelize(str, joinString) { + const lowercase = str.toLowerCase(); + joinString = joinString || '-'; + let notCamelcase = ''; + for (let i = 0; i < str.length; i++) { + const chrLower = lowercase.charAt(i); + const chrString = str.charAt(i); + if (chrLower !== chrString && i > 0) { + notCamelcase += `${joinString}${lowercase.charAt(i)}`; + } + else { + notCamelcase += chrString; + } + } + return notCamelcase; +} +function looksLikeNumber(x) { + if (x === null || x === undefined) + return false; + if (typeof x === 'number') + return true; + if (/^0x[0-9a-f]+$/i.test(x)) + return true; + if (/^0[^.]/.test(x)) + return false; + return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); +} + +function tokenizeArgString(argString) { + if (Array.isArray(argString)) { + return argString.map(e => typeof e !== 'string' ? e + '' : e); + } + argString = argString.trim(); + let i = 0; + let prevC = null; + let c = null; + let opening = null; + const args = []; + for (let ii = 0; ii < argString.length; ii++) { + prevC = c; + c = argString.charAt(ii); + if (c === ' ' && !opening) { + if (!(prevC === ' ')) { + i++; + } + continue; + } + if (c === opening) { + opening = null; + } + else if ((c === "'" || c === '"') && !opening) { + opening = c; + } + if (!args[i]) + args[i] = ''; + args[i] += c; + } + return args; +} + +var DefaultValuesForTypeKey; +(function (DefaultValuesForTypeKey) { + DefaultValuesForTypeKey["BOOLEAN"] = "boolean"; + DefaultValuesForTypeKey["STRING"] = "string"; + DefaultValuesForTypeKey["NUMBER"] = "number"; + DefaultValuesForTypeKey["ARRAY"] = "array"; +})(DefaultValuesForTypeKey || (DefaultValuesForTypeKey = {})); + +let mixin; +class YargsParser { + constructor(_mixin) { + mixin = _mixin; + } + parse(argsInput, options) { + const opts = Object.assign({ + alias: undefined, + array: undefined, + boolean: undefined, + config: undefined, + configObjects: undefined, + configuration: undefined, + coerce: undefined, + count: undefined, + default: undefined, + envPrefix: undefined, + narg: undefined, + normalize: undefined, + string: undefined, + number: undefined, + __: undefined, + key: undefined + }, options); + const args = tokenizeArgString(argsInput); + const inputIsString = typeof argsInput === 'string'; + const aliases = combineAliases(Object.assign(Object.create(null), opts.alias)); + const configuration = Object.assign({ + 'boolean-negation': true, + 'camel-case-expansion': true, + 'combine-arrays': false, + 'dot-notation': true, + 'duplicate-arguments-array': true, + 'flatten-duplicate-arrays': true, + 'greedy-arrays': true, + 'halt-at-non-option': false, + 'nargs-eats-options': false, + 'negation-prefix': 'no-', + 'parse-numbers': true, + 'parse-positional-numbers': true, + 'populate--': false, + 'set-placeholder-key': false, + 'short-option-groups': true, + 'strip-aliased': false, + 'strip-dashed': false, + 'unknown-options-as-args': false + }, opts.configuration); + const defaults = Object.assign(Object.create(null), opts.default); + const configObjects = opts.configObjects || []; + const envPrefix = opts.envPrefix; + const notFlagsOption = configuration['populate--']; + const notFlagsArgv = notFlagsOption ? '--' : '_'; + const newAliases = Object.create(null); + const defaulted = Object.create(null); + const __ = opts.__ || mixin.format; + const flags = { + aliases: Object.create(null), + arrays: Object.create(null), + bools: Object.create(null), + strings: Object.create(null), + numbers: Object.create(null), + counts: Object.create(null), + normalize: Object.create(null), + configs: Object.create(null), + nargs: Object.create(null), + coercions: Object.create(null), + keys: [] + }; + const negative = /^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/; + const negatedBoolean = new RegExp('^--' + configuration['negation-prefix'] + '(.+)'); + [].concat(opts.array || []).filter(Boolean).forEach(function (opt) { + const key = typeof opt === 'object' ? opt.key : opt; + const assignment = Object.keys(opt).map(function (key) { + const arrayFlagKeys = { + boolean: 'bools', + string: 'strings', + number: 'numbers' + }; + return arrayFlagKeys[key]; + }).filter(Boolean).pop(); + if (assignment) { + flags[assignment][key] = true; + } + flags.arrays[key] = true; + flags.keys.push(key); + }); + [].concat(opts.boolean || []).filter(Boolean).forEach(function (key) { + flags.bools[key] = true; + flags.keys.push(key); + }); + [].concat(opts.string || []).filter(Boolean).forEach(function (key) { + flags.strings[key] = true; + flags.keys.push(key); + }); + [].concat(opts.number || []).filter(Boolean).forEach(function (key) { + flags.numbers[key] = true; + flags.keys.push(key); + }); + [].concat(opts.count || []).filter(Boolean).forEach(function (key) { + flags.counts[key] = true; + flags.keys.push(key); + }); + [].concat(opts.normalize || []).filter(Boolean).forEach(function (key) { + flags.normalize[key] = true; + flags.keys.push(key); + }); + if (typeof opts.narg === 'object') { + Object.entries(opts.narg).forEach(([key, value]) => { + if (typeof value === 'number') { + flags.nargs[key] = value; + flags.keys.push(key); + } + }); + } + if (typeof opts.coerce === 'object') { + Object.entries(opts.coerce).forEach(([key, value]) => { + if (typeof value === 'function') { + flags.coercions[key] = value; + flags.keys.push(key); + } + }); + } + if (typeof opts.config !== 'undefined') { + if (Array.isArray(opts.config) || typeof opts.config === 'string') { + [].concat(opts.config).filter(Boolean).forEach(function (key) { + flags.configs[key] = true; + }); + } + else if (typeof opts.config === 'object') { + Object.entries(opts.config).forEach(([key, value]) => { + if (typeof value === 'boolean' || typeof value === 'function') { + flags.configs[key] = value; + } + }); + } + } + extendAliases(opts.key, aliases, opts.default, flags.arrays); + Object.keys(defaults).forEach(function (key) { + (flags.aliases[key] || []).forEach(function (alias) { + defaults[alias] = defaults[key]; + }); + }); + let error = null; + checkConfiguration(); + let notFlags = []; + const argv = Object.assign(Object.create(null), { _: [] }); + const argvReturn = {}; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + const truncatedArg = arg.replace(/^-{3,}/, '---'); + let broken; + let key; + let letters; + let m; + let next; + let value; + if (arg !== '--' && /^-/.test(arg) && isUnknownOptionAsArg(arg)) { + pushPositional(arg); + } + else if (truncatedArg.match(/^---+(=|$)/)) { + pushPositional(arg); + continue; + } + else if (arg.match(/^--.+=/) || (!configuration['short-option-groups'] && arg.match(/^-.+=/))) { + m = arg.match(/^--?([^=]+)=([\s\S]*)$/); + if (m !== null && Array.isArray(m) && m.length >= 3) { + if (checkAllAliases(m[1], flags.arrays)) { + i = eatArray(i, m[1], args, m[2]); + } + else if (checkAllAliases(m[1], flags.nargs) !== false) { + i = eatNargs(i, m[1], args, m[2]); + } + else { + setArg(m[1], m[2], true); + } + } + } + else if (arg.match(negatedBoolean) && configuration['boolean-negation']) { + m = arg.match(negatedBoolean); + if (m !== null && Array.isArray(m) && m.length >= 2) { + key = m[1]; + setArg(key, checkAllAliases(key, flags.arrays) ? [false] : false); + } + } + else if (arg.match(/^--.+/) || (!configuration['short-option-groups'] && arg.match(/^-[^-]+/))) { + m = arg.match(/^--?(.+)/); + if (m !== null && Array.isArray(m) && m.length >= 2) { + key = m[1]; + if (checkAllAliases(key, flags.arrays)) { + i = eatArray(i, key, args); + } + else if (checkAllAliases(key, flags.nargs) !== false) { + i = eatNargs(i, key, args); + } + else { + next = args[i + 1]; + if (next !== undefined && (!next.match(/^-/) || + next.match(negative)) && + !checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts)) { + setArg(key, next); + i++; + } + else if (/^(true|false)$/.test(next)) { + setArg(key, next); + i++; + } + else { + setArg(key, defaultValue(key)); + } + } + } + } + else if (arg.match(/^-.\..+=/)) { + m = arg.match(/^-([^=]+)=([\s\S]*)$/); + if (m !== null && Array.isArray(m) && m.length >= 3) { + setArg(m[1], m[2]); + } + } + else if (arg.match(/^-.\..+/) && !arg.match(negative)) { + next = args[i + 1]; + m = arg.match(/^-(.\..+)/); + if (m !== null && Array.isArray(m) && m.length >= 2) { + key = m[1]; + if (next !== undefined && !next.match(/^-/) && + !checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts)) { + setArg(key, next); + i++; + } + else { + setArg(key, defaultValue(key)); + } + } + } + else if (arg.match(/^-[^-]+/) && !arg.match(negative)) { + letters = arg.slice(1, -1).split(''); + broken = false; + for (let j = 0; j < letters.length; j++) { + next = arg.slice(j + 2); + if (letters[j + 1] && letters[j + 1] === '=') { + value = arg.slice(j + 3); + key = letters[j]; + if (checkAllAliases(key, flags.arrays)) { + i = eatArray(i, key, args, value); + } + else if (checkAllAliases(key, flags.nargs) !== false) { + i = eatNargs(i, key, args, value); + } + else { + setArg(key, value); + } + broken = true; + break; + } + if (next === '-') { + setArg(letters[j], next); + continue; + } + if (/[A-Za-z]/.test(letters[j]) && + /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) && + checkAllAliases(next, flags.bools) === false) { + setArg(letters[j], next); + broken = true; + break; + } + if (letters[j + 1] && letters[j + 1].match(/\W/)) { + setArg(letters[j], next); + broken = true; + break; + } + else { + setArg(letters[j], defaultValue(letters[j])); + } + } + key = arg.slice(-1)[0]; + if (!broken && key !== '-') { + if (checkAllAliases(key, flags.arrays)) { + i = eatArray(i, key, args); + } + else if (checkAllAliases(key, flags.nargs) !== false) { + i = eatNargs(i, key, args); + } + else { + next = args[i + 1]; + if (next !== undefined && (!/^(-|--)[^-]/.test(next) || + next.match(negative)) && + !checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts)) { + setArg(key, next); + i++; + } + else if (/^(true|false)$/.test(next)) { + setArg(key, next); + i++; + } + else { + setArg(key, defaultValue(key)); + } + } + } + } + else if (arg.match(/^-[0-9]$/) && + arg.match(negative) && + checkAllAliases(arg.slice(1), flags.bools)) { + key = arg.slice(1); + setArg(key, defaultValue(key)); + } + else if (arg === '--') { + notFlags = args.slice(i + 1); + break; + } + else if (configuration['halt-at-non-option']) { + notFlags = args.slice(i); + break; + } + else { + pushPositional(arg); + } + } + applyEnvVars(argv, true); + applyEnvVars(argv, false); + setConfig(argv); + setConfigObjects(); + applyDefaultsAndAliases(argv, flags.aliases, defaults, true); + applyCoercions(argv); + if (configuration['set-placeholder-key']) + setPlaceholderKeys(argv); + Object.keys(flags.counts).forEach(function (key) { + if (!hasKey(argv, key.split('.'))) + setArg(key, 0); + }); + if (notFlagsOption && notFlags.length) + argv[notFlagsArgv] = []; + notFlags.forEach(function (key) { + argv[notFlagsArgv].push(key); + }); + if (configuration['camel-case-expansion'] && configuration['strip-dashed']) { + Object.keys(argv).filter(key => key !== '--' && key.includes('-')).forEach(key => { + delete argv[key]; + }); + } + if (configuration['strip-aliased']) { + [].concat(...Object.keys(aliases).map(k => aliases[k])).forEach(alias => { + if (configuration['camel-case-expansion'] && alias.includes('-')) { + delete argv[alias.split('.').map(prop => camelCase(prop)).join('.')]; + } + delete argv[alias]; + }); + } + function pushPositional(arg) { + const maybeCoercedNumber = maybeCoerceNumber('_', arg); + if (typeof maybeCoercedNumber === 'string' || typeof maybeCoercedNumber === 'number') { + argv._.push(maybeCoercedNumber); + } + } + function eatNargs(i, key, args, argAfterEqualSign) { + let ii; + let toEat = checkAllAliases(key, flags.nargs); + toEat = typeof toEat !== 'number' || isNaN(toEat) ? 1 : toEat; + if (toEat === 0) { + if (!isUndefined(argAfterEqualSign)) { + error = Error(__('Argument unexpected for: %s', key)); + } + setArg(key, defaultValue(key)); + return i; + } + let available = isUndefined(argAfterEqualSign) ? 0 : 1; + if (configuration['nargs-eats-options']) { + if (args.length - (i + 1) + available < toEat) { + error = Error(__('Not enough arguments following: %s', key)); + } + available = toEat; + } + else { + for (ii = i + 1; ii < args.length; ii++) { + if (!args[ii].match(/^-[^0-9]/) || args[ii].match(negative) || isUnknownOptionAsArg(args[ii])) + available++; + else + break; + } + if (available < toEat) + error = Error(__('Not enough arguments following: %s', key)); + } + let consumed = Math.min(available, toEat); + if (!isUndefined(argAfterEqualSign) && consumed > 0) { + setArg(key, argAfterEqualSign); + consumed--; + } + for (ii = i + 1; ii < (consumed + i + 1); ii++) { + setArg(key, args[ii]); + } + return (i + consumed); + } + function eatArray(i, key, args, argAfterEqualSign) { + let argsToSet = []; + let next = argAfterEqualSign || args[i + 1]; + const nargsCount = checkAllAliases(key, flags.nargs); + if (checkAllAliases(key, flags.bools) && !(/^(true|false)$/.test(next))) { + argsToSet.push(true); + } + else if (isUndefined(next) || + (isUndefined(argAfterEqualSign) && /^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))) { + if (defaults[key] !== undefined) { + const defVal = defaults[key]; + argsToSet = Array.isArray(defVal) ? defVal : [defVal]; + } + } + else { + if (!isUndefined(argAfterEqualSign)) { + argsToSet.push(processValue(key, argAfterEqualSign, true)); + } + for (let ii = i + 1; ii < args.length; ii++) { + if ((!configuration['greedy-arrays'] && argsToSet.length > 0) || + (nargsCount && typeof nargsCount === 'number' && argsToSet.length >= nargsCount)) + break; + next = args[ii]; + if (/^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next)) + break; + i = ii; + argsToSet.push(processValue(key, next, inputIsString)); + } + } + if (typeof nargsCount === 'number' && ((nargsCount && argsToSet.length < nargsCount) || + (isNaN(nargsCount) && argsToSet.length === 0))) { + error = Error(__('Not enough arguments following: %s', key)); + } + setArg(key, argsToSet); + return i; + } + function setArg(key, val, shouldStripQuotes = inputIsString) { + if (/-/.test(key) && configuration['camel-case-expansion']) { + const alias = key.split('.').map(function (prop) { + return camelCase(prop); + }).join('.'); + addNewAlias(key, alias); + } + const value = processValue(key, val, shouldStripQuotes); + const splitKey = key.split('.'); + setKey(argv, splitKey, value); + if (flags.aliases[key]) { + flags.aliases[key].forEach(function (x) { + const keyProperties = x.split('.'); + setKey(argv, keyProperties, value); + }); + } + if (splitKey.length > 1 && configuration['dot-notation']) { + (flags.aliases[splitKey[0]] || []).forEach(function (x) { + let keyProperties = x.split('.'); + const a = [].concat(splitKey); + a.shift(); + keyProperties = keyProperties.concat(a); + if (!(flags.aliases[key] || []).includes(keyProperties.join('.'))) { + setKey(argv, keyProperties, value); + } + }); + } + if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) { + const keys = [key].concat(flags.aliases[key] || []); + keys.forEach(function (key) { + Object.defineProperty(argvReturn, key, { + enumerable: true, + get() { + return val; + }, + set(value) { + val = typeof value === 'string' ? mixin.normalize(value) : value; + } + }); + }); + } + } + function addNewAlias(key, alias) { + if (!(flags.aliases[key] && flags.aliases[key].length)) { + flags.aliases[key] = [alias]; + newAliases[alias] = true; + } + if (!(flags.aliases[alias] && flags.aliases[alias].length)) { + addNewAlias(alias, key); + } + } + function processValue(key, val, shouldStripQuotes) { + if (shouldStripQuotes) { + val = stripQuotes(val); + } + if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) { + if (typeof val === 'string') + val = val === 'true'; + } + let value = Array.isArray(val) + ? val.map(function (v) { return maybeCoerceNumber(key, v); }) + : maybeCoerceNumber(key, val); + if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === 'boolean')) { + value = increment(); + } + if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) { + if (Array.isArray(val)) + value = val.map((val) => { return mixin.normalize(val); }); + else + value = mixin.normalize(val); + } + return value; + } + function maybeCoerceNumber(key, value) { + if (!configuration['parse-positional-numbers'] && key === '_') + return value; + if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.bools) && !Array.isArray(value)) { + const shouldCoerceNumber = looksLikeNumber(value) && configuration['parse-numbers'] && (Number.isSafeInteger(Math.floor(parseFloat(`${value}`)))); + if (shouldCoerceNumber || (!isUndefined(value) && checkAllAliases(key, flags.numbers))) { + value = Number(value); + } + } + return value; + } + function setConfig(argv) { + const configLookup = Object.create(null); + applyDefaultsAndAliases(configLookup, flags.aliases, defaults); + Object.keys(flags.configs).forEach(function (configKey) { + const configPath = argv[configKey] || configLookup[configKey]; + if (configPath) { + try { + let config = null; + const resolvedConfigPath = mixin.resolve(mixin.cwd(), configPath); + const resolveConfig = flags.configs[configKey]; + if (typeof resolveConfig === 'function') { + try { + config = resolveConfig(resolvedConfigPath); + } + catch (e) { + config = e; + } + if (config instanceof Error) { + error = config; + return; + } + } + else { + config = mixin.require(resolvedConfigPath); + } + setConfigObject(config); + } + catch (ex) { + if (ex.name === 'PermissionDenied') + error = ex; + else if (argv[configKey]) + error = Error(__('Invalid JSON config file: %s', configPath)); + } + } + }); + } + function setConfigObject(config, prev) { + Object.keys(config).forEach(function (key) { + const value = config[key]; + const fullKey = prev ? prev + '.' + key : key; + if (typeof value === 'object' && value !== null && !Array.isArray(value) && configuration['dot-notation']) { + setConfigObject(value, fullKey); + } + else { + if (!hasKey(argv, fullKey.split('.')) || (checkAllAliases(fullKey, flags.arrays) && configuration['combine-arrays'])) { + setArg(fullKey, value); + } + } + }); + } + function setConfigObjects() { + if (typeof configObjects !== 'undefined') { + configObjects.forEach(function (configObject) { + setConfigObject(configObject); + }); + } + } + function applyEnvVars(argv, configOnly) { + if (typeof envPrefix === 'undefined') + return; + const prefix = typeof envPrefix === 'string' ? envPrefix : ''; + const env = mixin.env(); + Object.keys(env).forEach(function (envVar) { + if (prefix === '' || envVar.lastIndexOf(prefix, 0) === 0) { + const keys = envVar.split('__').map(function (key, i) { + if (i === 0) { + key = key.substring(prefix.length); + } + return camelCase(key); + }); + if (((configOnly && flags.configs[keys.join('.')]) || !configOnly) && !hasKey(argv, keys)) { + setArg(keys.join('.'), env[envVar]); + } + } + }); + } + function applyCoercions(argv) { + let coerce; + const applied = new Set(); + Object.keys(argv).forEach(function (key) { + if (!applied.has(key)) { + coerce = checkAllAliases(key, flags.coercions); + if (typeof coerce === 'function') { + try { + const value = maybeCoerceNumber(key, coerce(argv[key])); + ([].concat(flags.aliases[key] || [], key)).forEach(ali => { + applied.add(ali); + argv[ali] = value; + }); + } + catch (err) { + error = err; + } + } + } + }); + } + function setPlaceholderKeys(argv) { + flags.keys.forEach((key) => { + if (~key.indexOf('.')) + return; + if (typeof argv[key] === 'undefined') + argv[key] = undefined; + }); + return argv; + } + function applyDefaultsAndAliases(obj, aliases, defaults, canLog = false) { + Object.keys(defaults).forEach(function (key) { + if (!hasKey(obj, key.split('.'))) { + setKey(obj, key.split('.'), defaults[key]); + if (canLog) + defaulted[key] = true; + (aliases[key] || []).forEach(function (x) { + if (hasKey(obj, x.split('.'))) + return; + setKey(obj, x.split('.'), defaults[key]); + }); + } + }); + } + function hasKey(obj, keys) { + let o = obj; + if (!configuration['dot-notation']) + keys = [keys.join('.')]; + keys.slice(0, -1).forEach(function (key) { + o = (o[key] || {}); + }); + const key = keys[keys.length - 1]; + if (typeof o !== 'object') + return false; + else + return key in o; + } + function setKey(obj, keys, value) { + let o = obj; + if (!configuration['dot-notation']) + keys = [keys.join('.')]; + keys.slice(0, -1).forEach(function (key) { + key = sanitizeKey(key); + if (typeof o === 'object' && o[key] === undefined) { + o[key] = {}; + } + if (typeof o[key] !== 'object' || Array.isArray(o[key])) { + if (Array.isArray(o[key])) { + o[key].push({}); + } + else { + o[key] = [o[key], {}]; + } + o = o[key][o[key].length - 1]; + } + else { + o = o[key]; + } + }); + const key = sanitizeKey(keys[keys.length - 1]); + const isTypeArray = checkAllAliases(keys.join('.'), flags.arrays); + const isValueArray = Array.isArray(value); + let duplicate = configuration['duplicate-arguments-array']; + if (!duplicate && checkAllAliases(key, flags.nargs)) { + duplicate = true; + if ((!isUndefined(o[key]) && flags.nargs[key] === 1) || (Array.isArray(o[key]) && o[key].length === flags.nargs[key])) { + o[key] = undefined; + } + } + if (value === increment()) { + o[key] = increment(o[key]); + } + else if (Array.isArray(o[key])) { + if (duplicate && isTypeArray && isValueArray) { + o[key] = configuration['flatten-duplicate-arrays'] ? o[key].concat(value) : (Array.isArray(o[key][0]) ? o[key] : [o[key]]).concat([value]); + } + else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) { + o[key] = value; + } + else { + o[key] = o[key].concat([value]); + } + } + else if (o[key] === undefined && isTypeArray) { + o[key] = isValueArray ? value : [value]; + } + else if (duplicate && !(o[key] === undefined || + checkAllAliases(key, flags.counts) || + checkAllAliases(key, flags.bools))) { + o[key] = [o[key], value]; + } + else { + o[key] = value; + } + } + function extendAliases(...args) { + args.forEach(function (obj) { + Object.keys(obj || {}).forEach(function (key) { + if (flags.aliases[key]) + return; + flags.aliases[key] = [].concat(aliases[key] || []); + flags.aliases[key].concat(key).forEach(function (x) { + if (/-/.test(x) && configuration['camel-case-expansion']) { + const c = camelCase(x); + if (c !== key && flags.aliases[key].indexOf(c) === -1) { + flags.aliases[key].push(c); + newAliases[c] = true; + } + } + }); + flags.aliases[key].concat(key).forEach(function (x) { + if (x.length > 1 && /[A-Z]/.test(x) && configuration['camel-case-expansion']) { + const c = decamelize(x, '-'); + if (c !== key && flags.aliases[key].indexOf(c) === -1) { + flags.aliases[key].push(c); + newAliases[c] = true; + } + } + }); + flags.aliases[key].forEach(function (x) { + flags.aliases[x] = [key].concat(flags.aliases[key].filter(function (y) { + return x !== y; + })); + }); + }); + }); + } + function checkAllAliases(key, flag) { + const toCheck = [].concat(flags.aliases[key] || [], key); + const keys = Object.keys(flag); + const setAlias = toCheck.find(key => keys.includes(key)); + return setAlias ? flag[setAlias] : false; + } + function hasAnyFlag(key) { + const flagsKeys = Object.keys(flags); + const toCheck = [].concat(flagsKeys.map(k => flags[k])); + return toCheck.some(function (flag) { + return Array.isArray(flag) ? flag.includes(key) : flag[key]; + }); + } + function hasFlagsMatching(arg, ...patterns) { + const toCheck = [].concat(...patterns); + return toCheck.some(function (pattern) { + const match = arg.match(pattern); + return match && hasAnyFlag(match[1]); + }); + } + function hasAllShortFlags(arg) { + if (arg.match(negative) || !arg.match(/^-[^-]+/)) { + return false; + } + let hasAllFlags = true; + let next; + const letters = arg.slice(1).split(''); + for (let j = 0; j < letters.length; j++) { + next = arg.slice(j + 2); + if (!hasAnyFlag(letters[j])) { + hasAllFlags = false; + break; + } + if ((letters[j + 1] && letters[j + 1] === '=') || + next === '-' || + (/[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) || + (letters[j + 1] && letters[j + 1].match(/\W/))) { + break; + } + } + return hasAllFlags; + } + function isUnknownOptionAsArg(arg) { + return configuration['unknown-options-as-args'] && isUnknownOption(arg); + } + function isUnknownOption(arg) { + arg = arg.replace(/^-{3,}/, '--'); + if (arg.match(negative)) { + return false; + } + if (hasAllShortFlags(arg)) { + return false; + } + const flagWithEquals = /^-+([^=]+?)=[\s\S]*$/; + const normalFlag = /^-+([^=]+?)$/; + const flagEndingInHyphen = /^-+([^=]+?)-$/; + const flagEndingInDigits = /^-+([^=]+?\d+)$/; + const flagEndingInNonWordCharacters = /^-+([^=]+?)\W+.*$/; + return !hasFlagsMatching(arg, flagWithEquals, negatedBoolean, normalFlag, flagEndingInHyphen, flagEndingInDigits, flagEndingInNonWordCharacters); + } + function defaultValue(key) { + if (!checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts) && + `${key}` in defaults) { + return defaults[key]; + } + else { + return defaultForType(guessType(key)); + } + } + function defaultForType(type) { + const def = { + [DefaultValuesForTypeKey.BOOLEAN]: true, + [DefaultValuesForTypeKey.STRING]: '', + [DefaultValuesForTypeKey.NUMBER]: undefined, + [DefaultValuesForTypeKey.ARRAY]: [] + }; + return def[type]; + } + function guessType(key) { + let type = DefaultValuesForTypeKey.BOOLEAN; + if (checkAllAliases(key, flags.strings)) + type = DefaultValuesForTypeKey.STRING; + else if (checkAllAliases(key, flags.numbers)) + type = DefaultValuesForTypeKey.NUMBER; + else if (checkAllAliases(key, flags.bools)) + type = DefaultValuesForTypeKey.BOOLEAN; + else if (checkAllAliases(key, flags.arrays)) + type = DefaultValuesForTypeKey.ARRAY; + return type; + } + function isUndefined(num) { + return num === undefined; + } + function checkConfiguration() { + Object.keys(flags.counts).find(key => { + if (checkAllAliases(key, flags.arrays)) { + error = Error(__('Invalid configuration: %s, opts.count excludes opts.array.', key)); + return true; + } + else if (checkAllAliases(key, flags.nargs)) { + error = Error(__('Invalid configuration: %s, opts.count excludes opts.narg.', key)); + return true; + } + return false; + }); + } + return { + aliases: Object.assign({}, flags.aliases), + argv: Object.assign(argvReturn, argv), + configuration: configuration, + defaulted: Object.assign({}, defaulted), + error: error, + newAliases: Object.assign({}, newAliases) + }; + } +} +function combineAliases(aliases) { + const aliasArrays = []; + const combined = Object.create(null); + let change = true; + Object.keys(aliases).forEach(function (key) { + aliasArrays.push([].concat(aliases[key], key)); + }); + while (change) { + change = false; + for (let i = 0; i < aliasArrays.length; i++) { + for (let ii = i + 1; ii < aliasArrays.length; ii++) { + const intersect = aliasArrays[i].filter(function (v) { + return aliasArrays[ii].indexOf(v) !== -1; + }); + if (intersect.length) { + aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii]); + aliasArrays.splice(ii, 1); + change = true; + break; + } + } + } + } + aliasArrays.forEach(function (aliasArray) { + aliasArray = aliasArray.filter(function (v, i, self) { + return self.indexOf(v) === i; + }); + const lastAlias = aliasArray.pop(); + if (lastAlias !== undefined && typeof lastAlias === 'string') { + combined[lastAlias] = aliasArray; + } + }); + return combined; +} +function increment(orig) { + return orig !== undefined ? orig + 1 : 1; +} +function sanitizeKey(key) { + if (key === '__proto__') + return '___proto___'; + return key; +} +function stripQuotes(val) { + return (typeof val === 'string' && + (val[0] === "'" || val[0] === '"') && + val[val.length - 1] === val[0]) + ? val.substring(1, val.length - 1) + : val; +} + +var _a, _b, _c; +const minNodeVersion = (process && process.env && process.env.YARGS_MIN_NODE_VERSION) + ? Number(process.env.YARGS_MIN_NODE_VERSION) + : 12; +const nodeVersion = (_b = (_a = process === null || process === void 0 ? void 0 : process.versions) === null || _a === void 0 ? void 0 : _a.node) !== null && _b !== void 0 ? _b : (_c = process === null || process === void 0 ? void 0 : process.version) === null || _c === void 0 ? void 0 : _c.slice(1); +if (nodeVersion) { + const major = Number(nodeVersion.match(/^([^.]+)/)[1]); + if (major < minNodeVersion) { + throw Error(`yargs parser supports a minimum Node.js version of ${minNodeVersion}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`); + } +} +const env = process ? process.env : {}; +const parser = new YargsParser({ + cwd: process.cwd, + env: () => { + return env; + }, + format: util.format, + normalize: path.normalize, + resolve: path.resolve, + require: (path) => { + if (typeof require !== 'undefined') { + return require(path); + } + else if (path.match(/\.json$/)) { + return JSON.parse(fs.readFileSync(path, 'utf8')); + } + else { + throw Error('only .json config files are supported in ESM'); + } + } +}); +const yargsParser = function Parser(args, opts) { + const result = parser.parse(args.slice(), opts); + return result.argv; +}; +yargsParser.detailed = function (args, opts) { + return parser.parse(args.slice(), opts); +}; +yargsParser.camelCase = camelCase; +yargsParser.decamelize = decamelize; +yargsParser.looksLikeNumber = looksLikeNumber; + +module.exports = yargsParser; diff --git a/node_modules/yargs-parser/build/lib/index.js b/node_modules/yargs-parser/build/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..43ef485abc049c432ce5ef8e50a702dd05f78915 --- /dev/null +++ b/node_modules/yargs-parser/build/lib/index.js @@ -0,0 +1,62 @@ +/** + * @fileoverview Main entrypoint for libraries using yargs-parser in Node.js + * CJS and ESM environments. + * + * @license + * Copyright (c) 2016, Contributors + * SPDX-License-Identifier: ISC + */ +var _a, _b, _c; +import { format } from 'util'; +import { normalize, resolve } from 'path'; +import { camelCase, decamelize, looksLikeNumber } from './string-utils.js'; +import { YargsParser } from './yargs-parser.js'; +import { readFileSync } from 'fs'; +// See https://github.com/yargs/yargs-parser#supported-nodejs-versions for our +// version support policy. The YARGS_MIN_NODE_VERSION is used for testing only. +const minNodeVersion = (process && process.env && process.env.YARGS_MIN_NODE_VERSION) + ? Number(process.env.YARGS_MIN_NODE_VERSION) + : 12; +const nodeVersion = (_b = (_a = process === null || process === void 0 ? void 0 : process.versions) === null || _a === void 0 ? void 0 : _a.node) !== null && _b !== void 0 ? _b : (_c = process === null || process === void 0 ? void 0 : process.version) === null || _c === void 0 ? void 0 : _c.slice(1); +if (nodeVersion) { + const major = Number(nodeVersion.match(/^([^.]+)/)[1]); + if (major < minNodeVersion) { + throw Error(`yargs parser supports a minimum Node.js version of ${minNodeVersion}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`); + } +} +// Creates a yargs-parser instance using Node.js standard libraries: +const env = process ? process.env : {}; +const parser = new YargsParser({ + cwd: process.cwd, + env: () => { + return env; + }, + format, + normalize, + resolve, + // TODO: figure out a way to combine ESM and CJS coverage, such that + // we can exercise all the lines below: + require: (path) => { + if (typeof require !== 'undefined') { + return require(path); + } + else if (path.match(/\.json$/)) { + // Addresses: https://github.com/yargs/yargs/issues/2040 + return JSON.parse(readFileSync(path, 'utf8')); + } + else { + throw Error('only .json config files are supported in ESM'); + } + } +}); +const yargsParser = function Parser(args, opts) { + const result = parser.parse(args.slice(), opts); + return result.argv; +}; +yargsParser.detailed = function (args, opts) { + return parser.parse(args.slice(), opts); +}; +yargsParser.camelCase = camelCase; +yargsParser.decamelize = decamelize; +yargsParser.looksLikeNumber = looksLikeNumber; +export default yargsParser; diff --git a/node_modules/yargs-parser/build/lib/string-utils.js b/node_modules/yargs-parser/build/lib/string-utils.js new file mode 100644 index 0000000000000000000000000000000000000000..4e8bd996e7a97a2c1e9c9fc4919044a171b73918 --- /dev/null +++ b/node_modules/yargs-parser/build/lib/string-utils.js @@ -0,0 +1,65 @@ +/** + * @license + * Copyright (c) 2016, Contributors + * SPDX-License-Identifier: ISC + */ +export function camelCase(str) { + // Handle the case where an argument is provided as camel case, e.g., fooBar. + // by ensuring that the string isn't already mixed case: + const isCamelCase = str !== str.toLowerCase() && str !== str.toUpperCase(); + if (!isCamelCase) { + str = str.toLowerCase(); + } + if (str.indexOf('-') === -1 && str.indexOf('_') === -1) { + return str; + } + else { + let camelcase = ''; + let nextChrUpper = false; + const leadingHyphens = str.match(/^-+/); + for (let i = leadingHyphens ? leadingHyphens[0].length : 0; i < str.length; i++) { + let chr = str.charAt(i); + if (nextChrUpper) { + nextChrUpper = false; + chr = chr.toUpperCase(); + } + if (i !== 0 && (chr === '-' || chr === '_')) { + nextChrUpper = true; + } + else if (chr !== '-' && chr !== '_') { + camelcase += chr; + } + } + return camelcase; + } +} +export function decamelize(str, joinString) { + const lowercase = str.toLowerCase(); + joinString = joinString || '-'; + let notCamelcase = ''; + for (let i = 0; i < str.length; i++) { + const chrLower = lowercase.charAt(i); + const chrString = str.charAt(i); + if (chrLower !== chrString && i > 0) { + notCamelcase += `${joinString}${lowercase.charAt(i)}`; + } + else { + notCamelcase += chrString; + } + } + return notCamelcase; +} +export function looksLikeNumber(x) { + if (x === null || x === undefined) + return false; + // if loaded from config, may already be a number. + if (typeof x === 'number') + return true; + // hexadecimal. + if (/^0x[0-9a-f]+$/i.test(x)) + return true; + // don't treat 0123 as a number; as it drops the leading '0'. + if (/^0[^.]/.test(x)) + return false; + return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); +} diff --git a/node_modules/yargs-parser/build/lib/tokenize-arg-string.js b/node_modules/yargs-parser/build/lib/tokenize-arg-string.js new file mode 100644 index 0000000000000000000000000000000000000000..5e732efe019ab064effaa667bfe7bf904a5f1cb0 --- /dev/null +++ b/node_modules/yargs-parser/build/lib/tokenize-arg-string.js @@ -0,0 +1,40 @@ +/** + * @license + * Copyright (c) 2016, Contributors + * SPDX-License-Identifier: ISC + */ +// take an un-split argv string and tokenize it. +export function tokenizeArgString(argString) { + if (Array.isArray(argString)) { + return argString.map(e => typeof e !== 'string' ? e + '' : e); + } + argString = argString.trim(); + let i = 0; + let prevC = null; + let c = null; + let opening = null; + const args = []; + for (let ii = 0; ii < argString.length; ii++) { + prevC = c; + c = argString.charAt(ii); + // split on spaces unless we're in quotes. + if (c === ' ' && !opening) { + if (!(prevC === ' ')) { + i++; + } + continue; + } + // don't split the string if we're in matching + // opening or closing single and double quotes. + if (c === opening) { + opening = null; + } + else if ((c === "'" || c === '"') && !opening) { + opening = c; + } + if (!args[i]) + args[i] = ''; + args[i] += c; + } + return args; +} diff --git a/node_modules/yargs-parser/build/lib/yargs-parser-types.js b/node_modules/yargs-parser/build/lib/yargs-parser-types.js new file mode 100644 index 0000000000000000000000000000000000000000..63b7c313aa9b5fe645373222c88c5bccb19b806c --- /dev/null +++ b/node_modules/yargs-parser/build/lib/yargs-parser-types.js @@ -0,0 +1,12 @@ +/** + * @license + * Copyright (c) 2016, Contributors + * SPDX-License-Identifier: ISC + */ +export var DefaultValuesForTypeKey; +(function (DefaultValuesForTypeKey) { + DefaultValuesForTypeKey["BOOLEAN"] = "boolean"; + DefaultValuesForTypeKey["STRING"] = "string"; + DefaultValuesForTypeKey["NUMBER"] = "number"; + DefaultValuesForTypeKey["ARRAY"] = "array"; +})(DefaultValuesForTypeKey || (DefaultValuesForTypeKey = {})); diff --git a/node_modules/yargs-parser/build/lib/yargs-parser.js b/node_modules/yargs-parser/build/lib/yargs-parser.js new file mode 100644 index 0000000000000000000000000000000000000000..415d4bc8cb87a5b91d4ada8add37f250dca5b3a0 --- /dev/null +++ b/node_modules/yargs-parser/build/lib/yargs-parser.js @@ -0,0 +1,1045 @@ +/** + * @license + * Copyright (c) 2016, Contributors + * SPDX-License-Identifier: ISC + */ +import { tokenizeArgString } from './tokenize-arg-string.js'; +import { DefaultValuesForTypeKey } from './yargs-parser-types.js'; +import { camelCase, decamelize, looksLikeNumber } from './string-utils.js'; +let mixin; +export class YargsParser { + constructor(_mixin) { + mixin = _mixin; + } + parse(argsInput, options) { + const opts = Object.assign({ + alias: undefined, + array: undefined, + boolean: undefined, + config: undefined, + configObjects: undefined, + configuration: undefined, + coerce: undefined, + count: undefined, + default: undefined, + envPrefix: undefined, + narg: undefined, + normalize: undefined, + string: undefined, + number: undefined, + __: undefined, + key: undefined + }, options); + // allow a string argument to be passed in rather + // than an argv array. + const args = tokenizeArgString(argsInput); + // tokenizeArgString adds extra quotes to args if argsInput is a string + // only strip those extra quotes in processValue if argsInput is a string + const inputIsString = typeof argsInput === 'string'; + // aliases might have transitive relationships, normalize this. + const aliases = combineAliases(Object.assign(Object.create(null), opts.alias)); + const configuration = Object.assign({ + 'boolean-negation': true, + 'camel-case-expansion': true, + 'combine-arrays': false, + 'dot-notation': true, + 'duplicate-arguments-array': true, + 'flatten-duplicate-arrays': true, + 'greedy-arrays': true, + 'halt-at-non-option': false, + 'nargs-eats-options': false, + 'negation-prefix': 'no-', + 'parse-numbers': true, + 'parse-positional-numbers': true, + 'populate--': false, + 'set-placeholder-key': false, + 'short-option-groups': true, + 'strip-aliased': false, + 'strip-dashed': false, + 'unknown-options-as-args': false + }, opts.configuration); + const defaults = Object.assign(Object.create(null), opts.default); + const configObjects = opts.configObjects || []; + const envPrefix = opts.envPrefix; + const notFlagsOption = configuration['populate--']; + const notFlagsArgv = notFlagsOption ? '--' : '_'; + const newAliases = Object.create(null); + const defaulted = Object.create(null); + // allow a i18n handler to be passed in, default to a fake one (util.format). + const __ = opts.__ || mixin.format; + const flags = { + aliases: Object.create(null), + arrays: Object.create(null), + bools: Object.create(null), + strings: Object.create(null), + numbers: Object.create(null), + counts: Object.create(null), + normalize: Object.create(null), + configs: Object.create(null), + nargs: Object.create(null), + coercions: Object.create(null), + keys: [] + }; + const negative = /^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/; + const negatedBoolean = new RegExp('^--' + configuration['negation-prefix'] + '(.+)'); + [].concat(opts.array || []).filter(Boolean).forEach(function (opt) { + const key = typeof opt === 'object' ? opt.key : opt; + // assign to flags[bools|strings|numbers] + const assignment = Object.keys(opt).map(function (key) { + const arrayFlagKeys = { + boolean: 'bools', + string: 'strings', + number: 'numbers' + }; + return arrayFlagKeys[key]; + }).filter(Boolean).pop(); + // assign key to be coerced + if (assignment) { + flags[assignment][key] = true; + } + flags.arrays[key] = true; + flags.keys.push(key); + }); + [].concat(opts.boolean || []).filter(Boolean).forEach(function (key) { + flags.bools[key] = true; + flags.keys.push(key); + }); + [].concat(opts.string || []).filter(Boolean).forEach(function (key) { + flags.strings[key] = true; + flags.keys.push(key); + }); + [].concat(opts.number || []).filter(Boolean).forEach(function (key) { + flags.numbers[key] = true; + flags.keys.push(key); + }); + [].concat(opts.count || []).filter(Boolean).forEach(function (key) { + flags.counts[key] = true; + flags.keys.push(key); + }); + [].concat(opts.normalize || []).filter(Boolean).forEach(function (key) { + flags.normalize[key] = true; + flags.keys.push(key); + }); + if (typeof opts.narg === 'object') { + Object.entries(opts.narg).forEach(([key, value]) => { + if (typeof value === 'number') { + flags.nargs[key] = value; + flags.keys.push(key); + } + }); + } + if (typeof opts.coerce === 'object') { + Object.entries(opts.coerce).forEach(([key, value]) => { + if (typeof value === 'function') { + flags.coercions[key] = value; + flags.keys.push(key); + } + }); + } + if (typeof opts.config !== 'undefined') { + if (Array.isArray(opts.config) || typeof opts.config === 'string') { + ; + [].concat(opts.config).filter(Boolean).forEach(function (key) { + flags.configs[key] = true; + }); + } + else if (typeof opts.config === 'object') { + Object.entries(opts.config).forEach(([key, value]) => { + if (typeof value === 'boolean' || typeof value === 'function') { + flags.configs[key] = value; + } + }); + } + } + // create a lookup table that takes into account all + // combinations of aliases: {f: ['foo'], foo: ['f']} + extendAliases(opts.key, aliases, opts.default, flags.arrays); + // apply default values to all aliases. + Object.keys(defaults).forEach(function (key) { + (flags.aliases[key] || []).forEach(function (alias) { + defaults[alias] = defaults[key]; + }); + }); + let error = null; + checkConfiguration(); + let notFlags = []; + const argv = Object.assign(Object.create(null), { _: [] }); + // TODO(bcoe): for the first pass at removing object prototype we didn't + // remove all prototypes from objects returned by this API, we might want + // to gradually move towards doing so. + const argvReturn = {}; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + const truncatedArg = arg.replace(/^-{3,}/, '---'); + let broken; + let key; + let letters; + let m; + let next; + let value; + // any unknown option (except for end-of-options, "--") + if (arg !== '--' && /^-/.test(arg) && isUnknownOptionAsArg(arg)) { + pushPositional(arg); + // ---, ---=, ----, etc, + } + else if (truncatedArg.match(/^---+(=|$)/)) { + // options without key name are invalid. + pushPositional(arg); + continue; + // -- separated by = + } + else if (arg.match(/^--.+=/) || (!configuration['short-option-groups'] && arg.match(/^-.+=/))) { + // Using [\s\S] instead of . because js doesn't support the + // 'dotall' regex modifier. See: + // http://stackoverflow.com/a/1068308/13216 + m = arg.match(/^--?([^=]+)=([\s\S]*)$/); + // arrays format = '--f=a b c' + if (m !== null && Array.isArray(m) && m.length >= 3) { + if (checkAllAliases(m[1], flags.arrays)) { + i = eatArray(i, m[1], args, m[2]); + } + else if (checkAllAliases(m[1], flags.nargs) !== false) { + // nargs format = '--f=monkey washing cat' + i = eatNargs(i, m[1], args, m[2]); + } + else { + setArg(m[1], m[2], true); + } + } + } + else if (arg.match(negatedBoolean) && configuration['boolean-negation']) { + m = arg.match(negatedBoolean); + if (m !== null && Array.isArray(m) && m.length >= 2) { + key = m[1]; + setArg(key, checkAllAliases(key, flags.arrays) ? [false] : false); + } + // -- separated by space. + } + else if (arg.match(/^--.+/) || (!configuration['short-option-groups'] && arg.match(/^-[^-]+/))) { + m = arg.match(/^--?(.+)/); + if (m !== null && Array.isArray(m) && m.length >= 2) { + key = m[1]; + if (checkAllAliases(key, flags.arrays)) { + // array format = '--foo a b c' + i = eatArray(i, key, args); + } + else if (checkAllAliases(key, flags.nargs) !== false) { + // nargs format = '--foo a b c' + // should be truthy even if: flags.nargs[key] === 0 + i = eatNargs(i, key, args); + } + else { + next = args[i + 1]; + if (next !== undefined && (!next.match(/^-/) || + next.match(negative)) && + !checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts)) { + setArg(key, next); + i++; + } + else if (/^(true|false)$/.test(next)) { + setArg(key, next); + i++; + } + else { + setArg(key, defaultValue(key)); + } + } + } + // dot-notation flag separated by '='. + } + else if (arg.match(/^-.\..+=/)) { + m = arg.match(/^-([^=]+)=([\s\S]*)$/); + if (m !== null && Array.isArray(m) && m.length >= 3) { + setArg(m[1], m[2]); + } + // dot-notation flag separated by space. + } + else if (arg.match(/^-.\..+/) && !arg.match(negative)) { + next = args[i + 1]; + m = arg.match(/^-(.\..+)/); + if (m !== null && Array.isArray(m) && m.length >= 2) { + key = m[1]; + if (next !== undefined && !next.match(/^-/) && + !checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts)) { + setArg(key, next); + i++; + } + else { + setArg(key, defaultValue(key)); + } + } + } + else if (arg.match(/^-[^-]+/) && !arg.match(negative)) { + letters = arg.slice(1, -1).split(''); + broken = false; + for (let j = 0; j < letters.length; j++) { + next = arg.slice(j + 2); + if (letters[j + 1] && letters[j + 1] === '=') { + value = arg.slice(j + 3); + key = letters[j]; + if (checkAllAliases(key, flags.arrays)) { + // array format = '-f=a b c' + i = eatArray(i, key, args, value); + } + else if (checkAllAliases(key, flags.nargs) !== false) { + // nargs format = '-f=monkey washing cat' + i = eatNargs(i, key, args, value); + } + else { + setArg(key, value); + } + broken = true; + break; + } + if (next === '-') { + setArg(letters[j], next); + continue; + } + // current letter is an alphabetic character and next value is a number + if (/[A-Za-z]/.test(letters[j]) && + /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) && + checkAllAliases(next, flags.bools) === false) { + setArg(letters[j], next); + broken = true; + break; + } + if (letters[j + 1] && letters[j + 1].match(/\W/)) { + setArg(letters[j], next); + broken = true; + break; + } + else { + setArg(letters[j], defaultValue(letters[j])); + } + } + key = arg.slice(-1)[0]; + if (!broken && key !== '-') { + if (checkAllAliases(key, flags.arrays)) { + // array format = '-f a b c' + i = eatArray(i, key, args); + } + else if (checkAllAliases(key, flags.nargs) !== false) { + // nargs format = '-f a b c' + // should be truthy even if: flags.nargs[key] === 0 + i = eatNargs(i, key, args); + } + else { + next = args[i + 1]; + if (next !== undefined && (!/^(-|--)[^-]/.test(next) || + next.match(negative)) && + !checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts)) { + setArg(key, next); + i++; + } + else if (/^(true|false)$/.test(next)) { + setArg(key, next); + i++; + } + else { + setArg(key, defaultValue(key)); + } + } + } + } + else if (arg.match(/^-[0-9]$/) && + arg.match(negative) && + checkAllAliases(arg.slice(1), flags.bools)) { + // single-digit boolean alias, e.g: xargs -0 + key = arg.slice(1); + setArg(key, defaultValue(key)); + } + else if (arg === '--') { + notFlags = args.slice(i + 1); + break; + } + else if (configuration['halt-at-non-option']) { + notFlags = args.slice(i); + break; + } + else { + pushPositional(arg); + } + } + // order of precedence: + // 1. command line arg + // 2. value from env var + // 3. value from config file + // 4. value from config objects + // 5. configured default value + applyEnvVars(argv, true); // special case: check env vars that point to config file + applyEnvVars(argv, false); + setConfig(argv); + setConfigObjects(); + applyDefaultsAndAliases(argv, flags.aliases, defaults, true); + applyCoercions(argv); + if (configuration['set-placeholder-key']) + setPlaceholderKeys(argv); + // for any counts either not in args or without an explicit default, set to 0 + Object.keys(flags.counts).forEach(function (key) { + if (!hasKey(argv, key.split('.'))) + setArg(key, 0); + }); + // '--' defaults to undefined. + if (notFlagsOption && notFlags.length) + argv[notFlagsArgv] = []; + notFlags.forEach(function (key) { + argv[notFlagsArgv].push(key); + }); + if (configuration['camel-case-expansion'] && configuration['strip-dashed']) { + Object.keys(argv).filter(key => key !== '--' && key.includes('-')).forEach(key => { + delete argv[key]; + }); + } + if (configuration['strip-aliased']) { + ; + [].concat(...Object.keys(aliases).map(k => aliases[k])).forEach(alias => { + if (configuration['camel-case-expansion'] && alias.includes('-')) { + delete argv[alias.split('.').map(prop => camelCase(prop)).join('.')]; + } + delete argv[alias]; + }); + } + // Push argument into positional array, applying numeric coercion: + function pushPositional(arg) { + const maybeCoercedNumber = maybeCoerceNumber('_', arg); + if (typeof maybeCoercedNumber === 'string' || typeof maybeCoercedNumber === 'number') { + argv._.push(maybeCoercedNumber); + } + } + // how many arguments should we consume, based + // on the nargs option? + function eatNargs(i, key, args, argAfterEqualSign) { + let ii; + let toEat = checkAllAliases(key, flags.nargs); + // NaN has a special meaning for the array type, indicating that one or + // more values are expected. + toEat = typeof toEat !== 'number' || isNaN(toEat) ? 1 : toEat; + if (toEat === 0) { + if (!isUndefined(argAfterEqualSign)) { + error = Error(__('Argument unexpected for: %s', key)); + } + setArg(key, defaultValue(key)); + return i; + } + let available = isUndefined(argAfterEqualSign) ? 0 : 1; + if (configuration['nargs-eats-options']) { + // classic behavior, yargs eats positional and dash arguments. + if (args.length - (i + 1) + available < toEat) { + error = Error(__('Not enough arguments following: %s', key)); + } + available = toEat; + } + else { + // nargs will not consume flag arguments, e.g., -abc, --foo, + // and terminates when one is observed. + for (ii = i + 1; ii < args.length; ii++) { + if (!args[ii].match(/^-[^0-9]/) || args[ii].match(negative) || isUnknownOptionAsArg(args[ii])) + available++; + else + break; + } + if (available < toEat) + error = Error(__('Not enough arguments following: %s', key)); + } + let consumed = Math.min(available, toEat); + if (!isUndefined(argAfterEqualSign) && consumed > 0) { + setArg(key, argAfterEqualSign); + consumed--; + } + for (ii = i + 1; ii < (consumed + i + 1); ii++) { + setArg(key, args[ii]); + } + return (i + consumed); + } + // if an option is an array, eat all non-hyphenated arguments + // following it... YUM! + // e.g., --foo apple banana cat becomes ["apple", "banana", "cat"] + function eatArray(i, key, args, argAfterEqualSign) { + let argsToSet = []; + let next = argAfterEqualSign || args[i + 1]; + // If both array and nargs are configured, enforce the nargs count: + const nargsCount = checkAllAliases(key, flags.nargs); + if (checkAllAliases(key, flags.bools) && !(/^(true|false)$/.test(next))) { + argsToSet.push(true); + } + else if (isUndefined(next) || + (isUndefined(argAfterEqualSign) && /^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))) { + // for keys without value ==> argsToSet remains an empty [] + // set user default value, if available + if (defaults[key] !== undefined) { + const defVal = defaults[key]; + argsToSet = Array.isArray(defVal) ? defVal : [defVal]; + } + } + else { + // value in --option=value is eaten as is + if (!isUndefined(argAfterEqualSign)) { + argsToSet.push(processValue(key, argAfterEqualSign, true)); + } + for (let ii = i + 1; ii < args.length; ii++) { + if ((!configuration['greedy-arrays'] && argsToSet.length > 0) || + (nargsCount && typeof nargsCount === 'number' && argsToSet.length >= nargsCount)) + break; + next = args[ii]; + if (/^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next)) + break; + i = ii; + argsToSet.push(processValue(key, next, inputIsString)); + } + } + // If both array and nargs are configured, create an error if less than + // nargs positionals were found. NaN has special meaning, indicating + // that at least one value is required (more are okay). + if (typeof nargsCount === 'number' && ((nargsCount && argsToSet.length < nargsCount) || + (isNaN(nargsCount) && argsToSet.length === 0))) { + error = Error(__('Not enough arguments following: %s', key)); + } + setArg(key, argsToSet); + return i; + } + function setArg(key, val, shouldStripQuotes = inputIsString) { + if (/-/.test(key) && configuration['camel-case-expansion']) { + const alias = key.split('.').map(function (prop) { + return camelCase(prop); + }).join('.'); + addNewAlias(key, alias); + } + const value = processValue(key, val, shouldStripQuotes); + const splitKey = key.split('.'); + setKey(argv, splitKey, value); + // handle populating aliases of the full key + if (flags.aliases[key]) { + flags.aliases[key].forEach(function (x) { + const keyProperties = x.split('.'); + setKey(argv, keyProperties, value); + }); + } + // handle populating aliases of the first element of the dot-notation key + if (splitKey.length > 1 && configuration['dot-notation']) { + ; + (flags.aliases[splitKey[0]] || []).forEach(function (x) { + let keyProperties = x.split('.'); + // expand alias with nested objects in key + const a = [].concat(splitKey); + a.shift(); // nuke the old key. + keyProperties = keyProperties.concat(a); + // populate alias only if is not already an alias of the full key + // (already populated above) + if (!(flags.aliases[key] || []).includes(keyProperties.join('.'))) { + setKey(argv, keyProperties, value); + } + }); + } + // Set normalize getter and setter when key is in 'normalize' but isn't an array + if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) { + const keys = [key].concat(flags.aliases[key] || []); + keys.forEach(function (key) { + Object.defineProperty(argvReturn, key, { + enumerable: true, + get() { + return val; + }, + set(value) { + val = typeof value === 'string' ? mixin.normalize(value) : value; + } + }); + }); + } + } + function addNewAlias(key, alias) { + if (!(flags.aliases[key] && flags.aliases[key].length)) { + flags.aliases[key] = [alias]; + newAliases[alias] = true; + } + if (!(flags.aliases[alias] && flags.aliases[alias].length)) { + addNewAlias(alias, key); + } + } + function processValue(key, val, shouldStripQuotes) { + // strings may be quoted, clean this up as we assign values. + if (shouldStripQuotes) { + val = stripQuotes(val); + } + // handle parsing boolean arguments --foo=true --bar false. + if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) { + if (typeof val === 'string') + val = val === 'true'; + } + let value = Array.isArray(val) + ? val.map(function (v) { return maybeCoerceNumber(key, v); }) + : maybeCoerceNumber(key, val); + // increment a count given as arg (either no value or value parsed as boolean) + if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === 'boolean')) { + value = increment(); + } + // Set normalized value when key is in 'normalize' and in 'arrays' + if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) { + if (Array.isArray(val)) + value = val.map((val) => { return mixin.normalize(val); }); + else + value = mixin.normalize(val); + } + return value; + } + function maybeCoerceNumber(key, value) { + if (!configuration['parse-positional-numbers'] && key === '_') + return value; + if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.bools) && !Array.isArray(value)) { + const shouldCoerceNumber = looksLikeNumber(value) && configuration['parse-numbers'] && (Number.isSafeInteger(Math.floor(parseFloat(`${value}`)))); + if (shouldCoerceNumber || (!isUndefined(value) && checkAllAliases(key, flags.numbers))) { + value = Number(value); + } + } + return value; + } + // set args from config.json file, this should be + // applied last so that defaults can be applied. + function setConfig(argv) { + const configLookup = Object.create(null); + // expand defaults/aliases, in-case any happen to reference + // the config.json file. + applyDefaultsAndAliases(configLookup, flags.aliases, defaults); + Object.keys(flags.configs).forEach(function (configKey) { + const configPath = argv[configKey] || configLookup[configKey]; + if (configPath) { + try { + let config = null; + const resolvedConfigPath = mixin.resolve(mixin.cwd(), configPath); + const resolveConfig = flags.configs[configKey]; + if (typeof resolveConfig === 'function') { + try { + config = resolveConfig(resolvedConfigPath); + } + catch (e) { + config = e; + } + if (config instanceof Error) { + error = config; + return; + } + } + else { + config = mixin.require(resolvedConfigPath); + } + setConfigObject(config); + } + catch (ex) { + // Deno will receive a PermissionDenied error if an attempt is + // made to load config without the --allow-read flag: + if (ex.name === 'PermissionDenied') + error = ex; + else if (argv[configKey]) + error = Error(__('Invalid JSON config file: %s', configPath)); + } + } + }); + } + // set args from config object. + // it recursively checks nested objects. + function setConfigObject(config, prev) { + Object.keys(config).forEach(function (key) { + const value = config[key]; + const fullKey = prev ? prev + '.' + key : key; + // if the value is an inner object and we have dot-notation + // enabled, treat inner objects in config the same as + // heavily nested dot notations (foo.bar.apple). + if (typeof value === 'object' && value !== null && !Array.isArray(value) && configuration['dot-notation']) { + // if the value is an object but not an array, check nested object + setConfigObject(value, fullKey); + } + else { + // setting arguments via CLI takes precedence over + // values within the config file. + if (!hasKey(argv, fullKey.split('.')) || (checkAllAliases(fullKey, flags.arrays) && configuration['combine-arrays'])) { + setArg(fullKey, value); + } + } + }); + } + // set all config objects passed in opts + function setConfigObjects() { + if (typeof configObjects !== 'undefined') { + configObjects.forEach(function (configObject) { + setConfigObject(configObject); + }); + } + } + function applyEnvVars(argv, configOnly) { + if (typeof envPrefix === 'undefined') + return; + const prefix = typeof envPrefix === 'string' ? envPrefix : ''; + const env = mixin.env(); + Object.keys(env).forEach(function (envVar) { + if (prefix === '' || envVar.lastIndexOf(prefix, 0) === 0) { + // get array of nested keys and convert them to camel case + const keys = envVar.split('__').map(function (key, i) { + if (i === 0) { + key = key.substring(prefix.length); + } + return camelCase(key); + }); + if (((configOnly && flags.configs[keys.join('.')]) || !configOnly) && !hasKey(argv, keys)) { + setArg(keys.join('.'), env[envVar]); + } + } + }); + } + function applyCoercions(argv) { + let coerce; + const applied = new Set(); + Object.keys(argv).forEach(function (key) { + if (!applied.has(key)) { // If we haven't already coerced this option via one of its aliases + coerce = checkAllAliases(key, flags.coercions); + if (typeof coerce === 'function') { + try { + const value = maybeCoerceNumber(key, coerce(argv[key])); + ([].concat(flags.aliases[key] || [], key)).forEach(ali => { + applied.add(ali); + argv[ali] = value; + }); + } + catch (err) { + error = err; + } + } + } + }); + } + function setPlaceholderKeys(argv) { + flags.keys.forEach((key) => { + // don't set placeholder keys for dot notation options 'foo.bar'. + if (~key.indexOf('.')) + return; + if (typeof argv[key] === 'undefined') + argv[key] = undefined; + }); + return argv; + } + function applyDefaultsAndAliases(obj, aliases, defaults, canLog = false) { + Object.keys(defaults).forEach(function (key) { + if (!hasKey(obj, key.split('.'))) { + setKey(obj, key.split('.'), defaults[key]); + if (canLog) + defaulted[key] = true; + (aliases[key] || []).forEach(function (x) { + if (hasKey(obj, x.split('.'))) + return; + setKey(obj, x.split('.'), defaults[key]); + }); + } + }); + } + function hasKey(obj, keys) { + let o = obj; + if (!configuration['dot-notation']) + keys = [keys.join('.')]; + keys.slice(0, -1).forEach(function (key) { + o = (o[key] || {}); + }); + const key = keys[keys.length - 1]; + if (typeof o !== 'object') + return false; + else + return key in o; + } + function setKey(obj, keys, value) { + let o = obj; + if (!configuration['dot-notation']) + keys = [keys.join('.')]; + keys.slice(0, -1).forEach(function (key) { + // TODO(bcoe): in the next major version of yargs, switch to + // Object.create(null) for dot notation: + key = sanitizeKey(key); + if (typeof o === 'object' && o[key] === undefined) { + o[key] = {}; + } + if (typeof o[key] !== 'object' || Array.isArray(o[key])) { + // ensure that o[key] is an array, and that the last item is an empty object. + if (Array.isArray(o[key])) { + o[key].push({}); + } + else { + o[key] = [o[key], {}]; + } + // we want to update the empty object at the end of the o[key] array, so set o to that object + o = o[key][o[key].length - 1]; + } + else { + o = o[key]; + } + }); + // TODO(bcoe): in the next major version of yargs, switch to + // Object.create(null) for dot notation: + const key = sanitizeKey(keys[keys.length - 1]); + const isTypeArray = checkAllAliases(keys.join('.'), flags.arrays); + const isValueArray = Array.isArray(value); + let duplicate = configuration['duplicate-arguments-array']; + // nargs has higher priority than duplicate + if (!duplicate && checkAllAliases(key, flags.nargs)) { + duplicate = true; + if ((!isUndefined(o[key]) && flags.nargs[key] === 1) || (Array.isArray(o[key]) && o[key].length === flags.nargs[key])) { + o[key] = undefined; + } + } + if (value === increment()) { + o[key] = increment(o[key]); + } + else if (Array.isArray(o[key])) { + if (duplicate && isTypeArray && isValueArray) { + o[key] = configuration['flatten-duplicate-arrays'] ? o[key].concat(value) : (Array.isArray(o[key][0]) ? o[key] : [o[key]]).concat([value]); + } + else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) { + o[key] = value; + } + else { + o[key] = o[key].concat([value]); + } + } + else if (o[key] === undefined && isTypeArray) { + o[key] = isValueArray ? value : [value]; + } + else if (duplicate && !(o[key] === undefined || + checkAllAliases(key, flags.counts) || + checkAllAliases(key, flags.bools))) { + o[key] = [o[key], value]; + } + else { + o[key] = value; + } + } + // extend the aliases list with inferred aliases. + function extendAliases(...args) { + args.forEach(function (obj) { + Object.keys(obj || {}).forEach(function (key) { + // short-circuit if we've already added a key + // to the aliases array, for example it might + // exist in both 'opts.default' and 'opts.key'. + if (flags.aliases[key]) + return; + flags.aliases[key] = [].concat(aliases[key] || []); + // For "--option-name", also set argv.optionName + flags.aliases[key].concat(key).forEach(function (x) { + if (/-/.test(x) && configuration['camel-case-expansion']) { + const c = camelCase(x); + if (c !== key && flags.aliases[key].indexOf(c) === -1) { + flags.aliases[key].push(c); + newAliases[c] = true; + } + } + }); + // For "--optionName", also set argv['option-name'] + flags.aliases[key].concat(key).forEach(function (x) { + if (x.length > 1 && /[A-Z]/.test(x) && configuration['camel-case-expansion']) { + const c = decamelize(x, '-'); + if (c !== key && flags.aliases[key].indexOf(c) === -1) { + flags.aliases[key].push(c); + newAliases[c] = true; + } + } + }); + flags.aliases[key].forEach(function (x) { + flags.aliases[x] = [key].concat(flags.aliases[key].filter(function (y) { + return x !== y; + })); + }); + }); + }); + } + function checkAllAliases(key, flag) { + const toCheck = [].concat(flags.aliases[key] || [], key); + const keys = Object.keys(flag); + const setAlias = toCheck.find(key => keys.includes(key)); + return setAlias ? flag[setAlias] : false; + } + function hasAnyFlag(key) { + const flagsKeys = Object.keys(flags); + const toCheck = [].concat(flagsKeys.map(k => flags[k])); + return toCheck.some(function (flag) { + return Array.isArray(flag) ? flag.includes(key) : flag[key]; + }); + } + function hasFlagsMatching(arg, ...patterns) { + const toCheck = [].concat(...patterns); + return toCheck.some(function (pattern) { + const match = arg.match(pattern); + return match && hasAnyFlag(match[1]); + }); + } + // based on a simplified version of the short flag group parsing logic + function hasAllShortFlags(arg) { + // if this is a negative number, or doesn't start with a single hyphen, it's not a short flag group + if (arg.match(negative) || !arg.match(/^-[^-]+/)) { + return false; + } + let hasAllFlags = true; + let next; + const letters = arg.slice(1).split(''); + for (let j = 0; j < letters.length; j++) { + next = arg.slice(j + 2); + if (!hasAnyFlag(letters[j])) { + hasAllFlags = false; + break; + } + if ((letters[j + 1] && letters[j + 1] === '=') || + next === '-' || + (/[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) || + (letters[j + 1] && letters[j + 1].match(/\W/))) { + break; + } + } + return hasAllFlags; + } + function isUnknownOptionAsArg(arg) { + return configuration['unknown-options-as-args'] && isUnknownOption(arg); + } + function isUnknownOption(arg) { + arg = arg.replace(/^-{3,}/, '--'); + // ignore negative numbers + if (arg.match(negative)) { + return false; + } + // if this is a short option group and all of them are configured, it isn't unknown + if (hasAllShortFlags(arg)) { + return false; + } + // e.g. '--count=2' + const flagWithEquals = /^-+([^=]+?)=[\s\S]*$/; + // e.g. '-a' or '--arg' + const normalFlag = /^-+([^=]+?)$/; + // e.g. '-a-' + const flagEndingInHyphen = /^-+([^=]+?)-$/; + // e.g. '-abc123' + const flagEndingInDigits = /^-+([^=]+?\d+)$/; + // e.g. '-a/usr/local' + const flagEndingInNonWordCharacters = /^-+([^=]+?)\W+.*$/; + // check the different types of flag styles, including negatedBoolean, a pattern defined near the start of the parse method + return !hasFlagsMatching(arg, flagWithEquals, negatedBoolean, normalFlag, flagEndingInHyphen, flagEndingInDigits, flagEndingInNonWordCharacters); + } + // make a best effort to pick a default value + // for an option based on name and type. + function defaultValue(key) { + if (!checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts) && + `${key}` in defaults) { + return defaults[key]; + } + else { + return defaultForType(guessType(key)); + } + } + // return a default value, given the type of a flag., + function defaultForType(type) { + const def = { + [DefaultValuesForTypeKey.BOOLEAN]: true, + [DefaultValuesForTypeKey.STRING]: '', + [DefaultValuesForTypeKey.NUMBER]: undefined, + [DefaultValuesForTypeKey.ARRAY]: [] + }; + return def[type]; + } + // given a flag, enforce a default type. + function guessType(key) { + let type = DefaultValuesForTypeKey.BOOLEAN; + if (checkAllAliases(key, flags.strings)) + type = DefaultValuesForTypeKey.STRING; + else if (checkAllAliases(key, flags.numbers)) + type = DefaultValuesForTypeKey.NUMBER; + else if (checkAllAliases(key, flags.bools)) + type = DefaultValuesForTypeKey.BOOLEAN; + else if (checkAllAliases(key, flags.arrays)) + type = DefaultValuesForTypeKey.ARRAY; + return type; + } + function isUndefined(num) { + return num === undefined; + } + // check user configuration settings for inconsistencies + function checkConfiguration() { + // count keys should not be set as array/narg + Object.keys(flags.counts).find(key => { + if (checkAllAliases(key, flags.arrays)) { + error = Error(__('Invalid configuration: %s, opts.count excludes opts.array.', key)); + return true; + } + else if (checkAllAliases(key, flags.nargs)) { + error = Error(__('Invalid configuration: %s, opts.count excludes opts.narg.', key)); + return true; + } + return false; + }); + } + return { + aliases: Object.assign({}, flags.aliases), + argv: Object.assign(argvReturn, argv), + configuration: configuration, + defaulted: Object.assign({}, defaulted), + error: error, + newAliases: Object.assign({}, newAliases) + }; + } +} +// if any aliases reference each other, we should +// merge them together. +function combineAliases(aliases) { + const aliasArrays = []; + const combined = Object.create(null); + let change = true; + // turn alias lookup hash {key: ['alias1', 'alias2']} into + // a simple array ['key', 'alias1', 'alias2'] + Object.keys(aliases).forEach(function (key) { + aliasArrays.push([].concat(aliases[key], key)); + }); + // combine arrays until zero changes are + // made in an iteration. + while (change) { + change = false; + for (let i = 0; i < aliasArrays.length; i++) { + for (let ii = i + 1; ii < aliasArrays.length; ii++) { + const intersect = aliasArrays[i].filter(function (v) { + return aliasArrays[ii].indexOf(v) !== -1; + }); + if (intersect.length) { + aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii]); + aliasArrays.splice(ii, 1); + change = true; + break; + } + } + } + } + // map arrays back to the hash-lookup (de-dupe while + // we're at it). + aliasArrays.forEach(function (aliasArray) { + aliasArray = aliasArray.filter(function (v, i, self) { + return self.indexOf(v) === i; + }); + const lastAlias = aliasArray.pop(); + if (lastAlias !== undefined && typeof lastAlias === 'string') { + combined[lastAlias] = aliasArray; + } + }); + return combined; +} +// this function should only be called when a count is given as an arg +// it is NOT called to set a default value +// thus we can start the count at 1 instead of 0 +function increment(orig) { + return orig !== undefined ? orig + 1 : 1; +} +// TODO(bcoe): in the next major version of yargs, switch to +// Object.create(null) for dot notation: +function sanitizeKey(key) { + if (key === '__proto__') + return '___proto___'; + return key; +} +function stripQuotes(val) { + return (typeof val === 'string' && + (val[0] === "'" || val[0] === '"') && + val[val.length - 1] === val[0]) + ? val.substring(1, val.length - 1) + : val; +} diff --git a/node_modules/yargs-parser/package.json b/node_modules/yargs-parser/package.json new file mode 100644 index 0000000000000000000000000000000000000000..b72170d3324a901c9635d0741bd7bb0395c78762 --- /dev/null +++ b/node_modules/yargs-parser/package.json @@ -0,0 +1,133 @@ +{ + "_from": "yargs-parser@^21.1.1", + "_id": "yargs-parser@21.1.1", + "_inBundle": false, + "_integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "_location": "/yargs-parser", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "yargs-parser@^21.1.1", + "name": "yargs-parser", + "escapedName": "yargs-parser", + "rawSpec": "^21.1.1", + "saveSpec": null, + "fetchSpec": "^21.1.1" + }, + "_requiredBy": [ + "/yargs" + ], + "_resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "_shasum": "9096bceebf990d21bb31fa9516e0ede294a77d35", + "_spec": "yargs-parser@^21.1.1", + "_where": "/Users/sylvainfiloni/Documents/HuggingFace_Projects/live-vision/node_modules/yargs", + "author": { + "name": "Ben Coe", + "email": "ben@npmjs.com" + }, + "bugs": { + "url": "https://github.com/yargs/yargs-parser/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "the mighty option parser used by yargs", + "devDependencies": { + "@types/chai": "^4.2.11", + "@types/mocha": "^9.0.0", + "@types/node": "^16.11.4", + "@typescript-eslint/eslint-plugin": "^3.10.1", + "@typescript-eslint/parser": "^3.10.1", + "c8": "^7.3.0", + "chai": "^4.2.0", + "cross-env": "^7.0.2", + "eslint": "^7.0.0", + "eslint-plugin-import": "^2.20.1", + "eslint-plugin-node": "^11.0.0", + "gts": "^3.0.0", + "mocha": "^10.0.0", + "puppeteer": "^16.0.0", + "rimraf": "^3.0.2", + "rollup": "^2.22.1", + "rollup-plugin-cleanup": "^3.1.1", + "rollup-plugin-ts": "^3.0.2", + "serve": "^14.0.0", + "standardx": "^7.0.0", + "start-server-and-test": "^1.11.2", + "ts-transform-default-export": "^1.0.2", + "typescript": "^4.0.0" + }, + "engines": { + "node": ">=12" + }, + "exports": { + ".": [ + { + "import": "./build/lib/index.js", + "require": "./build/index.cjs" + }, + "./build/index.cjs" + ], + "./browser": [ + "./browser.js" + ] + }, + "files": [ + "browser.js", + "build", + "!*.d.ts", + "!*.d.cts" + ], + "homepage": "https://github.com/yargs/yargs-parser#readme", + "keywords": [ + "argument", + "parser", + "yargs", + "command", + "cli", + "parsing", + "option", + "args", + "argument" + ], + "license": "ISC", + "main": "build/index.cjs", + "module": "./build/lib/index.js", + "name": "yargs-parser", + "repository": { + "type": "git", + "url": "git+https://github.com/yargs/yargs-parser.git" + }, + "scripts": { + "build:cjs": "rollup -c", + "check": "standardx '**/*.ts' && standardx '**/*.js' && standardx '**/*.cjs'", + "compile": "tsc", + "coverage": "c8 report --check-coverage", + "fix": "standardx --fix '**/*.ts' && standardx --fix '**/*.js' && standardx --fix '**/*.cjs'", + "postcompile": "npm run build:cjs", + "precompile": "rimraf build", + "prepare": "npm run compile", + "pretest": "rimraf build && tsc -p tsconfig.test.json && cross-env NODE_ENV=test npm run build:cjs", + "pretest:typescript": "npm run pretest", + "test": "c8 --reporter=text --reporter=html mocha test/*.cjs", + "test:browser": "start-server-and-test 'serve ./ -p 8080' http://127.0.0.1:8080/package.json 'node ./test/browser/yargs-test.cjs'", + "test:esm": "c8 --reporter=text --reporter=html mocha test/*.mjs", + "test:typescript": "c8 mocha ./build/test/typescript/*.js" + }, + "standardx": { + "ignore": [ + "build" + ] + }, + "type": "module", + "version": "21.1.1", + "warnings": [ + { + "code": "ENOTSUP", + "required": { + "node": ">=12" + }, + "pkgid": "yargs-parser@21.1.1" + } + ] +} diff --git a/node_modules/yargs/LICENSE b/node_modules/yargs/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b0145ca0b03bdc922de70dbaf5ae87c3a244c413 --- /dev/null +++ b/node_modules/yargs/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright 2010 James Halliday (mail@substack.net); Modified work Copyright 2014 Contributors (ben@npmjs.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/node_modules/yargs/README.md b/node_modules/yargs/README.md new file mode 100644 index 0000000000000000000000000000000000000000..51f5b225d72cb15edc0a5854ff3e5bec725e7777 --- /dev/null +++ b/node_modules/yargs/README.md @@ -0,0 +1,204 @@ +

+ +

+

Yargs

+

+ Yargs be a node.js library fer hearties tryin' ter parse optstrings +

+ +
+ +![ci](https://github.com/yargs/yargs/workflows/ci/badge.svg) +[![NPM version][npm-image]][npm-url] +[![js-standard-style][standard-image]][standard-url] +[![Coverage][coverage-image]][coverage-url] +[![Conventional Commits][conventional-commits-image]][conventional-commits-url] +[![Slack][slack-image]][slack-url] + +## Description +Yargs helps you build interactive command line tools, by parsing arguments and generating an elegant user interface. + +It gives you: + +* commands and (grouped) options (`my-program.js serve --port=5000`). +* a dynamically generated help menu based on your arguments: + +``` +mocha [spec..] + +Run tests with Mocha + +Commands + mocha inspect [spec..] Run tests with Mocha [default] + mocha init create a client-side Mocha setup at + +Rules & Behavior + --allow-uncaught Allow uncaught errors to propagate [boolean] + --async-only, -A Require all tests to use a callback (async) or + return a Promise [boolean] +``` + +* bash-completion shortcuts for commands and options. +* and [tons more](/docs/api.md). + +## Installation + +Stable version: +```bash +npm i yargs +``` + +Bleeding edge version with the most recent features: +```bash +npm i yargs@next +``` + +## Usage + +### Simple Example + +```javascript +#!/usr/bin/env node +const yargs = require('yargs/yargs') +const { hideBin } = require('yargs/helpers') +const argv = yargs(hideBin(process.argv)).argv + +if (argv.ships > 3 && argv.distance < 53.5) { + console.log('Plunder more riffiwobbles!') +} else { + console.log('Retreat from the xupptumblers!') +} +``` + +```bash +$ ./plunder.js --ships=4 --distance=22 +Plunder more riffiwobbles! + +$ ./plunder.js --ships 12 --distance 98.7 +Retreat from the xupptumblers! +``` + +> Note: `hideBin` is a shorthand for [`process.argv.slice(2)`](https://nodejs.org/en/knowledge/command-line/how-to-parse-command-line-arguments/). It has the benefit that it takes into account variations in some environments, e.g., [Electron](https://github.com/electron/electron/issues/4690). + +### Complex Example + +```javascript +#!/usr/bin/env node +const yargs = require('yargs/yargs') +const { hideBin } = require('yargs/helpers') + +yargs(hideBin(process.argv)) + .command('serve [port]', 'start the server', (yargs) => { + return yargs + .positional('port', { + describe: 'port to bind on', + default: 5000 + }) + }, (argv) => { + if (argv.verbose) console.info(`start server on :${argv.port}`) + serve(argv.port) + }) + .option('verbose', { + alias: 'v', + type: 'boolean', + description: 'Run with verbose logging' + }) + .parse() +``` + +Run the example above with `--help` to see the help for the application. + +## Supported Platforms + +### TypeScript + +yargs has type definitions at [@types/yargs][type-definitions]. + +``` +npm i @types/yargs --save-dev +``` + +See usage examples in [docs](/docs/typescript.md). + +### Deno + +As of `v16`, `yargs` supports [Deno](https://github.com/denoland/deno): + +```typescript +import yargs from 'https://deno.land/x/yargs/deno.ts' +import { Arguments } from 'https://deno.land/x/yargs/deno-types.ts' + +yargs(Deno.args) + .command('download ', 'download a list of files', (yargs: any) => { + return yargs.positional('files', { + describe: 'a list of files to do something with' + }) + }, (argv: Arguments) => { + console.info(argv) + }) + .strictCommands() + .demandCommand(1) + .parse() +``` + +### ESM + +As of `v16`,`yargs` supports ESM imports: + +```js +import yargs from 'yargs' +import { hideBin } from 'yargs/helpers' + +yargs(hideBin(process.argv)) + .command('curl ', 'fetch the contents of the URL', () => {}, (argv) => { + console.info(argv) + }) + .demandCommand(1) + .parse() +``` + +### Usage in Browser + +See examples of using yargs in the browser in [docs](/docs/browser.md). + +## Community + +Having problems? want to contribute? join our [community slack](http://devtoolscommunity.herokuapp.com). + +## Documentation + +### Table of Contents + +* [Yargs' API](/docs/api.md) +* [Examples](/docs/examples.md) +* [Parsing Tricks](/docs/tricks.md) + * [Stop the Parser](/docs/tricks.md#stop) + * [Negating Boolean Arguments](/docs/tricks.md#negate) + * [Numbers](/docs/tricks.md#numbers) + * [Arrays](/docs/tricks.md#arrays) + * [Objects](/docs/tricks.md#objects) + * [Quotes](/docs/tricks.md#quotes) +* [Advanced Topics](/docs/advanced.md) + * [Composing Your App Using Commands](/docs/advanced.md#commands) + * [Building Configurable CLI Apps](/docs/advanced.md#configuration) + * [Customizing Yargs' Parser](/docs/advanced.md#customizing) + * [Bundling yargs](/docs/bundling.md) +* [Contributing](/contributing.md) + +## Supported Node.js Versions + +Libraries in this ecosystem make a best effort to track +[Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a +post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). + +[npm-url]: https://www.npmjs.com/package/yargs +[npm-image]: https://img.shields.io/npm/v/yargs.svg +[standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg +[standard-url]: http://standardjs.com/ +[conventional-commits-image]: https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg +[conventional-commits-url]: https://conventionalcommits.org/ +[slack-image]: http://devtoolscommunity.herokuapp.com/badge.svg +[slack-url]: http://devtoolscommunity.herokuapp.com +[type-definitions]: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/yargs +[coverage-image]: https://img.shields.io/nycrc/yargs/yargs +[coverage-url]: https://github.com/yargs/yargs/blob/main/.nycrc diff --git a/node_modules/yargs/browser.d.ts b/node_modules/yargs/browser.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..21f3fc69190b574ab8456514d3da1972afa53973 --- /dev/null +++ b/node_modules/yargs/browser.d.ts @@ -0,0 +1,5 @@ +import {YargsFactory} from './build/lib/yargs-factory'; + +declare const Yargs: ReturnType; + +export default Yargs; diff --git a/node_modules/yargs/browser.mjs b/node_modules/yargs/browser.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2d0d6e9e5b7c3e264462f10f0152efafae75005c --- /dev/null +++ b/node_modules/yargs/browser.mjs @@ -0,0 +1,7 @@ +// Bootstrap yargs for browser: +import browserPlatformShim from './lib/platform-shims/browser.mjs'; +import {YargsFactory} from './build/lib/yargs-factory.js'; + +const Yargs = YargsFactory(browserPlatformShim); + +export default Yargs; diff --git a/node_modules/yargs/build/index.cjs b/node_modules/yargs/build/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..e9cf0137e1fa05bd504e475f80451e4a179b8e44 --- /dev/null +++ b/node_modules/yargs/build/index.cjs @@ -0,0 +1 @@ +"use strict";var t=require("assert");class e extends Error{constructor(t){super(t||"yargs error"),this.name="YError",Error.captureStackTrace&&Error.captureStackTrace(this,e)}}let s,i=[];function n(t,o,a,h){s=h;let l={};if(Object.prototype.hasOwnProperty.call(t,"extends")){if("string"!=typeof t.extends)return l;const r=/\.json|\..*rc$/.test(t.extends);let h=null;if(r)h=function(t,e){return s.path.resolve(t,e)}(o,t.extends);else try{h=require.resolve(t.extends)}catch(e){return t}!function(t){if(i.indexOf(t)>-1)throw new e(`Circular extended configurations: '${t}'.`)}(h),i.push(h),l=r?JSON.parse(s.readFileSync(h,"utf8")):require(t.extends),delete t.extends,l=n(l,s.path.dirname(h),a,s)}return i=[],a?r(l,t):Object.assign({},l,t)}function r(t,e){const s={};function i(t){return t&&"object"==typeof t&&!Array.isArray(t)}Object.assign(s,t);for(const n of Object.keys(e))i(e[n])&&i(s[n])?s[n]=r(t[n],e[n]):s[n]=e[n];return s}function o(t){const e=t.replace(/\s{2,}/g," ").split(/\s+(?![^[]*]|[^<]*>)/),s=/\.*[\][<>]/g,i=e.shift();if(!i)throw new Error(`No command found in: ${t}`);const n={cmd:i.replace(s,""),demanded:[],optional:[]};return e.forEach(((t,i)=>{let r=!1;t=t.replace(/\s/g,""),/\.+[\]>]/.test(t)&&i===e.length-1&&(r=!0),/^\[/.test(t)?n.optional.push({cmd:t.replace(s,"").split("|"),variadic:r}):n.demanded.push({cmd:t.replace(s,"").split("|"),variadic:r})})),n}const a=["first","second","third","fourth","fifth","sixth"];function h(t,s,i){try{let n=0;const[r,a,h]="object"==typeof t?[{demanded:[],optional:[]},t,s]:[o(`cmd ${t}`),s,i],f=[].slice.call(a);for(;f.length&&void 0===f[f.length-1];)f.pop();const d=h||f.length;if(du)throw new e(`Too many arguments provided. Expected max ${u} but received ${d}.`);r.demanded.forEach((t=>{const e=l(f.shift());0===t.cmd.filter((t=>t===e||"*"===t)).length&&c(e,t.cmd,n),n+=1})),r.optional.forEach((t=>{if(0===f.length)return;const e=l(f.shift());0===t.cmd.filter((t=>t===e||"*"===t)).length&&c(e,t.cmd,n),n+=1}))}catch(t){console.warn(t.stack)}}function l(t){return Array.isArray(t)?"array":null===t?"null":typeof t}function c(t,s,i){throw new e(`Invalid ${a[i]||"manyith"} argument. Expected ${s.join(" or ")} but received ${t}.`)}function f(t){return!!t&&!!t.then&&"function"==typeof t.then}function d(t,e,s,i){s.assert.notStrictEqual(t,e,i)}function u(t,e){e.assert.strictEqual(typeof t,"string")}function p(t){return Object.keys(t)}function g(t={},e=(()=>!0)){const s={};return p(t).forEach((i=>{e(i,t[i])&&(s[i]=t[i])})),s}function m(){return process.versions.electron&&!process.defaultApp?0:1}function y(){return process.argv[m()]}var b=Object.freeze({__proto__:null,hideBin:function(t){return t.slice(m()+1)},getProcessArgvBin:y});function v(t,e,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(t):i?i.value:e.get(t)}function O(t,e,s,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(t,s):n?n.value=s:e.set(t,s),s}class w{constructor(t){this.globalMiddleware=[],this.frozens=[],this.yargs=t}addMiddleware(t,e,s=!0,i=!1){if(h(" [boolean] [boolean] [boolean]",[t,e,s],arguments.length),Array.isArray(t)){for(let i=0;i{const i=[...s[e]||[],e];return!t.option||!i.includes(t.option)})),t.option=e,this.addMiddleware(t,!0,!0,!0)}getMiddleware(){return this.globalMiddleware}freeze(){this.frozens.push([...this.globalMiddleware])}unfreeze(){const t=this.frozens.pop();void 0!==t&&(this.globalMiddleware=t)}reset(){this.globalMiddleware=this.globalMiddleware.filter((t=>t.global))}}function C(t,e,s,i){return s.reduce(((t,s)=>{if(s.applyBeforeValidation!==i)return t;if(s.mutates){if(s.applied)return t;s.applied=!0}if(f(t))return t.then((t=>Promise.all([t,s(t,e)]))).then((([t,e])=>Object.assign(t,e)));{const i=s(t,e);return f(i)?i.then((e=>Object.assign(t,e))):Object.assign(t,i)}}),t)}function j(t,e,s=(t=>{throw t})){try{const s="function"==typeof t?t():t;return f(s)?s.then((t=>e(t))):e(s)}catch(t){return s(t)}}const M=/(^\*)|(^\$0)/;class _{constructor(t,e,s,i){this.requireCache=new Set,this.handlers={},this.aliasMap={},this.frozens=[],this.shim=i,this.usage=t,this.globalMiddleware=s,this.validation=e}addDirectory(t,e,s,i){"boolean"!=typeof(i=i||{}).recurse&&(i.recurse=!1),Array.isArray(i.extensions)||(i.extensions=["js"]);const n="function"==typeof i.visit?i.visit:t=>t;i.visit=(t,e,s)=>{const i=n(t,e,s);if(i){if(this.requireCache.has(e))return i;this.requireCache.add(e),this.addHandler(i)}return i},this.shim.requireDirectory({require:e,filename:s},t,i)}addHandler(t,e,s,i,n,r){let a=[];const h=function(t){return t?t.map((t=>(t.applyBeforeValidation=!1,t))):[]}(n);if(i=i||(()=>{}),Array.isArray(t))if(function(t){return t.every((t=>"string"==typeof t))}(t))[t,...a]=t;else for(const e of t)this.addHandler(e);else{if(function(t){return"object"==typeof t&&!Array.isArray(t)}(t)){let e=Array.isArray(t.command)||"string"==typeof t.command?t.command:this.moduleName(t);return t.aliases&&(e=[].concat(e).concat(t.aliases)),void this.addHandler(e,this.extractDesc(t),t.builder,t.handler,t.middlewares,t.deprecated)}if(k(s))return void this.addHandler([t].concat(a),e,s.builder,s.handler,s.middlewares,s.deprecated)}if("string"==typeof t){const n=o(t);a=a.map((t=>o(t).cmd));let l=!1;const c=[n.cmd].concat(a).filter((t=>!M.test(t)||(l=!0,!1)));0===c.length&&l&&c.push("$0"),l&&(n.cmd=c[0],a=c.slice(1),t=t.replace(M,n.cmd)),a.forEach((t=>{this.aliasMap[t]=n.cmd})),!1!==e&&this.usage.command(t,e,l,a,r),this.handlers[n.cmd]={original:t,description:e,handler:i,builder:s||{},middlewares:h,deprecated:r,demanded:n.demanded,optional:n.optional},l&&(this.defaultCommand=this.handlers[n.cmd])}}getCommandHandlers(){return this.handlers}getCommands(){return Object.keys(this.handlers).concat(Object.keys(this.aliasMap))}hasDefaultCommand(){return!!this.defaultCommand}runCommand(t,e,s,i,n,r){const o=this.handlers[t]||this.handlers[this.aliasMap[t]]||this.defaultCommand,a=e.getInternalMethods().getContext(),h=a.commands.slice(),l=!t;t&&(a.commands.push(t),a.fullCommands.push(o.original));const c=this.applyBuilderUpdateUsageAndParse(l,o,e,s.aliases,h,i,n,r);return f(c)?c.then((t=>this.applyMiddlewareAndGetResult(l,o,t.innerArgv,a,n,t.aliases,e))):this.applyMiddlewareAndGetResult(l,o,c.innerArgv,a,n,c.aliases,e)}applyBuilderUpdateUsageAndParse(t,e,s,i,n,r,o,a){const h=e.builder;let l=s;if(x(h)){s.getInternalMethods().getUsageInstance().freeze();const c=h(s.getInternalMethods().reset(i),a);if(f(c))return c.then((i=>{var a;return l=(a=i)&&"function"==typeof a.getInternalMethods?i:s,this.parseAndUpdateUsage(t,e,l,n,r,o)}))}else(function(t){return"object"==typeof t})(h)&&(s.getInternalMethods().getUsageInstance().freeze(),l=s.getInternalMethods().reset(i),Object.keys(e.builder).forEach((t=>{l.option(t,h[t])})));return this.parseAndUpdateUsage(t,e,l,n,r,o)}parseAndUpdateUsage(t,e,s,i,n,r){t&&s.getInternalMethods().getUsageInstance().unfreeze(!0),this.shouldUpdateUsage(s)&&s.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(i,e),e.description);const o=s.getInternalMethods().runYargsParserAndExecuteCommands(null,void 0,!0,n,r);return f(o)?o.then((t=>({aliases:s.parsed.aliases,innerArgv:t}))):{aliases:s.parsed.aliases,innerArgv:o}}shouldUpdateUsage(t){return!t.getInternalMethods().getUsageInstance().getUsageDisabled()&&0===t.getInternalMethods().getUsageInstance().getUsage().length}usageFromParentCommandsCommandHandler(t,e){const s=M.test(e.original)?e.original.replace(M,"").trim():e.original,i=t.filter((t=>!M.test(t)));return i.push(s),`$0 ${i.join(" ")}`}handleValidationAndGetResult(t,e,s,i,n,r,o,a){if(!r.getInternalMethods().getHasOutput()){const e=r.getInternalMethods().runValidation(n,a,r.parsed.error,t);s=j(s,(t=>(e(t),t)))}if(e.handler&&!r.getInternalMethods().getHasOutput()){r.getInternalMethods().setHasOutput();const i=!!r.getOptions().configuration["populate--"];r.getInternalMethods().postProcess(s,i,!1,!1),s=j(s=C(s,r,o,!1),(t=>{const s=e.handler(t);return f(s)?s.then((()=>t)):t})),t||r.getInternalMethods().getUsageInstance().cacheHelpMessage(),f(s)&&!r.getInternalMethods().hasParseCallback()&&s.catch((t=>{try{r.getInternalMethods().getUsageInstance().fail(null,t)}catch(t){}}))}return t||(i.commands.pop(),i.fullCommands.pop()),s}applyMiddlewareAndGetResult(t,e,s,i,n,r,o){let a={};if(n)return s;o.getInternalMethods().getHasOutput()||(a=this.populatePositionals(e,s,i,o));const h=this.globalMiddleware.getMiddleware().slice(0).concat(e.middlewares),l=C(s,o,h,!0);return f(l)?l.then((s=>this.handleValidationAndGetResult(t,e,s,i,r,o,h,a))):this.handleValidationAndGetResult(t,e,l,i,r,o,h,a)}populatePositionals(t,e,s,i){e._=e._.slice(s.commands.length);const n=t.demanded.slice(0),r=t.optional.slice(0),o={};for(this.validation.positionalCount(n.length,e._.length);n.length;){const t=n.shift();this.populatePositional(t,e,o)}for(;r.length;){const t=r.shift();this.populatePositional(t,e,o)}return e._=s.commands.concat(e._.map((t=>""+t))),this.postProcessPositionals(e,o,this.cmdToParseOptions(t.original),i),o}populatePositional(t,e,s){const i=t.cmd[0];t.variadic?s[i]=e._.splice(0).map(String):e._.length&&(s[i]=[String(e._.shift())])}cmdToParseOptions(t){const e={array:[],default:{},alias:{},demand:{}},s=o(t);return s.demanded.forEach((t=>{const[s,...i]=t.cmd;t.variadic&&(e.array.push(s),e.default[s]=[]),e.alias[s]=i,e.demand[s]=!0})),s.optional.forEach((t=>{const[s,...i]=t.cmd;t.variadic&&(e.array.push(s),e.default[s]=[]),e.alias[s]=i})),e}postProcessPositionals(t,e,s,i){const n=Object.assign({},i.getOptions());n.default=Object.assign(s.default,n.default);for(const t of Object.keys(s.alias))n.alias[t]=(n.alias[t]||[]).concat(s.alias[t]);n.array=n.array.concat(s.array),n.config={};const r=[];if(Object.keys(e).forEach((t=>{e[t].map((e=>{n.configuration["unknown-options-as-args"]&&(n.key[t]=!0),r.push(`--${t}`),r.push(e)}))})),!r.length)return;const o=Object.assign({},n.configuration,{"populate--":!1}),a=this.shim.Parser.detailed(r,Object.assign({},n,{configuration:o}));if(a.error)i.getInternalMethods().getUsageInstance().fail(a.error.message,a.error);else{const s=Object.keys(e);Object.keys(e).forEach((t=>{s.push(...a.aliases[t])})),Object.keys(a.argv).forEach((n=>{s.includes(n)&&(e[n]||(e[n]=a.argv[n]),!this.isInConfigs(i,n)&&!this.isDefaulted(i,n)&&Object.prototype.hasOwnProperty.call(t,n)&&Object.prototype.hasOwnProperty.call(a.argv,n)&&(Array.isArray(t[n])||Array.isArray(a.argv[n]))?t[n]=[].concat(t[n],a.argv[n]):t[n]=a.argv[n])}))}}isDefaulted(t,e){const{default:s}=t.getOptions();return Object.prototype.hasOwnProperty.call(s,e)||Object.prototype.hasOwnProperty.call(s,this.shim.Parser.camelCase(e))}isInConfigs(t,e){const{configObjects:s}=t.getOptions();return s.some((t=>Object.prototype.hasOwnProperty.call(t,e)))||s.some((t=>Object.prototype.hasOwnProperty.call(t,this.shim.Parser.camelCase(e))))}runDefaultBuilderOn(t){if(!this.defaultCommand)return;if(this.shouldUpdateUsage(t)){const e=M.test(this.defaultCommand.original)?this.defaultCommand.original:this.defaultCommand.original.replace(/^[^[\]<>]*/,"$0 ");t.getInternalMethods().getUsageInstance().usage(e,this.defaultCommand.description)}const e=this.defaultCommand.builder;if(x(e))return e(t,!0);k(e)||Object.keys(e).forEach((s=>{t.option(s,e[s])}))}moduleName(t){const e=function(t){if("undefined"==typeof require)return null;for(let e,s=0,i=Object.keys(require.cache);s{const s=e;s._handle&&s.isTTY&&"function"==typeof s._handle.setBlocking&&s._handle.setBlocking(t)}))}function A(t){return"boolean"==typeof t}function P(t,s){const i=s.y18n.__,n={},r=[];n.failFn=function(t){r.push(t)};let o=null,a=null,h=!0;n.showHelpOnFail=function(e=!0,s){const[i,r]="string"==typeof e?[!0,e]:[e,s];return t.getInternalMethods().isGlobalContext()&&(a=r),o=r,h=i,n};let l=!1;n.fail=function(s,i){const c=t.getInternalMethods().getLoggerInstance();if(!r.length){if(t.getExitProcess()&&E(!0),!l){l=!0,h&&(t.showHelp("error"),c.error()),(s||i)&&c.error(s||i);const e=o||a;e&&((s||i)&&c.error(""),c.error(e))}if(i=i||new e(s),t.getExitProcess())return t.exit(1);if(t.getInternalMethods().hasParseCallback())return t.exit(1,i);throw i}for(let t=r.length-1;t>=0;--t){const e=r[t];if(A(e)){if(i)throw i;if(s)throw Error(s)}else e(s,i,n)}};let c=[],f=!1;n.usage=(t,e)=>null===t?(f=!0,c=[],n):(f=!1,c.push([t,e||""]),n),n.getUsage=()=>c,n.getUsageDisabled=()=>f,n.getPositionalGroupName=()=>i("Positionals:");let d=[];n.example=(t,e)=>{d.push([t,e||""])};let u=[];n.command=function(t,e,s,i,n=!1){s&&(u=u.map((t=>(t[2]=!1,t)))),u.push([t,e||"",s,i,n])},n.getCommands=()=>u;let p={};n.describe=function(t,e){Array.isArray(t)?t.forEach((t=>{n.describe(t,e)})):"object"==typeof t?Object.keys(t).forEach((e=>{n.describe(e,t[e])})):p[t]=e},n.getDescriptions=()=>p;let m=[];n.epilog=t=>{m.push(t)};let y,b=!1;n.wrap=t=>{b=!0,y=t},n.getWrap=()=>s.getEnv("YARGS_DISABLE_WRAP")?null:(b||(y=function(){const t=80;return s.process.stdColumns?Math.min(t,s.process.stdColumns):t}(),b=!0),y);const v="__yargsString__:";function O(t,e,i){let n=0;return Array.isArray(t)||(t=Object.values(t).map((t=>[t]))),t.forEach((t=>{n=Math.max(s.stringWidth(i?`${i} ${I(t[0])}`:I(t[0]))+$(t[0]),n)})),e&&(n=Math.min(n,parseInt((.5*e).toString(),10))),n}let w;function C(e){return t.getOptions().hiddenOptions.indexOf(e)<0||t.parsed.argv[t.getOptions().showHiddenOpt]}function j(t,e){let s=`[${i("default:")} `;if(void 0===t&&!e)return null;if(e)s+=e;else switch(typeof t){case"string":s+=`"${t}"`;break;case"object":s+=JSON.stringify(t);break;default:s+=t}return`${s}]`}n.deferY18nLookup=t=>v+t,n.help=function(){if(w)return w;!function(){const e=t.getDemandedOptions(),s=t.getOptions();(Object.keys(s.alias)||[]).forEach((i=>{s.alias[i].forEach((r=>{p[r]&&n.describe(i,p[r]),r in e&&t.demandOption(i,e[r]),s.boolean.includes(r)&&t.boolean(i),s.count.includes(r)&&t.count(i),s.string.includes(r)&&t.string(i),s.normalize.includes(r)&&t.normalize(i),s.array.includes(r)&&t.array(i),s.number.includes(r)&&t.number(i)}))}))}();const e=t.customScriptName?t.$0:s.path.basename(t.$0),r=t.getDemandedOptions(),o=t.getDemandedCommands(),a=t.getDeprecatedOptions(),h=t.getGroups(),l=t.getOptions();let g=[];g=g.concat(Object.keys(p)),g=g.concat(Object.keys(r)),g=g.concat(Object.keys(o)),g=g.concat(Object.keys(l.default)),g=g.filter(C),g=Object.keys(g.reduce(((t,e)=>("_"!==e&&(t[e]=!0),t)),{}));const y=n.getWrap(),b=s.cliui({width:y,wrap:!!y});if(!f)if(c.length)c.forEach((t=>{b.div({text:`${t[0].replace(/\$0/g,e)}`}),t[1]&&b.div({text:`${t[1]}`,padding:[1,0,0,0]})})),b.div();else if(u.length){let t=null;t=o._?`${e} <${i("command")}>\n`:`${e} [${i("command")}]\n`,b.div(`${t}`)}if(u.length>1||1===u.length&&!u[0][2]){b.div(i("Commands:"));const s=t.getInternalMethods().getContext(),n=s.commands.length?`${s.commands.join(" ")} `:"";!0===t.getInternalMethods().getParserConfiguration()["sort-commands"]&&(u=u.sort(((t,e)=>t[0].localeCompare(e[0]))));const r=e?`${e} `:"";u.forEach((t=>{const s=`${r}${n}${t[0].replace(/^\$0 ?/,"")}`;b.span({text:s,padding:[0,2,0,2],width:O(u,y,`${e}${n}`)+4},{text:t[1]});const o=[];t[2]&&o.push(`[${i("default")}]`),t[3]&&t[3].length&&o.push(`[${i("aliases:")} ${t[3].join(", ")}]`),t[4]&&("string"==typeof t[4]?o.push(`[${i("deprecated: %s",t[4])}]`):o.push(`[${i("deprecated")}]`)),o.length?b.div({text:o.join(" "),padding:[0,0,0,2],align:"right"}):b.div()})),b.div()}const M=(Object.keys(l.alias)||[]).concat(Object.keys(t.parsed.newAliases)||[]);g=g.filter((e=>!t.parsed.newAliases[e]&&M.every((t=>-1===(l.alias[t]||[]).indexOf(e)))));const _=i("Options:");h[_]||(h[_]=[]),function(t,e,s,i){let n=[],r=null;Object.keys(s).forEach((t=>{n=n.concat(s[t])})),t.forEach((t=>{r=[t].concat(e[t]),r.some((t=>-1!==n.indexOf(t)))||s[i].push(t)}))}(g,l.alias,h,_);const k=t=>/^--/.test(I(t)),x=Object.keys(h).filter((t=>h[t].length>0)).map((t=>({groupName:t,normalizedKeys:h[t].filter(C).map((t=>{if(M.includes(t))return t;for(let e,s=0;void 0!==(e=M[s]);s++)if((l.alias[e]||[]).includes(t))return e;return t}))}))).filter((({normalizedKeys:t})=>t.length>0)).map((({groupName:t,normalizedKeys:e})=>{const s=e.reduce(((e,s)=>(e[s]=[s].concat(l.alias[s]||[]).map((e=>t===n.getPositionalGroupName()?e:(/^[0-9]$/.test(e)?l.boolean.includes(s)?"-":"--":e.length>1?"--":"-")+e)).sort(((t,e)=>k(t)===k(e)?0:k(t)?1:-1)).join(", "),e)),{});return{groupName:t,normalizedKeys:e,switches:s}}));if(x.filter((({groupName:t})=>t!==n.getPositionalGroupName())).some((({normalizedKeys:t,switches:e})=>!t.every((t=>k(e[t])))))&&x.filter((({groupName:t})=>t!==n.getPositionalGroupName())).forEach((({normalizedKeys:t,switches:e})=>{t.forEach((t=>{var s,i;k(e[t])&&(e[t]=(s=e[t],i=4,S(s)?{text:s.text,indentation:s.indentation+i}:{text:s,indentation:i}))}))})),x.forEach((({groupName:e,normalizedKeys:s,switches:o})=>{b.div(e),s.forEach((e=>{const s=o[e];let h=p[e]||"",c=null;h.includes(v)&&(h=i(h.substring(16))),l.boolean.includes(e)&&(c=`[${i("boolean")}]`),l.count.includes(e)&&(c=`[${i("count")}]`),l.string.includes(e)&&(c=`[${i("string")}]`),l.normalize.includes(e)&&(c=`[${i("string")}]`),l.array.includes(e)&&(c=`[${i("array")}]`),l.number.includes(e)&&(c=`[${i("number")}]`);const f=[e in a?(d=a[e],"string"==typeof d?`[${i("deprecated: %s",d)}]`:`[${i("deprecated")}]`):null,c,e in r?`[${i("required")}]`:null,l.choices&&l.choices[e]?`[${i("choices:")} ${n.stringifiedValues(l.choices[e])}]`:null,j(l.default[e],l.defaultDescription[e])].filter(Boolean).join(" ");var d;b.span({text:I(s),padding:[0,2,0,2+$(s)],width:O(o,y)+4},h);const u=!0===t.getInternalMethods().getUsageConfiguration()["hide-types"];f&&!u?b.div({text:f,padding:[0,0,0,2],align:"right"}):b.div()})),b.div()})),d.length&&(b.div(i("Examples:")),d.forEach((t=>{t[0]=t[0].replace(/\$0/g,e)})),d.forEach((t=>{""===t[1]?b.div({text:t[0],padding:[0,2,0,2]}):b.div({text:t[0],padding:[0,2,0,2],width:O(d,y)+4},{text:t[1]})})),b.div()),m.length>0){const t=m.map((t=>t.replace(/\$0/g,e))).join("\n");b.div(`${t}\n`)}return b.toString().replace(/\s*$/,"")},n.cacheHelpMessage=function(){w=this.help()},n.clearCachedHelpMessage=function(){w=void 0},n.hasCachedHelpMessage=function(){return!!w},n.showHelp=e=>{const s=t.getInternalMethods().getLoggerInstance();e||(e="error");("function"==typeof e?e:s[e])(n.help())},n.functionDescription=t=>["(",t.name?s.Parser.decamelize(t.name,"-"):i("generated-value"),")"].join(""),n.stringifiedValues=function(t,e){let s="";const i=e||", ",n=[].concat(t);return t&&n.length?(n.forEach((t=>{s.length&&(s+=i),s+=JSON.stringify(t)})),s):s};let M=null;n.version=t=>{M=t},n.showVersion=e=>{const s=t.getInternalMethods().getLoggerInstance();e||(e="error");("function"==typeof e?e:s[e])(M)},n.reset=function(t){return o=null,l=!1,c=[],f=!1,m=[],d=[],u=[],p=g(p,(e=>!t[e])),n};const _=[];return n.freeze=function(){_.push({failMessage:o,failureOutput:l,usages:c,usageDisabled:f,epilogs:m,examples:d,commands:u,descriptions:p})},n.unfreeze=function(t=!1){const e=_.pop();e&&(t?(p={...e.descriptions,...p},u=[...e.commands,...u],c=[...e.usages,...c],d=[...e.examples,...d],m=[...e.epilogs,...m]):({failMessage:o,failureOutput:l,usages:c,usageDisabled:f,epilogs:m,examples:d,commands:u,descriptions:p}=e))},n}function S(t){return"object"==typeof t}function $(t){return S(t)?t.indentation:0}function I(t){return S(t)?t.text:t}class D{constructor(t,e,s,i){var n,r,o;this.yargs=t,this.usage=e,this.command=s,this.shim=i,this.completionKey="get-yargs-completions",this.aliases=null,this.customCompletionFunction=null,this.indexAfterLastReset=0,this.zshShell=null!==(o=(null===(n=this.shim.getEnv("SHELL"))||void 0===n?void 0:n.includes("zsh"))||(null===(r=this.shim.getEnv("ZSH_NAME"))||void 0===r?void 0:r.includes("zsh")))&&void 0!==o&&o}defaultCompletion(t,e,s,i){const n=this.command.getCommandHandlers();for(let e=0,s=t.length;e{const i=o(s[0]).cmd;if(-1===e.indexOf(i))if(this.zshShell){const e=s[1]||"";t.push(i.replace(/:/g,"\\:")+":"+e)}else t.push(i)}))}optionCompletions(t,e,s,i){if((i.match(/^-/)||""===i&&0===t.length)&&!this.previousArgHasChoices(e)){const s=this.yargs.getOptions(),n=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[];Object.keys(s.key).forEach((r=>{const o=!!s.configuration["boolean-negation"]&&s.boolean.includes(r);n.includes(r)||s.hiddenOptions.includes(r)||this.argsContainKey(e,r,o)||this.completeOptionKey(r,t,i,o&&!!s.default[r])}))}}choicesFromOptionsCompletions(t,e,s,i){if(this.previousArgHasChoices(e)){const s=this.getPreviousArgChoices(e);s&&s.length>0&&t.push(...s.map((t=>t.replace(/:/g,"\\:"))))}}choicesFromPositionalsCompletions(t,e,s,i){if(""===i&&t.length>0&&this.previousArgHasChoices(e))return;const n=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[],r=Math.max(this.indexAfterLastReset,this.yargs.getInternalMethods().getContext().commands.length+1),o=n[s._.length-r-1];if(!o)return;const a=this.yargs.getOptions().choices[o]||[];for(const e of a)e.startsWith(i)&&t.push(e.replace(/:/g,"\\:"))}getPreviousArgChoices(t){if(t.length<1)return;let e=t[t.length-1],s="";if(!e.startsWith("-")&&t.length>1&&(s=e,e=t[t.length-2]),!e.startsWith("-"))return;const i=e.replace(/^-+/,""),n=this.yargs.getOptions(),r=[i,...this.yargs.getAliases()[i]||[]];let o;for(const t of r)if(Object.prototype.hasOwnProperty.call(n.key,t)&&Array.isArray(n.choices[t])){o=n.choices[t];break}return o?o.filter((t=>!s||t.startsWith(s))):void 0}previousArgHasChoices(t){const e=this.getPreviousArgChoices(t);return void 0!==e&&e.length>0}argsContainKey(t,e,s){const i=e=>-1!==t.indexOf((/^[^0-9]$/.test(e)?"-":"--")+e);if(i(e))return!0;if(s&&i(`no-${e}`))return!0;if(this.aliases)for(const t of this.aliases[e])if(i(t))return!0;return!1}completeOptionKey(t,e,s,i){var n,r,o,a;let h=t;if(this.zshShell){const e=this.usage.getDescriptions(),s=null===(r=null===(n=null==this?void 0:this.aliases)||void 0===n?void 0:n[t])||void 0===r?void 0:r.find((t=>{const s=e[t];return"string"==typeof s&&s.length>0})),i=s?e[s]:void 0,l=null!==(a=null!==(o=e[t])&&void 0!==o?o:i)&&void 0!==a?a:"";h=`${t.replace(/:/g,"\\:")}:${l.replace("__yargsString__:","").replace(/(\r\n|\n|\r)/gm," ")}`}const l=!/^--/.test(s)&&(t=>/^[^0-9]$/.test(t))(t)?"-":"--";e.push(l+h),i&&e.push(l+"no-"+h)}customCompletion(t,e,s,i){if(d(this.customCompletionFunction,null,this.shim),this.customCompletionFunction.length<3){const t=this.customCompletionFunction(s,e);return f(t)?t.then((t=>{this.shim.process.nextTick((()=>{i(null,t)}))})).catch((t=>{this.shim.process.nextTick((()=>{i(t,void 0)}))})):i(null,t)}return function(t){return t.length>3}(this.customCompletionFunction)?this.customCompletionFunction(s,e,((n=i)=>this.defaultCompletion(t,e,s,n)),(t=>{i(null,t)})):this.customCompletionFunction(s,e,(t=>{i(null,t)}))}getCompletion(t,e){const s=t.length?t[t.length-1]:"",i=this.yargs.parse(t,!0),n=this.customCompletionFunction?i=>this.customCompletion(t,i,s,e):i=>this.defaultCompletion(t,i,s,e);return f(i)?i.then(n):n(i)}generateCompletionScript(t,e){let s=this.zshShell?'#compdef {{app_name}}\n###-begin-{{app_name}}-completions-###\n#\n# yargs command completion script\n#\n# Installation: {{app_path}} {{completion_command}} >> ~/.zshrc\n# or {{app_path}} {{completion_command}} >> ~/.zprofile on OSX.\n#\n_{{app_name}}_yargs_completions()\n{\n local reply\n local si=$IFS\n IFS=$\'\n\' reply=($(COMP_CWORD="$((CURRENT-1))" COMP_LINE="$BUFFER" COMP_POINT="$CURSOR" {{app_path}} --get-yargs-completions "${words[@]}"))\n IFS=$si\n _describe \'values\' reply\n}\ncompdef _{{app_name}}_yargs_completions {{app_name}}\n###-end-{{app_name}}-completions-###\n':'###-begin-{{app_name}}-completions-###\n#\n# yargs command completion script\n#\n# Installation: {{app_path}} {{completion_command}} >> ~/.bashrc\n# or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX.\n#\n_{{app_name}}_yargs_completions()\n{\n local cur_word args type_list\n\n cur_word="${COMP_WORDS[COMP_CWORD]}"\n args=("${COMP_WORDS[@]}")\n\n # ask yargs to generate completions.\n type_list=$({{app_path}} --get-yargs-completions "${args[@]}")\n\n COMPREPLY=( $(compgen -W "${type_list}" -- ${cur_word}) )\n\n # if no match was found, fall back to filename completion\n if [ ${#COMPREPLY[@]} -eq 0 ]; then\n COMPREPLY=()\n fi\n\n return 0\n}\ncomplete -o bashdefault -o default -F _{{app_name}}_yargs_completions {{app_name}}\n###-end-{{app_name}}-completions-###\n';const i=this.shim.path.basename(t);return t.match(/\.js$/)&&(t=`./${t}`),s=s.replace(/{{app_name}}/g,i),s=s.replace(/{{completion_command}}/g,e),s.replace(/{{app_path}}/g,t)}registerFunction(t){this.customCompletionFunction=t}setParsed(t){this.aliases=t.aliases}}function N(t,e){if(0===t.length)return e.length;if(0===e.length)return t.length;const s=[];let i,n;for(i=0;i<=e.length;i++)s[i]=[i];for(n=0;n<=t.length;n++)s[0][n]=n;for(i=1;i<=e.length;i++)for(n=1;n<=t.length;n++)e.charAt(i-1)===t.charAt(n-1)?s[i][n]=s[i-1][n-1]:i>1&&n>1&&e.charAt(i-2)===t.charAt(n-1)&&e.charAt(i-1)===t.charAt(n-2)?s[i][n]=s[i-2][n-2]+1:s[i][n]=Math.min(s[i-1][n-1]+1,Math.min(s[i][n-1]+1,s[i-1][n]+1));return s[e.length][t.length]}const H=["$0","--","_"];var z,W,q,U,F,L,V,G,R,T,B,Y,K,J,Z,X,Q,tt,et,st,it,nt,rt,ot,at,ht,lt,ct,ft,dt,ut,pt,gt,mt,yt;const bt=Symbol("copyDoubleDash"),vt=Symbol("copyDoubleDash"),Ot=Symbol("deleteFromParserHintObject"),wt=Symbol("emitWarning"),Ct=Symbol("freeze"),jt=Symbol("getDollarZero"),Mt=Symbol("getParserConfiguration"),_t=Symbol("getUsageConfiguration"),kt=Symbol("guessLocale"),xt=Symbol("guessVersion"),Et=Symbol("parsePositionalNumbers"),At=Symbol("pkgUp"),Pt=Symbol("populateParserHintArray"),St=Symbol("populateParserHintSingleValueDictionary"),$t=Symbol("populateParserHintArrayDictionary"),It=Symbol("populateParserHintDictionary"),Dt=Symbol("sanitizeKey"),Nt=Symbol("setKey"),Ht=Symbol("unfreeze"),zt=Symbol("validateAsync"),Wt=Symbol("getCommandInstance"),qt=Symbol("getContext"),Ut=Symbol("getHasOutput"),Ft=Symbol("getLoggerInstance"),Lt=Symbol("getParseContext"),Vt=Symbol("getUsageInstance"),Gt=Symbol("getValidationInstance"),Rt=Symbol("hasParseCallback"),Tt=Symbol("isGlobalContext"),Bt=Symbol("postProcess"),Yt=Symbol("rebase"),Kt=Symbol("reset"),Jt=Symbol("runYargsParserAndExecuteCommands"),Zt=Symbol("runValidation"),Xt=Symbol("setHasOutput"),Qt=Symbol("kTrackManuallySetKeys");class te{constructor(t=[],e,s,i){this.customScriptName=!1,this.parsed=!1,z.set(this,void 0),W.set(this,void 0),q.set(this,{commands:[],fullCommands:[]}),U.set(this,null),F.set(this,null),L.set(this,"show-hidden"),V.set(this,null),G.set(this,!0),R.set(this,{}),T.set(this,!0),B.set(this,[]),Y.set(this,void 0),K.set(this,{}),J.set(this,!1),Z.set(this,null),X.set(this,!0),Q.set(this,void 0),tt.set(this,""),et.set(this,void 0),st.set(this,void 0),it.set(this,{}),nt.set(this,null),rt.set(this,null),ot.set(this,{}),at.set(this,{}),ht.set(this,void 0),lt.set(this,!1),ct.set(this,void 0),ft.set(this,!1),dt.set(this,!1),ut.set(this,!1),pt.set(this,void 0),gt.set(this,{}),mt.set(this,null),yt.set(this,void 0),O(this,ct,i,"f"),O(this,ht,t,"f"),O(this,W,e,"f"),O(this,st,s,"f"),O(this,Y,new w(this),"f"),this.$0=this[jt](),this[Kt](),O(this,z,v(this,z,"f"),"f"),O(this,pt,v(this,pt,"f"),"f"),O(this,yt,v(this,yt,"f"),"f"),O(this,et,v(this,et,"f"),"f"),v(this,et,"f").showHiddenOpt=v(this,L,"f"),O(this,Q,this[vt](),"f")}addHelpOpt(t,e){return h("[string|boolean] [string]",[t,e],arguments.length),v(this,Z,"f")&&(this[Ot](v(this,Z,"f")),O(this,Z,null,"f")),!1===t&&void 0===e||(O(this,Z,"string"==typeof t?t:"help","f"),this.boolean(v(this,Z,"f")),this.describe(v(this,Z,"f"),e||v(this,pt,"f").deferY18nLookup("Show help"))),this}help(t,e){return this.addHelpOpt(t,e)}addShowHiddenOpt(t,e){if(h("[string|boolean] [string]",[t,e],arguments.length),!1===t&&void 0===e)return this;const s="string"==typeof t?t:v(this,L,"f");return this.boolean(s),this.describe(s,e||v(this,pt,"f").deferY18nLookup("Show hidden options")),v(this,et,"f").showHiddenOpt=s,this}showHidden(t,e){return this.addShowHiddenOpt(t,e)}alias(t,e){return h(" [string|array]",[t,e],arguments.length),this[$t](this.alias.bind(this),"alias",t,e),this}array(t){return h("",[t],arguments.length),this[Pt]("array",t),this[Qt](t),this}boolean(t){return h("",[t],arguments.length),this[Pt]("boolean",t),this[Qt](t),this}check(t,e){return h(" [boolean]",[t,e],arguments.length),this.middleware(((e,s)=>j((()=>t(e,s.getOptions())),(s=>(s?("string"==typeof s||s instanceof Error)&&v(this,pt,"f").fail(s.toString(),s):v(this,pt,"f").fail(v(this,ct,"f").y18n.__("Argument check failed: %s",t.toString())),e)),(t=>(v(this,pt,"f").fail(t.message?t.message:t.toString(),t),e)))),!1,e),this}choices(t,e){return h(" [string|array]",[t,e],arguments.length),this[$t](this.choices.bind(this),"choices",t,e),this}coerce(t,s){if(h(" [function]",[t,s],arguments.length),Array.isArray(t)){if(!s)throw new e("coerce callback must be provided");for(const e of t)this.coerce(e,s);return this}if("object"==typeof t){for(const e of Object.keys(t))this.coerce(e,t[e]);return this}if(!s)throw new e("coerce callback must be provided");return v(this,et,"f").key[t]=!0,v(this,Y,"f").addCoerceMiddleware(((i,n)=>{let r;return Object.prototype.hasOwnProperty.call(i,t)?j((()=>(r=n.getAliases(),s(i[t]))),(e=>{i[t]=e;const s=n.getInternalMethods().getParserConfiguration()["strip-aliased"];if(r[t]&&!0!==s)for(const s of r[t])i[s]=e;return i}),(t=>{throw new e(t.message)})):i}),t),this}conflicts(t,e){return h(" [string|array]",[t,e],arguments.length),v(this,yt,"f").conflicts(t,e),this}config(t="config",e,s){return h("[object|string] [string|function] [function]",[t,e,s],arguments.length),"object"!=typeof t||Array.isArray(t)?("function"==typeof e&&(s=e,e=void 0),this.describe(t,e||v(this,pt,"f").deferY18nLookup("Path to JSON config file")),(Array.isArray(t)?t:[t]).forEach((t=>{v(this,et,"f").config[t]=s||!0})),this):(t=n(t,v(this,W,"f"),this[Mt]()["deep-merge-config"]||!1,v(this,ct,"f")),v(this,et,"f").configObjects=(v(this,et,"f").configObjects||[]).concat(t),this)}completion(t,e,s){return h("[string] [string|boolean|function] [function]",[t,e,s],arguments.length),"function"==typeof e&&(s=e,e=void 0),O(this,F,t||v(this,F,"f")||"completion","f"),e||!1===e||(e="generate completion script"),this.command(v(this,F,"f"),e),s&&v(this,U,"f").registerFunction(s),this}command(t,e,s,i,n,r){return h(" [string|boolean] [function|object] [function] [array] [boolean|string]",[t,e,s,i,n,r],arguments.length),v(this,z,"f").addHandler(t,e,s,i,n,r),this}commands(t,e,s,i,n,r){return this.command(t,e,s,i,n,r)}commandDir(t,e){h(" [object]",[t,e],arguments.length);const s=v(this,st,"f")||v(this,ct,"f").require;return v(this,z,"f").addDirectory(t,s,v(this,ct,"f").getCallerFile(),e),this}count(t){return h("",[t],arguments.length),this[Pt]("count",t),this[Qt](t),this}default(t,e,s){return h(" [*] [string]",[t,e,s],arguments.length),s&&(u(t,v(this,ct,"f")),v(this,et,"f").defaultDescription[t]=s),"function"==typeof e&&(u(t,v(this,ct,"f")),v(this,et,"f").defaultDescription[t]||(v(this,et,"f").defaultDescription[t]=v(this,pt,"f").functionDescription(e)),e=e.call()),this[St](this.default.bind(this),"default",t,e),this}defaults(t,e,s){return this.default(t,e,s)}demandCommand(t=1,e,s,i){return h("[number] [number|string] [string|null|undefined] [string|null|undefined]",[t,e,s,i],arguments.length),"number"!=typeof e&&(s=e,e=1/0),this.global("_",!1),v(this,et,"f").demandedCommands._={min:t,max:e,minMsg:s,maxMsg:i},this}demand(t,e,s){return Array.isArray(e)?(e.forEach((t=>{d(s,!0,v(this,ct,"f")),this.demandOption(t,s)})),e=1/0):"number"!=typeof e&&(s=e,e=1/0),"number"==typeof t?(d(s,!0,v(this,ct,"f")),this.demandCommand(t,e,s,s)):Array.isArray(t)?t.forEach((t=>{d(s,!0,v(this,ct,"f")),this.demandOption(t,s)})):"string"==typeof s?this.demandOption(t,s):!0!==s&&void 0!==s||this.demandOption(t),this}demandOption(t,e){return h(" [string]",[t,e],arguments.length),this[St](this.demandOption.bind(this),"demandedOptions",t,e),this}deprecateOption(t,e){return h(" [string|boolean]",[t,e],arguments.length),v(this,et,"f").deprecatedOptions[t]=e,this}describe(t,e){return h(" [string]",[t,e],arguments.length),this[Nt](t,!0),v(this,pt,"f").describe(t,e),this}detectLocale(t){return h("",[t],arguments.length),O(this,G,t,"f"),this}env(t){return h("[string|boolean]",[t],arguments.length),!1===t?delete v(this,et,"f").envPrefix:v(this,et,"f").envPrefix=t||"",this}epilogue(t){return h("",[t],arguments.length),v(this,pt,"f").epilog(t),this}epilog(t){return this.epilogue(t)}example(t,e){return h(" [string]",[t,e],arguments.length),Array.isArray(t)?t.forEach((t=>this.example(...t))):v(this,pt,"f").example(t,e),this}exit(t,e){O(this,J,!0,"f"),O(this,V,e,"f"),v(this,T,"f")&&v(this,ct,"f").process.exit(t)}exitProcess(t=!0){return h("[boolean]",[t],arguments.length),O(this,T,t,"f"),this}fail(t){if(h("",[t],arguments.length),"boolean"==typeof t&&!1!==t)throw new e("Invalid first argument. Expected function or boolean 'false'");return v(this,pt,"f").failFn(t),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(t,e){return h(" [function]",[t,e],arguments.length),e?v(this,U,"f").getCompletion(t,e):new Promise(((e,s)=>{v(this,U,"f").getCompletion(t,((t,i)=>{t?s(t):e(i)}))}))}getDemandedOptions(){return h([],0),v(this,et,"f").demandedOptions}getDemandedCommands(){return h([],0),v(this,et,"f").demandedCommands}getDeprecatedOptions(){return h([],0),v(this,et,"f").deprecatedOptions}getDetectLocale(){return v(this,G,"f")}getExitProcess(){return v(this,T,"f")}getGroups(){return Object.assign({},v(this,K,"f"),v(this,at,"f"))}getHelp(){if(O(this,J,!0,"f"),!v(this,pt,"f").hasCachedHelpMessage()){if(!this.parsed){const t=this[Jt](v(this,ht,"f"),void 0,void 0,0,!0);if(f(t))return t.then((()=>v(this,pt,"f").help()))}const t=v(this,z,"f").runDefaultBuilderOn(this);if(f(t))return t.then((()=>v(this,pt,"f").help()))}return Promise.resolve(v(this,pt,"f").help())}getOptions(){return v(this,et,"f")}getStrict(){return v(this,ft,"f")}getStrictCommands(){return v(this,dt,"f")}getStrictOptions(){return v(this,ut,"f")}global(t,e){return h(" [boolean]",[t,e],arguments.length),t=[].concat(t),!1!==e?v(this,et,"f").local=v(this,et,"f").local.filter((e=>-1===t.indexOf(e))):t.forEach((t=>{v(this,et,"f").local.includes(t)||v(this,et,"f").local.push(t)})),this}group(t,e){h(" ",[t,e],arguments.length);const s=v(this,at,"f")[e]||v(this,K,"f")[e];v(this,at,"f")[e]&&delete v(this,at,"f")[e];const i={};return v(this,K,"f")[e]=(s||[]).concat(t).filter((t=>!i[t]&&(i[t]=!0))),this}hide(t){return h("",[t],arguments.length),v(this,et,"f").hiddenOptions.push(t),this}implies(t,e){return h(" [number|string|array]",[t,e],arguments.length),v(this,yt,"f").implies(t,e),this}locale(t){return h("[string]",[t],arguments.length),void 0===t?(this[kt](),v(this,ct,"f").y18n.getLocale()):(O(this,G,!1,"f"),v(this,ct,"f").y18n.setLocale(t),this)}middleware(t,e,s){return v(this,Y,"f").addMiddleware(t,!!e,s)}nargs(t,e){return h(" [number]",[t,e],arguments.length),this[St](this.nargs.bind(this),"narg",t,e),this}normalize(t){return h("",[t],arguments.length),this[Pt]("normalize",t),this}number(t){return h("",[t],arguments.length),this[Pt]("number",t),this[Qt](t),this}option(t,e){if(h(" [object]",[t,e],arguments.length),"object"==typeof t)Object.keys(t).forEach((e=>{this.options(e,t[e])}));else{"object"!=typeof e&&(e={}),this[Qt](t),!v(this,mt,"f")||"version"!==t&&"version"!==(null==e?void 0:e.alias)||this[wt](['"version" is a reserved word.',"Please do one of the following:",'- Disable version with `yargs.version(false)` if using "version" as an option',"- Use the built-in `yargs.version` method instead (if applicable)","- Use a different option key","https://yargs.js.org/docs/#api-reference-version"].join("\n"),void 0,"versionWarning"),v(this,et,"f").key[t]=!0,e.alias&&this.alias(t,e.alias);const s=e.deprecate||e.deprecated;s&&this.deprecateOption(t,s);const i=e.demand||e.required||e.require;i&&this.demand(t,i),e.demandOption&&this.demandOption(t,"string"==typeof e.demandOption?e.demandOption:void 0),e.conflicts&&this.conflicts(t,e.conflicts),"default"in e&&this.default(t,e.default),void 0!==e.implies&&this.implies(t,e.implies),void 0!==e.nargs&&this.nargs(t,e.nargs),e.config&&this.config(t,e.configParser),e.normalize&&this.normalize(t),e.choices&&this.choices(t,e.choices),e.coerce&&this.coerce(t,e.coerce),e.group&&this.group(t,e.group),(e.boolean||"boolean"===e.type)&&(this.boolean(t),e.alias&&this.boolean(e.alias)),(e.array||"array"===e.type)&&(this.array(t),e.alias&&this.array(e.alias)),(e.number||"number"===e.type)&&(this.number(t),e.alias&&this.number(e.alias)),(e.string||"string"===e.type)&&(this.string(t),e.alias&&this.string(e.alias)),(e.count||"count"===e.type)&&this.count(t),"boolean"==typeof e.global&&this.global(t,e.global),e.defaultDescription&&(v(this,et,"f").defaultDescription[t]=e.defaultDescription),e.skipValidation&&this.skipValidation(t);const n=e.describe||e.description||e.desc,r=v(this,pt,"f").getDescriptions();Object.prototype.hasOwnProperty.call(r,t)&&"string"!=typeof n||this.describe(t,n),e.hidden&&this.hide(t),e.requiresArg&&this.requiresArg(t)}return this}options(t,e){return this.option(t,e)}parse(t,e,s){h("[string|array] [function|boolean|object] [function]",[t,e,s],arguments.length),this[Ct](),void 0===t&&(t=v(this,ht,"f")),"object"==typeof e&&(O(this,rt,e,"f"),e=s),"function"==typeof e&&(O(this,nt,e,"f"),e=!1),e||O(this,ht,t,"f"),v(this,nt,"f")&&O(this,T,!1,"f");const i=this[Jt](t,!!e),n=this.parsed;return v(this,U,"f").setParsed(this.parsed),f(i)?i.then((t=>(v(this,nt,"f")&&v(this,nt,"f").call(this,v(this,V,"f"),t,v(this,tt,"f")),t))).catch((t=>{throw v(this,nt,"f")&&v(this,nt,"f")(t,this.parsed.argv,v(this,tt,"f")),t})).finally((()=>{this[Ht](),this.parsed=n})):(v(this,nt,"f")&&v(this,nt,"f").call(this,v(this,V,"f"),i,v(this,tt,"f")),this[Ht](),this.parsed=n,i)}parseAsync(t,e,s){const i=this.parse(t,e,s);return f(i)?i:Promise.resolve(i)}parseSync(t,s,i){const n=this.parse(t,s,i);if(f(n))throw new e(".parseSync() must not be used with asynchronous builders, handlers, or middleware");return n}parserConfiguration(t){return h("",[t],arguments.length),O(this,it,t,"f"),this}pkgConf(t,e){h(" [string]",[t,e],arguments.length);let s=null;const i=this[At](e||v(this,W,"f"));return i[t]&&"object"==typeof i[t]&&(s=n(i[t],e||v(this,W,"f"),this[Mt]()["deep-merge-config"]||!1,v(this,ct,"f")),v(this,et,"f").configObjects=(v(this,et,"f").configObjects||[]).concat(s)),this}positional(t,e){h(" ",[t,e],arguments.length);const s=["default","defaultDescription","implies","normalize","choices","conflicts","coerce","type","describe","desc","description","alias"];e=g(e,((t,e)=>!("type"===t&&!["string","number","boolean"].includes(e))&&s.includes(t)));const i=v(this,q,"f").fullCommands[v(this,q,"f").fullCommands.length-1],n=i?v(this,z,"f").cmdToParseOptions(i):{array:[],alias:{},default:{},demand:{}};return p(n).forEach((s=>{const i=n[s];Array.isArray(i)?-1!==i.indexOf(t)&&(e[s]=!0):i[t]&&!(s in e)&&(e[s]=i[t])})),this.group(t,v(this,pt,"f").getPositionalGroupName()),this.option(t,e)}recommendCommands(t=!0){return h("[boolean]",[t],arguments.length),O(this,lt,t,"f"),this}required(t,e,s){return this.demand(t,e,s)}require(t,e,s){return this.demand(t,e,s)}requiresArg(t){return h(" [number]",[t],arguments.length),"string"==typeof t&&v(this,et,"f").narg[t]||this[St](this.requiresArg.bind(this),"narg",t,NaN),this}showCompletionScript(t,e){return h("[string] [string]",[t,e],arguments.length),t=t||this.$0,v(this,Q,"f").log(v(this,U,"f").generateCompletionScript(t,e||v(this,F,"f")||"completion")),this}showHelp(t){if(h("[string|function]",[t],arguments.length),O(this,J,!0,"f"),!v(this,pt,"f").hasCachedHelpMessage()){if(!this.parsed){const e=this[Jt](v(this,ht,"f"),void 0,void 0,0,!0);if(f(e))return e.then((()=>{v(this,pt,"f").showHelp(t)})),this}const e=v(this,z,"f").runDefaultBuilderOn(this);if(f(e))return e.then((()=>{v(this,pt,"f").showHelp(t)})),this}return v(this,pt,"f").showHelp(t),this}scriptName(t){return this.customScriptName=!0,this.$0=t,this}showHelpOnFail(t,e){return h("[boolean|string] [string]",[t,e],arguments.length),v(this,pt,"f").showHelpOnFail(t,e),this}showVersion(t){return h("[string|function]",[t],arguments.length),v(this,pt,"f").showVersion(t),this}skipValidation(t){return h("",[t],arguments.length),this[Pt]("skipValidation",t),this}strict(t){return h("[boolean]",[t],arguments.length),O(this,ft,!1!==t,"f"),this}strictCommands(t){return h("[boolean]",[t],arguments.length),O(this,dt,!1!==t,"f"),this}strictOptions(t){return h("[boolean]",[t],arguments.length),O(this,ut,!1!==t,"f"),this}string(t){return h("",[t],arguments.length),this[Pt]("string",t),this[Qt](t),this}terminalWidth(){return h([],0),v(this,ct,"f").process.stdColumns}updateLocale(t){return this.updateStrings(t)}updateStrings(t){return h("",[t],arguments.length),O(this,G,!1,"f"),v(this,ct,"f").y18n.updateLocale(t),this}usage(t,s,i,n){if(h(" [string|boolean] [function|object] [function]",[t,s,i,n],arguments.length),void 0!==s){if(d(t,null,v(this,ct,"f")),(t||"").match(/^\$0( |$)/))return this.command(t,s,i,n);throw new e(".usage() description must start with $0 if being used as alias for .command()")}return v(this,pt,"f").usage(t),this}usageConfiguration(t){return h("",[t],arguments.length),O(this,gt,t,"f"),this}version(t,e,s){const i="version";if(h("[boolean|string] [string] [string]",[t,e,s],arguments.length),v(this,mt,"f")&&(this[Ot](v(this,mt,"f")),v(this,pt,"f").version(void 0),O(this,mt,null,"f")),0===arguments.length)s=this[xt](),t=i;else if(1===arguments.length){if(!1===t)return this;s=t,t=i}else 2===arguments.length&&(s=e,e=void 0);return O(this,mt,"string"==typeof t?t:i,"f"),e=e||v(this,pt,"f").deferY18nLookup("Show version number"),v(this,pt,"f").version(s||void 0),this.boolean(v(this,mt,"f")),this.describe(v(this,mt,"f"),e),this}wrap(t){return h("",[t],arguments.length),v(this,pt,"f").wrap(t),this}[(z=new WeakMap,W=new WeakMap,q=new WeakMap,U=new WeakMap,F=new WeakMap,L=new WeakMap,V=new WeakMap,G=new WeakMap,R=new WeakMap,T=new WeakMap,B=new WeakMap,Y=new WeakMap,K=new WeakMap,J=new WeakMap,Z=new WeakMap,X=new WeakMap,Q=new WeakMap,tt=new WeakMap,et=new WeakMap,st=new WeakMap,it=new WeakMap,nt=new WeakMap,rt=new WeakMap,ot=new WeakMap,at=new WeakMap,ht=new WeakMap,lt=new WeakMap,ct=new WeakMap,ft=new WeakMap,dt=new WeakMap,ut=new WeakMap,pt=new WeakMap,gt=new WeakMap,mt=new WeakMap,yt=new WeakMap,bt)](t){if(!t._||!t["--"])return t;t._.push.apply(t._,t["--"]);try{delete t["--"]}catch(t){}return t}[vt](){return{log:(...t)=>{this[Rt]()||console.log(...t),O(this,J,!0,"f"),v(this,tt,"f").length&&O(this,tt,v(this,tt,"f")+"\n","f"),O(this,tt,v(this,tt,"f")+t.join(" "),"f")},error:(...t)=>{this[Rt]()||console.error(...t),O(this,J,!0,"f"),v(this,tt,"f").length&&O(this,tt,v(this,tt,"f")+"\n","f"),O(this,tt,v(this,tt,"f")+t.join(" "),"f")}}}[Ot](t){p(v(this,et,"f")).forEach((e=>{if("configObjects"===e)return;const s=v(this,et,"f")[e];Array.isArray(s)?s.includes(t)&&s.splice(s.indexOf(t),1):"object"==typeof s&&delete s[t]})),delete v(this,pt,"f").getDescriptions()[t]}[wt](t,e,s){v(this,R,"f")[s]||(v(this,ct,"f").process.emitWarning(t,e),v(this,R,"f")[s]=!0)}[Ct](){v(this,B,"f").push({options:v(this,et,"f"),configObjects:v(this,et,"f").configObjects.slice(0),exitProcess:v(this,T,"f"),groups:v(this,K,"f"),strict:v(this,ft,"f"),strictCommands:v(this,dt,"f"),strictOptions:v(this,ut,"f"),completionCommand:v(this,F,"f"),output:v(this,tt,"f"),exitError:v(this,V,"f"),hasOutput:v(this,J,"f"),parsed:this.parsed,parseFn:v(this,nt,"f"),parseContext:v(this,rt,"f")}),v(this,pt,"f").freeze(),v(this,yt,"f").freeze(),v(this,z,"f").freeze(),v(this,Y,"f").freeze()}[jt](){let t,e="";return t=/\b(node|iojs|electron)(\.exe)?$/.test(v(this,ct,"f").process.argv()[0])?v(this,ct,"f").process.argv().slice(1,2):v(this,ct,"f").process.argv().slice(0,1),e=t.map((t=>{const e=this[Yt](v(this,W,"f"),t);return t.match(/^(\/|([a-zA-Z]:)?\\)/)&&e.lengthe.includes("package.json")?"package.json":void 0));d(i,void 0,v(this,ct,"f")),s=JSON.parse(v(this,ct,"f").readFileSync(i,"utf8"))}catch(t){}return v(this,ot,"f")[e]=s||{},v(this,ot,"f")[e]}[Pt](t,e){(e=[].concat(e)).forEach((e=>{e=this[Dt](e),v(this,et,"f")[t].push(e)}))}[St](t,e,s,i){this[It](t,e,s,i,((t,e,s)=>{v(this,et,"f")[t][e]=s}))}[$t](t,e,s,i){this[It](t,e,s,i,((t,e,s)=>{v(this,et,"f")[t][e]=(v(this,et,"f")[t][e]||[]).concat(s)}))}[It](t,e,s,i,n){if(Array.isArray(s))s.forEach((e=>{t(e,i)}));else if((t=>"object"==typeof t)(s))for(const e of p(s))t(e,s[e]);else n(e,this[Dt](s),i)}[Dt](t){return"__proto__"===t?"___proto___":t}[Nt](t,e){return this[St](this[Nt].bind(this),"key",t,e),this}[Ht](){var t,e,s,i,n,r,o,a,h,l,c,f;const u=v(this,B,"f").pop();let p;d(u,void 0,v(this,ct,"f")),t=this,e=this,s=this,i=this,n=this,r=this,o=this,a=this,h=this,l=this,c=this,f=this,({options:{set value(e){O(t,et,e,"f")}}.value,configObjects:p,exitProcess:{set value(t){O(e,T,t,"f")}}.value,groups:{set value(t){O(s,K,t,"f")}}.value,output:{set value(t){O(i,tt,t,"f")}}.value,exitError:{set value(t){O(n,V,t,"f")}}.value,hasOutput:{set value(t){O(r,J,t,"f")}}.value,parsed:this.parsed,strict:{set value(t){O(o,ft,t,"f")}}.value,strictCommands:{set value(t){O(a,dt,t,"f")}}.value,strictOptions:{set value(t){O(h,ut,t,"f")}}.value,completionCommand:{set value(t){O(l,F,t,"f")}}.value,parseFn:{set value(t){O(c,nt,t,"f")}}.value,parseContext:{set value(t){O(f,rt,t,"f")}}.value}=u),v(this,et,"f").configObjects=p,v(this,pt,"f").unfreeze(),v(this,yt,"f").unfreeze(),v(this,z,"f").unfreeze(),v(this,Y,"f").unfreeze()}[zt](t,e){return j(e,(e=>(t(e),e)))}getInternalMethods(){return{getCommandInstance:this[Wt].bind(this),getContext:this[qt].bind(this),getHasOutput:this[Ut].bind(this),getLoggerInstance:this[Ft].bind(this),getParseContext:this[Lt].bind(this),getParserConfiguration:this[Mt].bind(this),getUsageConfiguration:this[_t].bind(this),getUsageInstance:this[Vt].bind(this),getValidationInstance:this[Gt].bind(this),hasParseCallback:this[Rt].bind(this),isGlobalContext:this[Tt].bind(this),postProcess:this[Bt].bind(this),reset:this[Kt].bind(this),runValidation:this[Zt].bind(this),runYargsParserAndExecuteCommands:this[Jt].bind(this),setHasOutput:this[Xt].bind(this)}}[Wt](){return v(this,z,"f")}[qt](){return v(this,q,"f")}[Ut](){return v(this,J,"f")}[Ft](){return v(this,Q,"f")}[Lt](){return v(this,rt,"f")||{}}[Vt](){return v(this,pt,"f")}[Gt](){return v(this,yt,"f")}[Rt](){return!!v(this,nt,"f")}[Tt](){return v(this,X,"f")}[Bt](t,e,s,i){if(s)return t;if(f(t))return t;e||(t=this[bt](t));return(this[Mt]()["parse-positional-numbers"]||void 0===this[Mt]()["parse-positional-numbers"])&&(t=this[Et](t)),i&&(t=C(t,this,v(this,Y,"f").getMiddleware(),!1)),t}[Kt](t={}){O(this,et,v(this,et,"f")||{},"f");const e={};e.local=v(this,et,"f").local||[],e.configObjects=v(this,et,"f").configObjects||[];const s={};e.local.forEach((e=>{s[e]=!0,(t[e]||[]).forEach((t=>{s[t]=!0}))})),Object.assign(v(this,at,"f"),Object.keys(v(this,K,"f")).reduce(((t,e)=>{const i=v(this,K,"f")[e].filter((t=>!(t in s)));return i.length>0&&(t[e]=i),t}),{})),O(this,K,{},"f");return["array","boolean","string","skipValidation","count","normalize","number","hiddenOptions"].forEach((t=>{e[t]=(v(this,et,"f")[t]||[]).filter((t=>!s[t]))})),["narg","key","alias","default","defaultDescription","config","choices","demandedOptions","demandedCommands","deprecatedOptions"].forEach((t=>{e[t]=g(v(this,et,"f")[t],(t=>!s[t]))})),e.envPrefix=v(this,et,"f").envPrefix,O(this,et,e,"f"),O(this,pt,v(this,pt,"f")?v(this,pt,"f").reset(s):P(this,v(this,ct,"f")),"f"),O(this,yt,v(this,yt,"f")?v(this,yt,"f").reset(s):function(t,e,s){const i=s.y18n.__,n=s.y18n.__n,r={nonOptionCount:function(s){const i=t.getDemandedCommands(),r=s._.length+(s["--"]?s["--"].length:0)-t.getInternalMethods().getContext().commands.length;i._&&(ri._.max)&&(ri._.max&&(void 0!==i._.maxMsg?e.fail(i._.maxMsg?i._.maxMsg.replace(/\$0/g,r.toString()).replace(/\$1/,i._.max.toString()):null):e.fail(n("Too many non-option arguments: got %s, maximum of %s","Too many non-option arguments: got %s, maximum of %s",r,r.toString(),i._.max.toString()))))},positionalCount:function(t,s){s{H.includes(e)||Object.prototype.hasOwnProperty.call(o,e)||Object.prototype.hasOwnProperty.call(t.getInternalMethods().getParseContext(),e)||r.isValidAndSomeAliasIsNotNew(e,i)||f.push(e)})),h&&(d.commands.length>0||c.length>0||a)&&s._.slice(d.commands.length).forEach((t=>{c.includes(""+t)||f.push(""+t)})),h){const e=(null===(l=t.getDemandedCommands()._)||void 0===l?void 0:l.max)||0,i=d.commands.length+e;i{t=String(t),d.commands.includes(t)||f.includes(t)||f.push(t)}))}f.length&&e.fail(n("Unknown argument: %s","Unknown arguments: %s",f.length,f.map((t=>t.trim()?t:`"${t}"`)).join(", ")))},unknownCommands:function(s){const i=t.getInternalMethods().getCommandInstance().getCommands(),r=[],o=t.getInternalMethods().getContext();return(o.commands.length>0||i.length>0)&&s._.slice(o.commands.length).forEach((t=>{i.includes(""+t)||r.push(""+t)})),r.length>0&&(e.fail(n("Unknown command: %s","Unknown commands: %s",r.length,r.join(", "))),!0)},isValidAndSomeAliasIsNotNew:function(e,s){if(!Object.prototype.hasOwnProperty.call(s,e))return!1;const i=t.parsed.newAliases;return[e,...s[e]].some((t=>!Object.prototype.hasOwnProperty.call(i,t)||!i[e]))},limitedChoices:function(s){const n=t.getOptions(),r={};if(!Object.keys(n.choices).length)return;Object.keys(s).forEach((t=>{-1===H.indexOf(t)&&Object.prototype.hasOwnProperty.call(n.choices,t)&&[].concat(s[t]).forEach((e=>{-1===n.choices[t].indexOf(e)&&void 0!==e&&(r[t]=(r[t]||[]).concat(e))}))}));const o=Object.keys(r);if(!o.length)return;let a=i("Invalid values:");o.forEach((t=>{a+=`\n ${i("Argument: %s, Given: %s, Choices: %s",t,e.stringifiedValues(r[t]),e.stringifiedValues(n.choices[t]))}`})),e.fail(a)}};let o={};function a(t,e){const s=Number(e);return"number"==typeof(e=isNaN(s)?e:s)?e=t._.length>=e:e.match(/^--no-.+/)?(e=e.match(/^--no-(.+)/)[1],e=!Object.prototype.hasOwnProperty.call(t,e)):e=Object.prototype.hasOwnProperty.call(t,e),e}r.implies=function(e,i){h(" [array|number|string]",[e,i],arguments.length),"object"==typeof e?Object.keys(e).forEach((t=>{r.implies(t,e[t])})):(t.global(e),o[e]||(o[e]=[]),Array.isArray(i)?i.forEach((t=>r.implies(e,t))):(d(i,void 0,s),o[e].push(i)))},r.getImplied=function(){return o},r.implications=function(t){const s=[];if(Object.keys(o).forEach((e=>{const i=e;(o[e]||[]).forEach((e=>{let n=i;const r=e;n=a(t,n),e=a(t,e),n&&!e&&s.push(` ${i} -> ${r}`)}))})),s.length){let t=`${i("Implications failed:")}\n`;s.forEach((e=>{t+=e})),e.fail(t)}};let l={};r.conflicts=function(e,s){h(" [array|string]",[e,s],arguments.length),"object"==typeof e?Object.keys(e).forEach((t=>{r.conflicts(t,e[t])})):(t.global(e),l[e]||(l[e]=[]),Array.isArray(s)?s.forEach((t=>r.conflicts(e,t))):l[e].push(s))},r.getConflicting=()=>l,r.conflicting=function(n){Object.keys(n).forEach((t=>{l[t]&&l[t].forEach((s=>{s&&void 0!==n[t]&&void 0!==n[s]&&e.fail(i("Arguments %s and %s are mutually exclusive",t,s))}))})),t.getInternalMethods().getParserConfiguration()["strip-dashed"]&&Object.keys(l).forEach((t=>{l[t].forEach((r=>{r&&void 0!==n[s.Parser.camelCase(t)]&&void 0!==n[s.Parser.camelCase(r)]&&e.fail(i("Arguments %s and %s are mutually exclusive",t,r))}))}))},r.recommendCommands=function(t,s){s=s.sort(((t,e)=>e.length-t.length));let n=null,r=1/0;for(let e,i=0;void 0!==(e=s[i]);i++){const s=N(t,e);s<=3&&s!t[e])),l=g(l,(e=>!t[e])),r};const c=[];return r.freeze=function(){c.push({implied:o,conflicting:l})},r.unfreeze=function(){const t=c.pop();d(t,void 0,s),({implied:o,conflicting:l}=t)},r}(this,v(this,pt,"f"),v(this,ct,"f")),"f"),O(this,z,v(this,z,"f")?v(this,z,"f").reset():function(t,e,s,i){return new _(t,e,s,i)}(v(this,pt,"f"),v(this,yt,"f"),v(this,Y,"f"),v(this,ct,"f")),"f"),v(this,U,"f")||O(this,U,function(t,e,s,i){return new D(t,e,s,i)}(this,v(this,pt,"f"),v(this,z,"f"),v(this,ct,"f")),"f"),v(this,Y,"f").reset(),O(this,F,null,"f"),O(this,tt,"","f"),O(this,V,null,"f"),O(this,J,!1,"f"),this.parsed=!1,this}[Yt](t,e){return v(this,ct,"f").path.relative(t,e)}[Jt](t,s,i,n=0,r=!1){let o=!!i||r;t=t||v(this,ht,"f"),v(this,et,"f").__=v(this,ct,"f").y18n.__,v(this,et,"f").configuration=this[Mt]();const a=!!v(this,et,"f").configuration["populate--"],h=Object.assign({},v(this,et,"f").configuration,{"populate--":!0}),l=v(this,ct,"f").Parser.detailed(t,Object.assign({},v(this,et,"f"),{configuration:{"parse-positional-numbers":!1,...h}})),c=Object.assign(l.argv,v(this,rt,"f"));let d;const u=l.aliases;let p=!1,g=!1;Object.keys(c).forEach((t=>{t===v(this,Z,"f")&&c[t]?p=!0:t===v(this,mt,"f")&&c[t]&&(g=!0)})),c.$0=this.$0,this.parsed=l,0===n&&v(this,pt,"f").clearCachedHelpMessage();try{if(this[kt](),s)return this[Bt](c,a,!!i,!1);if(v(this,Z,"f")){[v(this,Z,"f")].concat(u[v(this,Z,"f")]||[]).filter((t=>t.length>1)).includes(""+c._[c._.length-1])&&(c._.pop(),p=!0)}O(this,X,!1,"f");const h=v(this,z,"f").getCommands(),m=v(this,U,"f").completionKey in c,y=p||m||r;if(c._.length){if(h.length){let t;for(let e,s=n||0;void 0!==c._[s];s++){if(e=String(c._[s]),h.includes(e)&&e!==v(this,F,"f")){const t=v(this,z,"f").runCommand(e,this,l,s+1,r,p||g||r);return this[Bt](t,a,!!i,!1)}if(!t&&e!==v(this,F,"f")){t=e;break}}!v(this,z,"f").hasDefaultCommand()&&v(this,lt,"f")&&t&&!y&&v(this,yt,"f").recommendCommands(t,h)}v(this,F,"f")&&c._.includes(v(this,F,"f"))&&!m&&(v(this,T,"f")&&E(!0),this.showCompletionScript(),this.exit(0))}if(v(this,z,"f").hasDefaultCommand()&&!y){const t=v(this,z,"f").runCommand(null,this,l,0,r,p||g||r);return this[Bt](t,a,!!i,!1)}if(m){v(this,T,"f")&&E(!0);const s=(t=[].concat(t)).slice(t.indexOf(`--${v(this,U,"f").completionKey}`)+1);return v(this,U,"f").getCompletion(s,((t,s)=>{if(t)throw new e(t.message);(s||[]).forEach((t=>{v(this,Q,"f").log(t)})),this.exit(0)})),this[Bt](c,!a,!!i,!1)}if(v(this,J,"f")||(p?(v(this,T,"f")&&E(!0),o=!0,this.showHelp("log"),this.exit(0)):g&&(v(this,T,"f")&&E(!0),o=!0,v(this,pt,"f").showVersion("log"),this.exit(0))),!o&&v(this,et,"f").skipValidation.length>0&&(o=Object.keys(c).some((t=>v(this,et,"f").skipValidation.indexOf(t)>=0&&!0===c[t]))),!o){if(l.error)throw new e(l.error.message);if(!m){const t=this[Zt](u,{},l.error);i||(d=C(c,this,v(this,Y,"f").getMiddleware(),!0)),d=this[zt](t,null!=d?d:c),f(d)&&!i&&(d=d.then((()=>C(c,this,v(this,Y,"f").getMiddleware(),!1))))}}}catch(t){if(!(t instanceof e))throw t;v(this,pt,"f").fail(t.message,t)}return this[Bt](null!=d?d:c,a,!!i,!0)}[Zt](t,s,i,n){const r={...this.getDemandedOptions()};return o=>{if(i)throw new e(i.message);v(this,yt,"f").nonOptionCount(o),v(this,yt,"f").requiredArguments(o,r);let a=!1;v(this,dt,"f")&&(a=v(this,yt,"f").unknownCommands(o)),v(this,ft,"f")&&!a?v(this,yt,"f").unknownArguments(o,t,s,!!n):v(this,ut,"f")&&v(this,yt,"f").unknownArguments(o,t,{},!1,!1),v(this,yt,"f").limitedChoices(o),v(this,yt,"f").implications(o),v(this,yt,"f").conflicting(o)}}[Xt](){O(this,J,!0,"f")}[Qt](t){if("string"==typeof t)v(this,et,"f").key[t]=!0;else for(const e of t)v(this,et,"f").key[e]=!0}}var ee,se;const{readFileSync:ie}=require("fs"),{inspect:ne}=require("util"),{resolve:re}=require("path"),oe=require("y18n"),ae=require("yargs-parser");var he,le={assert:{notStrictEqual:t.notStrictEqual,strictEqual:t.strictEqual},cliui:require("cliui"),findUp:require("escalade/sync"),getEnv:t=>process.env[t],getCallerFile:require("get-caller-file"),getProcessArgvBin:y,inspect:ne,mainFilename:null!==(se=null===(ee=null===require||void 0===require?void 0:require.main)||void 0===ee?void 0:ee.filename)&&void 0!==se?se:process.cwd(),Parser:ae,path:require("path"),process:{argv:()=>process.argv,cwd:process.cwd,emitWarning:(t,e)=>process.emitWarning(t,e),execPath:()=>process.execPath,exit:t=>{process.exit(t)},nextTick:process.nextTick,stdColumns:void 0!==process.stdout.columns?process.stdout.columns:null},readFileSync:ie,require:require,requireDirectory:require("require-directory"),stringWidth:require("string-width"),y18n:oe({directory:re(__dirname,"../locales"),updateFiles:!1})};const ce=(null===(he=null===process||void 0===process?void 0:process.env)||void 0===he?void 0:he.YARGS_MIN_NODE_VERSION)?Number(process.env.YARGS_MIN_NODE_VERSION):12;if(process&&process.version){if(Number(process.version.match(/v([^.]+)/)[1]){const i=new te(t,e,s,de);return Object.defineProperty(i,"argv",{get:()=>i.parse(),enumerable:!0}),i.help(),i.version(),i}),argsert:h,isPromise:f,objFilter:g,parseCommand:o,Parser:fe,processArgv:b,YError:e};module.exports=ue; diff --git a/node_modules/yargs/build/lib/argsert.js b/node_modules/yargs/build/lib/argsert.js new file mode 100644 index 0000000000000000000000000000000000000000..be5b3aa69f30d65946196e1c79621ca9987e5f36 --- /dev/null +++ b/node_modules/yargs/build/lib/argsert.js @@ -0,0 +1,62 @@ +import { YError } from './yerror.js'; +import { parseCommand } from './parse-command.js'; +const positionName = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth']; +export function argsert(arg1, arg2, arg3) { + function parseArgs() { + return typeof arg1 === 'object' + ? [{ demanded: [], optional: [] }, arg1, arg2] + : [ + parseCommand(`cmd ${arg1}`), + arg2, + arg3, + ]; + } + try { + let position = 0; + const [parsed, callerArguments, _length] = parseArgs(); + const args = [].slice.call(callerArguments); + while (args.length && args[args.length - 1] === undefined) + args.pop(); + const length = _length || args.length; + if (length < parsed.demanded.length) { + throw new YError(`Not enough arguments provided. Expected ${parsed.demanded.length} but received ${args.length}.`); + } + const totalCommands = parsed.demanded.length + parsed.optional.length; + if (length > totalCommands) { + throw new YError(`Too many arguments provided. Expected max ${totalCommands} but received ${length}.`); + } + parsed.demanded.forEach(demanded => { + const arg = args.shift(); + const observedType = guessType(arg); + const matchingTypes = demanded.cmd.filter(type => type === observedType || type === '*'); + if (matchingTypes.length === 0) + argumentTypeError(observedType, demanded.cmd, position); + position += 1; + }); + parsed.optional.forEach(optional => { + if (args.length === 0) + return; + const arg = args.shift(); + const observedType = guessType(arg); + const matchingTypes = optional.cmd.filter(type => type === observedType || type === '*'); + if (matchingTypes.length === 0) + argumentTypeError(observedType, optional.cmd, position); + position += 1; + }); + } + catch (err) { + console.warn(err.stack); + } +} +function guessType(arg) { + if (Array.isArray(arg)) { + return 'array'; + } + else if (arg === null) { + return 'null'; + } + return typeof arg; +} +function argumentTypeError(observedType, allowedTypes, position) { + throw new YError(`Invalid ${positionName[position] || 'manyith'} argument. Expected ${allowedTypes.join(' or ')} but received ${observedType}.`); +} diff --git a/node_modules/yargs/build/lib/command.js b/node_modules/yargs/build/lib/command.js new file mode 100644 index 0000000000000000000000000000000000000000..47c1ed63581a0f173e0973c89d8b45671f90d073 --- /dev/null +++ b/node_modules/yargs/build/lib/command.js @@ -0,0 +1,449 @@ +import { assertNotStrictEqual, } from './typings/common-types.js'; +import { isPromise } from './utils/is-promise.js'; +import { applyMiddleware, commandMiddlewareFactory, } from './middleware.js'; +import { parseCommand } from './parse-command.js'; +import { isYargsInstance, } from './yargs-factory.js'; +import { maybeAsyncResult } from './utils/maybe-async-result.js'; +import whichModule from './utils/which-module.js'; +const DEFAULT_MARKER = /(^\*)|(^\$0)/; +export class CommandInstance { + constructor(usage, validation, globalMiddleware, shim) { + this.requireCache = new Set(); + this.handlers = {}; + this.aliasMap = {}; + this.frozens = []; + this.shim = shim; + this.usage = usage; + this.globalMiddleware = globalMiddleware; + this.validation = validation; + } + addDirectory(dir, req, callerFile, opts) { + opts = opts || {}; + if (typeof opts.recurse !== 'boolean') + opts.recurse = false; + if (!Array.isArray(opts.extensions)) + opts.extensions = ['js']; + const parentVisit = typeof opts.visit === 'function' ? opts.visit : (o) => o; + opts.visit = (obj, joined, filename) => { + const visited = parentVisit(obj, joined, filename); + if (visited) { + if (this.requireCache.has(joined)) + return visited; + else + this.requireCache.add(joined); + this.addHandler(visited); + } + return visited; + }; + this.shim.requireDirectory({ require: req, filename: callerFile }, dir, opts); + } + addHandler(cmd, description, builder, handler, commandMiddleware, deprecated) { + let aliases = []; + const middlewares = commandMiddlewareFactory(commandMiddleware); + handler = handler || (() => { }); + if (Array.isArray(cmd)) { + if (isCommandAndAliases(cmd)) { + [cmd, ...aliases] = cmd; + } + else { + for (const command of cmd) { + this.addHandler(command); + } + } + } + else if (isCommandHandlerDefinition(cmd)) { + let command = Array.isArray(cmd.command) || typeof cmd.command === 'string' + ? cmd.command + : this.moduleName(cmd); + if (cmd.aliases) + command = [].concat(command).concat(cmd.aliases); + this.addHandler(command, this.extractDesc(cmd), cmd.builder, cmd.handler, cmd.middlewares, cmd.deprecated); + return; + } + else if (isCommandBuilderDefinition(builder)) { + this.addHandler([cmd].concat(aliases), description, builder.builder, builder.handler, builder.middlewares, builder.deprecated); + return; + } + if (typeof cmd === 'string') { + const parsedCommand = parseCommand(cmd); + aliases = aliases.map(alias => parseCommand(alias).cmd); + let isDefault = false; + const parsedAliases = [parsedCommand.cmd].concat(aliases).filter(c => { + if (DEFAULT_MARKER.test(c)) { + isDefault = true; + return false; + } + return true; + }); + if (parsedAliases.length === 0 && isDefault) + parsedAliases.push('$0'); + if (isDefault) { + parsedCommand.cmd = parsedAliases[0]; + aliases = parsedAliases.slice(1); + cmd = cmd.replace(DEFAULT_MARKER, parsedCommand.cmd); + } + aliases.forEach(alias => { + this.aliasMap[alias] = parsedCommand.cmd; + }); + if (description !== false) { + this.usage.command(cmd, description, isDefault, aliases, deprecated); + } + this.handlers[parsedCommand.cmd] = { + original: cmd, + description, + handler, + builder: builder || {}, + middlewares, + deprecated, + demanded: parsedCommand.demanded, + optional: parsedCommand.optional, + }; + if (isDefault) + this.defaultCommand = this.handlers[parsedCommand.cmd]; + } + } + getCommandHandlers() { + return this.handlers; + } + getCommands() { + return Object.keys(this.handlers).concat(Object.keys(this.aliasMap)); + } + hasDefaultCommand() { + return !!this.defaultCommand; + } + runCommand(command, yargs, parsed, commandIndex, helpOnly, helpOrVersionSet) { + const commandHandler = this.handlers[command] || + this.handlers[this.aliasMap[command]] || + this.defaultCommand; + const currentContext = yargs.getInternalMethods().getContext(); + const parentCommands = currentContext.commands.slice(); + const isDefaultCommand = !command; + if (command) { + currentContext.commands.push(command); + currentContext.fullCommands.push(commandHandler.original); + } + const builderResult = this.applyBuilderUpdateUsageAndParse(isDefaultCommand, commandHandler, yargs, parsed.aliases, parentCommands, commandIndex, helpOnly, helpOrVersionSet); + return isPromise(builderResult) + ? builderResult.then(result => this.applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, result.innerArgv, currentContext, helpOnly, result.aliases, yargs)) + : this.applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, builderResult.innerArgv, currentContext, helpOnly, builderResult.aliases, yargs); + } + applyBuilderUpdateUsageAndParse(isDefaultCommand, commandHandler, yargs, aliases, parentCommands, commandIndex, helpOnly, helpOrVersionSet) { + const builder = commandHandler.builder; + let innerYargs = yargs; + if (isCommandBuilderCallback(builder)) { + yargs.getInternalMethods().getUsageInstance().freeze(); + const builderOutput = builder(yargs.getInternalMethods().reset(aliases), helpOrVersionSet); + if (isPromise(builderOutput)) { + return builderOutput.then(output => { + innerYargs = isYargsInstance(output) ? output : yargs; + return this.parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly); + }); + } + } + else if (isCommandBuilderOptionDefinitions(builder)) { + yargs.getInternalMethods().getUsageInstance().freeze(); + innerYargs = yargs.getInternalMethods().reset(aliases); + Object.keys(commandHandler.builder).forEach(key => { + innerYargs.option(key, builder[key]); + }); + } + return this.parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly); + } + parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly) { + if (isDefaultCommand) + innerYargs.getInternalMethods().getUsageInstance().unfreeze(true); + if (this.shouldUpdateUsage(innerYargs)) { + innerYargs + .getInternalMethods() + .getUsageInstance() + .usage(this.usageFromParentCommandsCommandHandler(parentCommands, commandHandler), commandHandler.description); + } + const innerArgv = innerYargs + .getInternalMethods() + .runYargsParserAndExecuteCommands(null, undefined, true, commandIndex, helpOnly); + return isPromise(innerArgv) + ? innerArgv.then(argv => ({ + aliases: innerYargs.parsed.aliases, + innerArgv: argv, + })) + : { + aliases: innerYargs.parsed.aliases, + innerArgv: innerArgv, + }; + } + shouldUpdateUsage(yargs) { + return (!yargs.getInternalMethods().getUsageInstance().getUsageDisabled() && + yargs.getInternalMethods().getUsageInstance().getUsage().length === 0); + } + usageFromParentCommandsCommandHandler(parentCommands, commandHandler) { + const c = DEFAULT_MARKER.test(commandHandler.original) + ? commandHandler.original.replace(DEFAULT_MARKER, '').trim() + : commandHandler.original; + const pc = parentCommands.filter(c => { + return !DEFAULT_MARKER.test(c); + }); + pc.push(c); + return `$0 ${pc.join(' ')}`; + } + handleValidationAndGetResult(isDefaultCommand, commandHandler, innerArgv, currentContext, aliases, yargs, middlewares, positionalMap) { + if (!yargs.getInternalMethods().getHasOutput()) { + const validation = yargs + .getInternalMethods() + .runValidation(aliases, positionalMap, yargs.parsed.error, isDefaultCommand); + innerArgv = maybeAsyncResult(innerArgv, result => { + validation(result); + return result; + }); + } + if (commandHandler.handler && !yargs.getInternalMethods().getHasOutput()) { + yargs.getInternalMethods().setHasOutput(); + const populateDoubleDash = !!yargs.getOptions().configuration['populate--']; + yargs + .getInternalMethods() + .postProcess(innerArgv, populateDoubleDash, false, false); + innerArgv = applyMiddleware(innerArgv, yargs, middlewares, false); + innerArgv = maybeAsyncResult(innerArgv, result => { + const handlerResult = commandHandler.handler(result); + return isPromise(handlerResult) + ? handlerResult.then(() => result) + : result; + }); + if (!isDefaultCommand) { + yargs.getInternalMethods().getUsageInstance().cacheHelpMessage(); + } + if (isPromise(innerArgv) && + !yargs.getInternalMethods().hasParseCallback()) { + innerArgv.catch(error => { + try { + yargs.getInternalMethods().getUsageInstance().fail(null, error); + } + catch (_err) { + } + }); + } + } + if (!isDefaultCommand) { + currentContext.commands.pop(); + currentContext.fullCommands.pop(); + } + return innerArgv; + } + applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, innerArgv, currentContext, helpOnly, aliases, yargs) { + let positionalMap = {}; + if (helpOnly) + return innerArgv; + if (!yargs.getInternalMethods().getHasOutput()) { + positionalMap = this.populatePositionals(commandHandler, innerArgv, currentContext, yargs); + } + const middlewares = this.globalMiddleware + .getMiddleware() + .slice(0) + .concat(commandHandler.middlewares); + const maybePromiseArgv = applyMiddleware(innerArgv, yargs, middlewares, true); + return isPromise(maybePromiseArgv) + ? maybePromiseArgv.then(resolvedInnerArgv => this.handleValidationAndGetResult(isDefaultCommand, commandHandler, resolvedInnerArgv, currentContext, aliases, yargs, middlewares, positionalMap)) + : this.handleValidationAndGetResult(isDefaultCommand, commandHandler, maybePromiseArgv, currentContext, aliases, yargs, middlewares, positionalMap); + } + populatePositionals(commandHandler, argv, context, yargs) { + argv._ = argv._.slice(context.commands.length); + const demanded = commandHandler.demanded.slice(0); + const optional = commandHandler.optional.slice(0); + const positionalMap = {}; + this.validation.positionalCount(demanded.length, argv._.length); + while (demanded.length) { + const demand = demanded.shift(); + this.populatePositional(demand, argv, positionalMap); + } + while (optional.length) { + const maybe = optional.shift(); + this.populatePositional(maybe, argv, positionalMap); + } + argv._ = context.commands.concat(argv._.map(a => '' + a)); + this.postProcessPositionals(argv, positionalMap, this.cmdToParseOptions(commandHandler.original), yargs); + return positionalMap; + } + populatePositional(positional, argv, positionalMap) { + const cmd = positional.cmd[0]; + if (positional.variadic) { + positionalMap[cmd] = argv._.splice(0).map(String); + } + else { + if (argv._.length) + positionalMap[cmd] = [String(argv._.shift())]; + } + } + cmdToParseOptions(cmdString) { + const parseOptions = { + array: [], + default: {}, + alias: {}, + demand: {}, + }; + const parsed = parseCommand(cmdString); + parsed.demanded.forEach(d => { + const [cmd, ...aliases] = d.cmd; + if (d.variadic) { + parseOptions.array.push(cmd); + parseOptions.default[cmd] = []; + } + parseOptions.alias[cmd] = aliases; + parseOptions.demand[cmd] = true; + }); + parsed.optional.forEach(o => { + const [cmd, ...aliases] = o.cmd; + if (o.variadic) { + parseOptions.array.push(cmd); + parseOptions.default[cmd] = []; + } + parseOptions.alias[cmd] = aliases; + }); + return parseOptions; + } + postProcessPositionals(argv, positionalMap, parseOptions, yargs) { + const options = Object.assign({}, yargs.getOptions()); + options.default = Object.assign(parseOptions.default, options.default); + for (const key of Object.keys(parseOptions.alias)) { + options.alias[key] = (options.alias[key] || []).concat(parseOptions.alias[key]); + } + options.array = options.array.concat(parseOptions.array); + options.config = {}; + const unparsed = []; + Object.keys(positionalMap).forEach(key => { + positionalMap[key].map(value => { + if (options.configuration['unknown-options-as-args']) + options.key[key] = true; + unparsed.push(`--${key}`); + unparsed.push(value); + }); + }); + if (!unparsed.length) + return; + const config = Object.assign({}, options.configuration, { + 'populate--': false, + }); + const parsed = this.shim.Parser.detailed(unparsed, Object.assign({}, options, { + configuration: config, + })); + if (parsed.error) { + yargs + .getInternalMethods() + .getUsageInstance() + .fail(parsed.error.message, parsed.error); + } + else { + const positionalKeys = Object.keys(positionalMap); + Object.keys(positionalMap).forEach(key => { + positionalKeys.push(...parsed.aliases[key]); + }); + Object.keys(parsed.argv).forEach(key => { + if (positionalKeys.includes(key)) { + if (!positionalMap[key]) + positionalMap[key] = parsed.argv[key]; + if (!this.isInConfigs(yargs, key) && + !this.isDefaulted(yargs, key) && + Object.prototype.hasOwnProperty.call(argv, key) && + Object.prototype.hasOwnProperty.call(parsed.argv, key) && + (Array.isArray(argv[key]) || Array.isArray(parsed.argv[key]))) { + argv[key] = [].concat(argv[key], parsed.argv[key]); + } + else { + argv[key] = parsed.argv[key]; + } + } + }); + } + } + isDefaulted(yargs, key) { + const { default: defaults } = yargs.getOptions(); + return (Object.prototype.hasOwnProperty.call(defaults, key) || + Object.prototype.hasOwnProperty.call(defaults, this.shim.Parser.camelCase(key))); + } + isInConfigs(yargs, key) { + const { configObjects } = yargs.getOptions(); + return (configObjects.some(c => Object.prototype.hasOwnProperty.call(c, key)) || + configObjects.some(c => Object.prototype.hasOwnProperty.call(c, this.shim.Parser.camelCase(key)))); + } + runDefaultBuilderOn(yargs) { + if (!this.defaultCommand) + return; + if (this.shouldUpdateUsage(yargs)) { + const commandString = DEFAULT_MARKER.test(this.defaultCommand.original) + ? this.defaultCommand.original + : this.defaultCommand.original.replace(/^[^[\]<>]*/, '$0 '); + yargs + .getInternalMethods() + .getUsageInstance() + .usage(commandString, this.defaultCommand.description); + } + const builder = this.defaultCommand.builder; + if (isCommandBuilderCallback(builder)) { + return builder(yargs, true); + } + else if (!isCommandBuilderDefinition(builder)) { + Object.keys(builder).forEach(key => { + yargs.option(key, builder[key]); + }); + } + return undefined; + } + moduleName(obj) { + const mod = whichModule(obj); + if (!mod) + throw new Error(`No command name given for module: ${this.shim.inspect(obj)}`); + return this.commandFromFilename(mod.filename); + } + commandFromFilename(filename) { + return this.shim.path.basename(filename, this.shim.path.extname(filename)); + } + extractDesc({ describe, description, desc }) { + for (const test of [describe, description, desc]) { + if (typeof test === 'string' || test === false) + return test; + assertNotStrictEqual(test, true, this.shim); + } + return false; + } + freeze() { + this.frozens.push({ + handlers: this.handlers, + aliasMap: this.aliasMap, + defaultCommand: this.defaultCommand, + }); + } + unfreeze() { + const frozen = this.frozens.pop(); + assertNotStrictEqual(frozen, undefined, this.shim); + ({ + handlers: this.handlers, + aliasMap: this.aliasMap, + defaultCommand: this.defaultCommand, + } = frozen); + } + reset() { + this.handlers = {}; + this.aliasMap = {}; + this.defaultCommand = undefined; + this.requireCache = new Set(); + return this; + } +} +export function command(usage, validation, globalMiddleware, shim) { + return new CommandInstance(usage, validation, globalMiddleware, shim); +} +export function isCommandBuilderDefinition(builder) { + return (typeof builder === 'object' && + !!builder.builder && + typeof builder.handler === 'function'); +} +function isCommandAndAliases(cmd) { + return cmd.every(c => typeof c === 'string'); +} +export function isCommandBuilderCallback(builder) { + return typeof builder === 'function'; +} +function isCommandBuilderOptionDefinitions(builder) { + return typeof builder === 'object'; +} +export function isCommandHandlerDefinition(cmd) { + return typeof cmd === 'object' && !Array.isArray(cmd); +} diff --git a/node_modules/yargs/build/lib/completion-templates.js b/node_modules/yargs/build/lib/completion-templates.js new file mode 100644 index 0000000000000000000000000000000000000000..2c4dcb580d2c8800241395ed62854f348586ec91 --- /dev/null +++ b/node_modules/yargs/build/lib/completion-templates.js @@ -0,0 +1,48 @@ +export const completionShTemplate = `###-begin-{{app_name}}-completions-### +# +# yargs command completion script +# +# Installation: {{app_path}} {{completion_command}} >> ~/.bashrc +# or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX. +# +_{{app_name}}_yargs_completions() +{ + local cur_word args type_list + + cur_word="\${COMP_WORDS[COMP_CWORD]}" + args=("\${COMP_WORDS[@]}") + + # ask yargs to generate completions. + type_list=$({{app_path}} --get-yargs-completions "\${args[@]}") + + COMPREPLY=( $(compgen -W "\${type_list}" -- \${cur_word}) ) + + # if no match was found, fall back to filename completion + if [ \${#COMPREPLY[@]} -eq 0 ]; then + COMPREPLY=() + fi + + return 0 +} +complete -o bashdefault -o default -F _{{app_name}}_yargs_completions {{app_name}} +###-end-{{app_name}}-completions-### +`; +export const completionZshTemplate = `#compdef {{app_name}} +###-begin-{{app_name}}-completions-### +# +# yargs command completion script +# +# Installation: {{app_path}} {{completion_command}} >> ~/.zshrc +# or {{app_path}} {{completion_command}} >> ~/.zprofile on OSX. +# +_{{app_name}}_yargs_completions() +{ + local reply + local si=$IFS + IFS=$'\n' reply=($(COMP_CWORD="$((CURRENT-1))" COMP_LINE="$BUFFER" COMP_POINT="$CURSOR" {{app_path}} --get-yargs-completions "\${words[@]}")) + IFS=$si + _describe 'values' reply +} +compdef _{{app_name}}_yargs_completions {{app_name}} +###-end-{{app_name}}-completions-### +`; diff --git a/node_modules/yargs/build/lib/completion.js b/node_modules/yargs/build/lib/completion.js new file mode 100644 index 0000000000000000000000000000000000000000..cef2bbe0890aa083348a2e9a55d7e4bb6b7ee672 --- /dev/null +++ b/node_modules/yargs/build/lib/completion.js @@ -0,0 +1,243 @@ +import { isCommandBuilderCallback } from './command.js'; +import { assertNotStrictEqual } from './typings/common-types.js'; +import * as templates from './completion-templates.js'; +import { isPromise } from './utils/is-promise.js'; +import { parseCommand } from './parse-command.js'; +export class Completion { + constructor(yargs, usage, command, shim) { + var _a, _b, _c; + this.yargs = yargs; + this.usage = usage; + this.command = command; + this.shim = shim; + this.completionKey = 'get-yargs-completions'; + this.aliases = null; + this.customCompletionFunction = null; + this.indexAfterLastReset = 0; + this.zshShell = + (_c = (((_a = this.shim.getEnv('SHELL')) === null || _a === void 0 ? void 0 : _a.includes('zsh')) || + ((_b = this.shim.getEnv('ZSH_NAME')) === null || _b === void 0 ? void 0 : _b.includes('zsh')))) !== null && _c !== void 0 ? _c : false; + } + defaultCompletion(args, argv, current, done) { + const handlers = this.command.getCommandHandlers(); + for (let i = 0, ii = args.length; i < ii; ++i) { + if (handlers[args[i]] && handlers[args[i]].builder) { + const builder = handlers[args[i]].builder; + if (isCommandBuilderCallback(builder)) { + this.indexAfterLastReset = i + 1; + const y = this.yargs.getInternalMethods().reset(); + builder(y, true); + return y.argv; + } + } + } + const completions = []; + this.commandCompletions(completions, args, current); + this.optionCompletions(completions, args, argv, current); + this.choicesFromOptionsCompletions(completions, args, argv, current); + this.choicesFromPositionalsCompletions(completions, args, argv, current); + done(null, completions); + } + commandCompletions(completions, args, current) { + const parentCommands = this.yargs + .getInternalMethods() + .getContext().commands; + if (!current.match(/^-/) && + parentCommands[parentCommands.length - 1] !== current && + !this.previousArgHasChoices(args)) { + this.usage.getCommands().forEach(usageCommand => { + const commandName = parseCommand(usageCommand[0]).cmd; + if (args.indexOf(commandName) === -1) { + if (!this.zshShell) { + completions.push(commandName); + } + else { + const desc = usageCommand[1] || ''; + completions.push(commandName.replace(/:/g, '\\:') + ':' + desc); + } + } + }); + } + } + optionCompletions(completions, args, argv, current) { + if ((current.match(/^-/) || (current === '' && completions.length === 0)) && + !this.previousArgHasChoices(args)) { + const options = this.yargs.getOptions(); + const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || []; + Object.keys(options.key).forEach(key => { + const negable = !!options.configuration['boolean-negation'] && + options.boolean.includes(key); + const isPositionalKey = positionalKeys.includes(key); + if (!isPositionalKey && + !options.hiddenOptions.includes(key) && + !this.argsContainKey(args, key, negable)) { + this.completeOptionKey(key, completions, current, negable && !!options.default[key]); + } + }); + } + } + choicesFromOptionsCompletions(completions, args, argv, current) { + if (this.previousArgHasChoices(args)) { + const choices = this.getPreviousArgChoices(args); + if (choices && choices.length > 0) { + completions.push(...choices.map(c => c.replace(/:/g, '\\:'))); + } + } + } + choicesFromPositionalsCompletions(completions, args, argv, current) { + if (current === '' && + completions.length > 0 && + this.previousArgHasChoices(args)) { + return; + } + const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || []; + const offset = Math.max(this.indexAfterLastReset, this.yargs.getInternalMethods().getContext().commands.length + + 1); + const positionalKey = positionalKeys[argv._.length - offset - 1]; + if (!positionalKey) { + return; + } + const choices = this.yargs.getOptions().choices[positionalKey] || []; + for (const choice of choices) { + if (choice.startsWith(current)) { + completions.push(choice.replace(/:/g, '\\:')); + } + } + } + getPreviousArgChoices(args) { + if (args.length < 1) + return; + let previousArg = args[args.length - 1]; + let filter = ''; + if (!previousArg.startsWith('-') && args.length > 1) { + filter = previousArg; + previousArg = args[args.length - 2]; + } + if (!previousArg.startsWith('-')) + return; + const previousArgKey = previousArg.replace(/^-+/, ''); + const options = this.yargs.getOptions(); + const possibleAliases = [ + previousArgKey, + ...(this.yargs.getAliases()[previousArgKey] || []), + ]; + let choices; + for (const possibleAlias of possibleAliases) { + if (Object.prototype.hasOwnProperty.call(options.key, possibleAlias) && + Array.isArray(options.choices[possibleAlias])) { + choices = options.choices[possibleAlias]; + break; + } + } + if (choices) { + return choices.filter(choice => !filter || choice.startsWith(filter)); + } + } + previousArgHasChoices(args) { + const choices = this.getPreviousArgChoices(args); + return choices !== undefined && choices.length > 0; + } + argsContainKey(args, key, negable) { + const argsContains = (s) => args.indexOf((/^[^0-9]$/.test(s) ? '-' : '--') + s) !== -1; + if (argsContains(key)) + return true; + if (negable && argsContains(`no-${key}`)) + return true; + if (this.aliases) { + for (const alias of this.aliases[key]) { + if (argsContains(alias)) + return true; + } + } + return false; + } + completeOptionKey(key, completions, current, negable) { + var _a, _b, _c, _d; + let keyWithDesc = key; + if (this.zshShell) { + const descs = this.usage.getDescriptions(); + const aliasKey = (_b = (_a = this === null || this === void 0 ? void 0 : this.aliases) === null || _a === void 0 ? void 0 : _a[key]) === null || _b === void 0 ? void 0 : _b.find(alias => { + const desc = descs[alias]; + return typeof desc === 'string' && desc.length > 0; + }); + const descFromAlias = aliasKey ? descs[aliasKey] : undefined; + const desc = (_d = (_c = descs[key]) !== null && _c !== void 0 ? _c : descFromAlias) !== null && _d !== void 0 ? _d : ''; + keyWithDesc = `${key.replace(/:/g, '\\:')}:${desc + .replace('__yargsString__:', '') + .replace(/(\r\n|\n|\r)/gm, ' ')}`; + } + const startsByTwoDashes = (s) => /^--/.test(s); + const isShortOption = (s) => /^[^0-9]$/.test(s); + const dashes = !startsByTwoDashes(current) && isShortOption(key) ? '-' : '--'; + completions.push(dashes + keyWithDesc); + if (negable) { + completions.push(dashes + 'no-' + keyWithDesc); + } + } + customCompletion(args, argv, current, done) { + assertNotStrictEqual(this.customCompletionFunction, null, this.shim); + if (isSyncCompletionFunction(this.customCompletionFunction)) { + const result = this.customCompletionFunction(current, argv); + if (isPromise(result)) { + return result + .then(list => { + this.shim.process.nextTick(() => { + done(null, list); + }); + }) + .catch(err => { + this.shim.process.nextTick(() => { + done(err, undefined); + }); + }); + } + return done(null, result); + } + else if (isFallbackCompletionFunction(this.customCompletionFunction)) { + return this.customCompletionFunction(current, argv, (onCompleted = done) => this.defaultCompletion(args, argv, current, onCompleted), completions => { + done(null, completions); + }); + } + else { + return this.customCompletionFunction(current, argv, completions => { + done(null, completions); + }); + } + } + getCompletion(args, done) { + const current = args.length ? args[args.length - 1] : ''; + const argv = this.yargs.parse(args, true); + const completionFunction = this.customCompletionFunction + ? (argv) => this.customCompletion(args, argv, current, done) + : (argv) => this.defaultCompletion(args, argv, current, done); + return isPromise(argv) + ? argv.then(completionFunction) + : completionFunction(argv); + } + generateCompletionScript($0, cmd) { + let script = this.zshShell + ? templates.completionZshTemplate + : templates.completionShTemplate; + const name = this.shim.path.basename($0); + if ($0.match(/\.js$/)) + $0 = `./${$0}`; + script = script.replace(/{{app_name}}/g, name); + script = script.replace(/{{completion_command}}/g, cmd); + return script.replace(/{{app_path}}/g, $0); + } + registerFunction(fn) { + this.customCompletionFunction = fn; + } + setParsed(parsed) { + this.aliases = parsed.aliases; + } +} +export function completion(yargs, usage, command, shim) { + return new Completion(yargs, usage, command, shim); +} +function isSyncCompletionFunction(completionFunction) { + return completionFunction.length < 3; +} +function isFallbackCompletionFunction(completionFunction) { + return completionFunction.length > 3; +} diff --git a/node_modules/yargs/build/lib/middleware.js b/node_modules/yargs/build/lib/middleware.js new file mode 100644 index 0000000000000000000000000000000000000000..4e561a79f8614dc18dc8df156ddaba7e996cfedc --- /dev/null +++ b/node_modules/yargs/build/lib/middleware.js @@ -0,0 +1,88 @@ +import { argsert } from './argsert.js'; +import { isPromise } from './utils/is-promise.js'; +export class GlobalMiddleware { + constructor(yargs) { + this.globalMiddleware = []; + this.frozens = []; + this.yargs = yargs; + } + addMiddleware(callback, applyBeforeValidation, global = true, mutates = false) { + argsert(' [boolean] [boolean] [boolean]', [callback, applyBeforeValidation, global], arguments.length); + if (Array.isArray(callback)) { + for (let i = 0; i < callback.length; i++) { + if (typeof callback[i] !== 'function') { + throw Error('middleware must be a function'); + } + const m = callback[i]; + m.applyBeforeValidation = applyBeforeValidation; + m.global = global; + } + Array.prototype.push.apply(this.globalMiddleware, callback); + } + else if (typeof callback === 'function') { + const m = callback; + m.applyBeforeValidation = applyBeforeValidation; + m.global = global; + m.mutates = mutates; + this.globalMiddleware.push(callback); + } + return this.yargs; + } + addCoerceMiddleware(callback, option) { + const aliases = this.yargs.getAliases(); + this.globalMiddleware = this.globalMiddleware.filter(m => { + const toCheck = [...(aliases[option] || []), option]; + if (!m.option) + return true; + else + return !toCheck.includes(m.option); + }); + callback.option = option; + return this.addMiddleware(callback, true, true, true); + } + getMiddleware() { + return this.globalMiddleware; + } + freeze() { + this.frozens.push([...this.globalMiddleware]); + } + unfreeze() { + const frozen = this.frozens.pop(); + if (frozen !== undefined) + this.globalMiddleware = frozen; + } + reset() { + this.globalMiddleware = this.globalMiddleware.filter(m => m.global); + } +} +export function commandMiddlewareFactory(commandMiddleware) { + if (!commandMiddleware) + return []; + return commandMiddleware.map(middleware => { + middleware.applyBeforeValidation = false; + return middleware; + }); +} +export function applyMiddleware(argv, yargs, middlewares, beforeValidation) { + return middlewares.reduce((acc, middleware) => { + if (middleware.applyBeforeValidation !== beforeValidation) { + return acc; + } + if (middleware.mutates) { + if (middleware.applied) + return acc; + middleware.applied = true; + } + if (isPromise(acc)) { + return acc + .then(initialObj => Promise.all([initialObj, middleware(initialObj, yargs)])) + .then(([initialObj, middlewareObj]) => Object.assign(initialObj, middlewareObj)); + } + else { + const result = middleware(acc, yargs); + return isPromise(result) + ? result.then(middlewareObj => Object.assign(acc, middlewareObj)) + : Object.assign(acc, result); + } + }, argv); +} diff --git a/node_modules/yargs/build/lib/parse-command.js b/node_modules/yargs/build/lib/parse-command.js new file mode 100644 index 0000000000000000000000000000000000000000..4989f53102bff7466b12475db98047852d02eabc --- /dev/null +++ b/node_modules/yargs/build/lib/parse-command.js @@ -0,0 +1,32 @@ +export function parseCommand(cmd) { + const extraSpacesStrippedCommand = cmd.replace(/\s{2,}/g, ' '); + const splitCommand = extraSpacesStrippedCommand.split(/\s+(?![^[]*]|[^<]*>)/); + const bregex = /\.*[\][<>]/g; + const firstCommand = splitCommand.shift(); + if (!firstCommand) + throw new Error(`No command found in: ${cmd}`); + const parsedCommand = { + cmd: firstCommand.replace(bregex, ''), + demanded: [], + optional: [], + }; + splitCommand.forEach((cmd, i) => { + let variadic = false; + cmd = cmd.replace(/\s/g, ''); + if (/\.+[\]>]/.test(cmd) && i === splitCommand.length - 1) + variadic = true; + if (/^\[/.test(cmd)) { + parsedCommand.optional.push({ + cmd: cmd.replace(bregex, '').split('|'), + variadic, + }); + } + else { + parsedCommand.demanded.push({ + cmd: cmd.replace(bregex, '').split('|'), + variadic, + }); + } + }); + return parsedCommand; +} diff --git a/node_modules/yargs/build/lib/typings/common-types.js b/node_modules/yargs/build/lib/typings/common-types.js new file mode 100644 index 0000000000000000000000000000000000000000..73e1773a26a670272d0c3a9fabff2717b553fdbe --- /dev/null +++ b/node_modules/yargs/build/lib/typings/common-types.js @@ -0,0 +1,9 @@ +export function assertNotStrictEqual(actual, expected, shim, message) { + shim.assert.notStrictEqual(actual, expected, message); +} +export function assertSingleKey(actual, shim) { + shim.assert.strictEqual(typeof actual, 'string'); +} +export function objectKeys(object) { + return Object.keys(object); +} diff --git a/node_modules/yargs/build/lib/typings/yargs-parser-types.js b/node_modules/yargs/build/lib/typings/yargs-parser-types.js new file mode 100644 index 0000000000000000000000000000000000000000..cb0ff5c3b541f646105198ee23ac0fc3d805023e --- /dev/null +++ b/node_modules/yargs/build/lib/typings/yargs-parser-types.js @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/yargs/build/lib/usage.js b/node_modules/yargs/build/lib/usage.js new file mode 100644 index 0000000000000000000000000000000000000000..0127c130d504fc0ac43adf40369f452c6c4782c7 --- /dev/null +++ b/node_modules/yargs/build/lib/usage.js @@ -0,0 +1,584 @@ +import { objFilter } from './utils/obj-filter.js'; +import { YError } from './yerror.js'; +import setBlocking from './utils/set-blocking.js'; +function isBoolean(fail) { + return typeof fail === 'boolean'; +} +export function usage(yargs, shim) { + const __ = shim.y18n.__; + const self = {}; + const fails = []; + self.failFn = function failFn(f) { + fails.push(f); + }; + let failMessage = null; + let globalFailMessage = null; + let showHelpOnFail = true; + self.showHelpOnFail = function showHelpOnFailFn(arg1 = true, arg2) { + const [enabled, message] = typeof arg1 === 'string' ? [true, arg1] : [arg1, arg2]; + if (yargs.getInternalMethods().isGlobalContext()) { + globalFailMessage = message; + } + failMessage = message; + showHelpOnFail = enabled; + return self; + }; + let failureOutput = false; + self.fail = function fail(msg, err) { + const logger = yargs.getInternalMethods().getLoggerInstance(); + if (fails.length) { + for (let i = fails.length - 1; i >= 0; --i) { + const fail = fails[i]; + if (isBoolean(fail)) { + if (err) + throw err; + else if (msg) + throw Error(msg); + } + else { + fail(msg, err, self); + } + } + } + else { + if (yargs.getExitProcess()) + setBlocking(true); + if (!failureOutput) { + failureOutput = true; + if (showHelpOnFail) { + yargs.showHelp('error'); + logger.error(); + } + if (msg || err) + logger.error(msg || err); + const globalOrCommandFailMessage = failMessage || globalFailMessage; + if (globalOrCommandFailMessage) { + if (msg || err) + logger.error(''); + logger.error(globalOrCommandFailMessage); + } + } + err = err || new YError(msg); + if (yargs.getExitProcess()) { + return yargs.exit(1); + } + else if (yargs.getInternalMethods().hasParseCallback()) { + return yargs.exit(1, err); + } + else { + throw err; + } + } + }; + let usages = []; + let usageDisabled = false; + self.usage = (msg, description) => { + if (msg === null) { + usageDisabled = true; + usages = []; + return self; + } + usageDisabled = false; + usages.push([msg, description || '']); + return self; + }; + self.getUsage = () => { + return usages; + }; + self.getUsageDisabled = () => { + return usageDisabled; + }; + self.getPositionalGroupName = () => { + return __('Positionals:'); + }; + let examples = []; + self.example = (cmd, description) => { + examples.push([cmd, description || '']); + }; + let commands = []; + self.command = function command(cmd, description, isDefault, aliases, deprecated = false) { + if (isDefault) { + commands = commands.map(cmdArray => { + cmdArray[2] = false; + return cmdArray; + }); + } + commands.push([cmd, description || '', isDefault, aliases, deprecated]); + }; + self.getCommands = () => commands; + let descriptions = {}; + self.describe = function describe(keyOrKeys, desc) { + if (Array.isArray(keyOrKeys)) { + keyOrKeys.forEach(k => { + self.describe(k, desc); + }); + } + else if (typeof keyOrKeys === 'object') { + Object.keys(keyOrKeys).forEach(k => { + self.describe(k, keyOrKeys[k]); + }); + } + else { + descriptions[keyOrKeys] = desc; + } + }; + self.getDescriptions = () => descriptions; + let epilogs = []; + self.epilog = msg => { + epilogs.push(msg); + }; + let wrapSet = false; + let wrap; + self.wrap = cols => { + wrapSet = true; + wrap = cols; + }; + self.getWrap = () => { + if (shim.getEnv('YARGS_DISABLE_WRAP')) { + return null; + } + if (!wrapSet) { + wrap = windowWidth(); + wrapSet = true; + } + return wrap; + }; + const deferY18nLookupPrefix = '__yargsString__:'; + self.deferY18nLookup = str => deferY18nLookupPrefix + str; + self.help = function help() { + if (cachedHelpMessage) + return cachedHelpMessage; + normalizeAliases(); + const base$0 = yargs.customScriptName + ? yargs.$0 + : shim.path.basename(yargs.$0); + const demandedOptions = yargs.getDemandedOptions(); + const demandedCommands = yargs.getDemandedCommands(); + const deprecatedOptions = yargs.getDeprecatedOptions(); + const groups = yargs.getGroups(); + const options = yargs.getOptions(); + let keys = []; + keys = keys.concat(Object.keys(descriptions)); + keys = keys.concat(Object.keys(demandedOptions)); + keys = keys.concat(Object.keys(demandedCommands)); + keys = keys.concat(Object.keys(options.default)); + keys = keys.filter(filterHiddenOptions); + keys = Object.keys(keys.reduce((acc, key) => { + if (key !== '_') + acc[key] = true; + return acc; + }, {})); + const theWrap = self.getWrap(); + const ui = shim.cliui({ + width: theWrap, + wrap: !!theWrap, + }); + if (!usageDisabled) { + if (usages.length) { + usages.forEach(usage => { + ui.div({ text: `${usage[0].replace(/\$0/g, base$0)}` }); + if (usage[1]) { + ui.div({ text: `${usage[1]}`, padding: [1, 0, 0, 0] }); + } + }); + ui.div(); + } + else if (commands.length) { + let u = null; + if (demandedCommands._) { + u = `${base$0} <${__('command')}>\n`; + } + else { + u = `${base$0} [${__('command')}]\n`; + } + ui.div(`${u}`); + } + } + if (commands.length > 1 || (commands.length === 1 && !commands[0][2])) { + ui.div(__('Commands:')); + const context = yargs.getInternalMethods().getContext(); + const parentCommands = context.commands.length + ? `${context.commands.join(' ')} ` + : ''; + if (yargs.getInternalMethods().getParserConfiguration()['sort-commands'] === + true) { + commands = commands.sort((a, b) => a[0].localeCompare(b[0])); + } + const prefix = base$0 ? `${base$0} ` : ''; + commands.forEach(command => { + const commandString = `${prefix}${parentCommands}${command[0].replace(/^\$0 ?/, '')}`; + ui.span({ + text: commandString, + padding: [0, 2, 0, 2], + width: maxWidth(commands, theWrap, `${base$0}${parentCommands}`) + 4, + }, { text: command[1] }); + const hints = []; + if (command[2]) + hints.push(`[${__('default')}]`); + if (command[3] && command[3].length) { + hints.push(`[${__('aliases:')} ${command[3].join(', ')}]`); + } + if (command[4]) { + if (typeof command[4] === 'string') { + hints.push(`[${__('deprecated: %s', command[4])}]`); + } + else { + hints.push(`[${__('deprecated')}]`); + } + } + if (hints.length) { + ui.div({ + text: hints.join(' '), + padding: [0, 0, 0, 2], + align: 'right', + }); + } + else { + ui.div(); + } + }); + ui.div(); + } + const aliasKeys = (Object.keys(options.alias) || []).concat(Object.keys(yargs.parsed.newAliases) || []); + keys = keys.filter(key => !yargs.parsed.newAliases[key] && + aliasKeys.every(alias => (options.alias[alias] || []).indexOf(key) === -1)); + const defaultGroup = __('Options:'); + if (!groups[defaultGroup]) + groups[defaultGroup] = []; + addUngroupedKeys(keys, options.alias, groups, defaultGroup); + const isLongSwitch = (sw) => /^--/.test(getText(sw)); + const displayedGroups = Object.keys(groups) + .filter(groupName => groups[groupName].length > 0) + .map(groupName => { + const normalizedKeys = groups[groupName] + .filter(filterHiddenOptions) + .map(key => { + if (aliasKeys.includes(key)) + return key; + for (let i = 0, aliasKey; (aliasKey = aliasKeys[i]) !== undefined; i++) { + if ((options.alias[aliasKey] || []).includes(key)) + return aliasKey; + } + return key; + }); + return { groupName, normalizedKeys }; + }) + .filter(({ normalizedKeys }) => normalizedKeys.length > 0) + .map(({ groupName, normalizedKeys }) => { + const switches = normalizedKeys.reduce((acc, key) => { + acc[key] = [key] + .concat(options.alias[key] || []) + .map(sw => { + if (groupName === self.getPositionalGroupName()) + return sw; + else { + return ((/^[0-9]$/.test(sw) + ? options.boolean.includes(key) + ? '-' + : '--' + : sw.length > 1 + ? '--' + : '-') + sw); + } + }) + .sort((sw1, sw2) => isLongSwitch(sw1) === isLongSwitch(sw2) + ? 0 + : isLongSwitch(sw1) + ? 1 + : -1) + .join(', '); + return acc; + }, {}); + return { groupName, normalizedKeys, switches }; + }); + const shortSwitchesUsed = displayedGroups + .filter(({ groupName }) => groupName !== self.getPositionalGroupName()) + .some(({ normalizedKeys, switches }) => !normalizedKeys.every(key => isLongSwitch(switches[key]))); + if (shortSwitchesUsed) { + displayedGroups + .filter(({ groupName }) => groupName !== self.getPositionalGroupName()) + .forEach(({ normalizedKeys, switches }) => { + normalizedKeys.forEach(key => { + if (isLongSwitch(switches[key])) { + switches[key] = addIndentation(switches[key], '-x, '.length); + } + }); + }); + } + displayedGroups.forEach(({ groupName, normalizedKeys, switches }) => { + ui.div(groupName); + normalizedKeys.forEach(key => { + const kswitch = switches[key]; + let desc = descriptions[key] || ''; + let type = null; + if (desc.includes(deferY18nLookupPrefix)) + desc = __(desc.substring(deferY18nLookupPrefix.length)); + if (options.boolean.includes(key)) + type = `[${__('boolean')}]`; + if (options.count.includes(key)) + type = `[${__('count')}]`; + if (options.string.includes(key)) + type = `[${__('string')}]`; + if (options.normalize.includes(key)) + type = `[${__('string')}]`; + if (options.array.includes(key)) + type = `[${__('array')}]`; + if (options.number.includes(key)) + type = `[${__('number')}]`; + const deprecatedExtra = (deprecated) => typeof deprecated === 'string' + ? `[${__('deprecated: %s', deprecated)}]` + : `[${__('deprecated')}]`; + const extra = [ + key in deprecatedOptions + ? deprecatedExtra(deprecatedOptions[key]) + : null, + type, + key in demandedOptions ? `[${__('required')}]` : null, + options.choices && options.choices[key] + ? `[${__('choices:')} ${self.stringifiedValues(options.choices[key])}]` + : null, + defaultString(options.default[key], options.defaultDescription[key]), + ] + .filter(Boolean) + .join(' '); + ui.span({ + text: getText(kswitch), + padding: [0, 2, 0, 2 + getIndentation(kswitch)], + width: maxWidth(switches, theWrap) + 4, + }, desc); + const shouldHideOptionExtras = yargs.getInternalMethods().getUsageConfiguration()['hide-types'] === + true; + if (extra && !shouldHideOptionExtras) + ui.div({ text: extra, padding: [0, 0, 0, 2], align: 'right' }); + else + ui.div(); + }); + ui.div(); + }); + if (examples.length) { + ui.div(__('Examples:')); + examples.forEach(example => { + example[0] = example[0].replace(/\$0/g, base$0); + }); + examples.forEach(example => { + if (example[1] === '') { + ui.div({ + text: example[0], + padding: [0, 2, 0, 2], + }); + } + else { + ui.div({ + text: example[0], + padding: [0, 2, 0, 2], + width: maxWidth(examples, theWrap) + 4, + }, { + text: example[1], + }); + } + }); + ui.div(); + } + if (epilogs.length > 0) { + const e = epilogs + .map(epilog => epilog.replace(/\$0/g, base$0)) + .join('\n'); + ui.div(`${e}\n`); + } + return ui.toString().replace(/\s*$/, ''); + }; + function maxWidth(table, theWrap, modifier) { + let width = 0; + if (!Array.isArray(table)) { + table = Object.values(table).map(v => [v]); + } + table.forEach(v => { + width = Math.max(shim.stringWidth(modifier ? `${modifier} ${getText(v[0])}` : getText(v[0])) + getIndentation(v[0]), width); + }); + if (theWrap) + width = Math.min(width, parseInt((theWrap * 0.5).toString(), 10)); + return width; + } + function normalizeAliases() { + const demandedOptions = yargs.getDemandedOptions(); + const options = yargs.getOptions(); + (Object.keys(options.alias) || []).forEach(key => { + options.alias[key].forEach(alias => { + if (descriptions[alias]) + self.describe(key, descriptions[alias]); + if (alias in demandedOptions) + yargs.demandOption(key, demandedOptions[alias]); + if (options.boolean.includes(alias)) + yargs.boolean(key); + if (options.count.includes(alias)) + yargs.count(key); + if (options.string.includes(alias)) + yargs.string(key); + if (options.normalize.includes(alias)) + yargs.normalize(key); + if (options.array.includes(alias)) + yargs.array(key); + if (options.number.includes(alias)) + yargs.number(key); + }); + }); + } + let cachedHelpMessage; + self.cacheHelpMessage = function () { + cachedHelpMessage = this.help(); + }; + self.clearCachedHelpMessage = function () { + cachedHelpMessage = undefined; + }; + self.hasCachedHelpMessage = function () { + return !!cachedHelpMessage; + }; + function addUngroupedKeys(keys, aliases, groups, defaultGroup) { + let groupedKeys = []; + let toCheck = null; + Object.keys(groups).forEach(group => { + groupedKeys = groupedKeys.concat(groups[group]); + }); + keys.forEach(key => { + toCheck = [key].concat(aliases[key]); + if (!toCheck.some(k => groupedKeys.indexOf(k) !== -1)) { + groups[defaultGroup].push(key); + } + }); + return groupedKeys; + } + function filterHiddenOptions(key) { + return (yargs.getOptions().hiddenOptions.indexOf(key) < 0 || + yargs.parsed.argv[yargs.getOptions().showHiddenOpt]); + } + self.showHelp = (level) => { + const logger = yargs.getInternalMethods().getLoggerInstance(); + if (!level) + level = 'error'; + const emit = typeof level === 'function' ? level : logger[level]; + emit(self.help()); + }; + self.functionDescription = fn => { + const description = fn.name + ? shim.Parser.decamelize(fn.name, '-') + : __('generated-value'); + return ['(', description, ')'].join(''); + }; + self.stringifiedValues = function stringifiedValues(values, separator) { + let string = ''; + const sep = separator || ', '; + const array = [].concat(values); + if (!values || !array.length) + return string; + array.forEach(value => { + if (string.length) + string += sep; + string += JSON.stringify(value); + }); + return string; + }; + function defaultString(value, defaultDescription) { + let string = `[${__('default:')} `; + if (value === undefined && !defaultDescription) + return null; + if (defaultDescription) { + string += defaultDescription; + } + else { + switch (typeof value) { + case 'string': + string += `"${value}"`; + break; + case 'object': + string += JSON.stringify(value); + break; + default: + string += value; + } + } + return `${string}]`; + } + function windowWidth() { + const maxWidth = 80; + if (shim.process.stdColumns) { + return Math.min(maxWidth, shim.process.stdColumns); + } + else { + return maxWidth; + } + } + let version = null; + self.version = ver => { + version = ver; + }; + self.showVersion = level => { + const logger = yargs.getInternalMethods().getLoggerInstance(); + if (!level) + level = 'error'; + const emit = typeof level === 'function' ? level : logger[level]; + emit(version); + }; + self.reset = function reset(localLookup) { + failMessage = null; + failureOutput = false; + usages = []; + usageDisabled = false; + epilogs = []; + examples = []; + commands = []; + descriptions = objFilter(descriptions, k => !localLookup[k]); + return self; + }; + const frozens = []; + self.freeze = function freeze() { + frozens.push({ + failMessage, + failureOutput, + usages, + usageDisabled, + epilogs, + examples, + commands, + descriptions, + }); + }; + self.unfreeze = function unfreeze(defaultCommand = false) { + const frozen = frozens.pop(); + if (!frozen) + return; + if (defaultCommand) { + descriptions = { ...frozen.descriptions, ...descriptions }; + commands = [...frozen.commands, ...commands]; + usages = [...frozen.usages, ...usages]; + examples = [...frozen.examples, ...examples]; + epilogs = [...frozen.epilogs, ...epilogs]; + } + else { + ({ + failMessage, + failureOutput, + usages, + usageDisabled, + epilogs, + examples, + commands, + descriptions, + } = frozen); + } + }; + return self; +} +function isIndentedText(text) { + return typeof text === 'object'; +} +function addIndentation(text, indent) { + return isIndentedText(text) + ? { text: text.text, indentation: text.indentation + indent } + : { text, indentation: indent }; +} +function getIndentation(text) { + return isIndentedText(text) ? text.indentation : 0; +} +function getText(text) { + return isIndentedText(text) ? text.text : text; +} diff --git a/node_modules/yargs/build/lib/utils/apply-extends.js b/node_modules/yargs/build/lib/utils/apply-extends.js new file mode 100644 index 0000000000000000000000000000000000000000..0e593b4fe6d3d2a6d58a81d1919198d1a6f143aa --- /dev/null +++ b/node_modules/yargs/build/lib/utils/apply-extends.js @@ -0,0 +1,59 @@ +import { YError } from '../yerror.js'; +let previouslyVisitedConfigs = []; +let shim; +export function applyExtends(config, cwd, mergeExtends, _shim) { + shim = _shim; + let defaultConfig = {}; + if (Object.prototype.hasOwnProperty.call(config, 'extends')) { + if (typeof config.extends !== 'string') + return defaultConfig; + const isPath = /\.json|\..*rc$/.test(config.extends); + let pathToDefault = null; + if (!isPath) { + try { + pathToDefault = require.resolve(config.extends); + } + catch (_err) { + return config; + } + } + else { + pathToDefault = getPathToDefaultConfig(cwd, config.extends); + } + checkForCircularExtends(pathToDefault); + previouslyVisitedConfigs.push(pathToDefault); + defaultConfig = isPath + ? JSON.parse(shim.readFileSync(pathToDefault, 'utf8')) + : require(config.extends); + delete config.extends; + defaultConfig = applyExtends(defaultConfig, shim.path.dirname(pathToDefault), mergeExtends, shim); + } + previouslyVisitedConfigs = []; + return mergeExtends + ? mergeDeep(defaultConfig, config) + : Object.assign({}, defaultConfig, config); +} +function checkForCircularExtends(cfgPath) { + if (previouslyVisitedConfigs.indexOf(cfgPath) > -1) { + throw new YError(`Circular extended configurations: '${cfgPath}'.`); + } +} +function getPathToDefaultConfig(cwd, pathToExtend) { + return shim.path.resolve(cwd, pathToExtend); +} +function mergeDeep(config1, config2) { + const target = {}; + function isObject(obj) { + return obj && typeof obj === 'object' && !Array.isArray(obj); + } + Object.assign(target, config1); + for (const key of Object.keys(config2)) { + if (isObject(config2[key]) && isObject(target[key])) { + target[key] = mergeDeep(config1[key], config2[key]); + } + else { + target[key] = config2[key]; + } + } + return target; +} diff --git a/node_modules/yargs/build/lib/utils/is-promise.js b/node_modules/yargs/build/lib/utils/is-promise.js new file mode 100644 index 0000000000000000000000000000000000000000..d250c08aaf47c1e104a4ec720a5833242a0c9e26 --- /dev/null +++ b/node_modules/yargs/build/lib/utils/is-promise.js @@ -0,0 +1,5 @@ +export function isPromise(maybePromise) { + return (!!maybePromise && + !!maybePromise.then && + typeof maybePromise.then === 'function'); +} diff --git a/node_modules/yargs/build/lib/utils/levenshtein.js b/node_modules/yargs/build/lib/utils/levenshtein.js new file mode 100644 index 0000000000000000000000000000000000000000..60575ef34f08f8a711639dcd1e57f47030cc6af6 --- /dev/null +++ b/node_modules/yargs/build/lib/utils/levenshtein.js @@ -0,0 +1,34 @@ +export function levenshtein(a, b) { + if (a.length === 0) + return b.length; + if (b.length === 0) + return a.length; + const matrix = []; + let i; + for (i = 0; i <= b.length; i++) { + matrix[i] = [i]; + } + let j; + for (j = 0; j <= a.length; j++) { + matrix[0][j] = j; + } + for (i = 1; i <= b.length; i++) { + for (j = 1; j <= a.length; j++) { + if (b.charAt(i - 1) === a.charAt(j - 1)) { + matrix[i][j] = matrix[i - 1][j - 1]; + } + else { + if (i > 1 && + j > 1 && + b.charAt(i - 2) === a.charAt(j - 1) && + b.charAt(i - 1) === a.charAt(j - 2)) { + matrix[i][j] = matrix[i - 2][j - 2] + 1; + } + else { + matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, Math.min(matrix[i][j - 1] + 1, matrix[i - 1][j] + 1)); + } + } + } + } + return matrix[b.length][a.length]; +} diff --git a/node_modules/yargs/build/lib/utils/maybe-async-result.js b/node_modules/yargs/build/lib/utils/maybe-async-result.js new file mode 100644 index 0000000000000000000000000000000000000000..8c6a40c658a7704dc0756573d18c097ec20481ef --- /dev/null +++ b/node_modules/yargs/build/lib/utils/maybe-async-result.js @@ -0,0 +1,17 @@ +import { isPromise } from './is-promise.js'; +export function maybeAsyncResult(getResult, resultHandler, errorHandler = (err) => { + throw err; +}) { + try { + const result = isFunction(getResult) ? getResult() : getResult; + return isPromise(result) + ? result.then((result) => resultHandler(result)) + : resultHandler(result); + } + catch (err) { + return errorHandler(err); + } +} +function isFunction(arg) { + return typeof arg === 'function'; +} diff --git a/node_modules/yargs/build/lib/utils/obj-filter.js b/node_modules/yargs/build/lib/utils/obj-filter.js new file mode 100644 index 0000000000000000000000000000000000000000..cd68ad2983c063049da26ce1ac731bcbec9017f0 --- /dev/null +++ b/node_modules/yargs/build/lib/utils/obj-filter.js @@ -0,0 +1,10 @@ +import { objectKeys } from '../typings/common-types.js'; +export function objFilter(original = {}, filter = () => true) { + const obj = {}; + objectKeys(original).forEach(key => { + if (filter(key, original[key])) { + obj[key] = original[key]; + } + }); + return obj; +} diff --git a/node_modules/yargs/build/lib/utils/process-argv.js b/node_modules/yargs/build/lib/utils/process-argv.js new file mode 100644 index 0000000000000000000000000000000000000000..74dc9e4c451d0503ec91fd578429887f96f5a449 --- /dev/null +++ b/node_modules/yargs/build/lib/utils/process-argv.js @@ -0,0 +1,17 @@ +function getProcessArgvBinIndex() { + if (isBundledElectronApp()) + return 0; + return 1; +} +function isBundledElectronApp() { + return isElectronApp() && !process.defaultApp; +} +function isElectronApp() { + return !!process.versions.electron; +} +export function hideBin(argv) { + return argv.slice(getProcessArgvBinIndex() + 1); +} +export function getProcessArgvBin() { + return process.argv[getProcessArgvBinIndex()]; +} diff --git a/node_modules/yargs/build/lib/utils/set-blocking.js b/node_modules/yargs/build/lib/utils/set-blocking.js new file mode 100644 index 0000000000000000000000000000000000000000..88fb806df36b9f035b55b958776a4e429a8baeaa --- /dev/null +++ b/node_modules/yargs/build/lib/utils/set-blocking.js @@ -0,0 +1,12 @@ +export default function setBlocking(blocking) { + if (typeof process === 'undefined') + return; + [process.stdout, process.stderr].forEach(_stream => { + const stream = _stream; + if (stream._handle && + stream.isTTY && + typeof stream._handle.setBlocking === 'function') { + stream._handle.setBlocking(blocking); + } + }); +} diff --git a/node_modules/yargs/build/lib/utils/which-module.js b/node_modules/yargs/build/lib/utils/which-module.js new file mode 100644 index 0000000000000000000000000000000000000000..5974e22689d43f748460b4e103493fe70f7f3841 --- /dev/null +++ b/node_modules/yargs/build/lib/utils/which-module.js @@ -0,0 +1,10 @@ +export default function whichModule(exported) { + if (typeof require === 'undefined') + return null; + for (let i = 0, files = Object.keys(require.cache), mod; i < files.length; i++) { + mod = require.cache[files[i]]; + if (mod.exports === exported) + return mod; + } + return null; +} diff --git a/node_modules/yargs/build/lib/validation.js b/node_modules/yargs/build/lib/validation.js new file mode 100644 index 0000000000000000000000000000000000000000..bd2e1b8b1a70ebbac8088ae30c36d0a283a6ad81 --- /dev/null +++ b/node_modules/yargs/build/lib/validation.js @@ -0,0 +1,305 @@ +import { argsert } from './argsert.js'; +import { assertNotStrictEqual, } from './typings/common-types.js'; +import { levenshtein as distance } from './utils/levenshtein.js'; +import { objFilter } from './utils/obj-filter.js'; +const specialKeys = ['$0', '--', '_']; +export function validation(yargs, usage, shim) { + const __ = shim.y18n.__; + const __n = shim.y18n.__n; + const self = {}; + self.nonOptionCount = function nonOptionCount(argv) { + const demandedCommands = yargs.getDemandedCommands(); + const positionalCount = argv._.length + (argv['--'] ? argv['--'].length : 0); + const _s = positionalCount - yargs.getInternalMethods().getContext().commands.length; + if (demandedCommands._ && + (_s < demandedCommands._.min || _s > demandedCommands._.max)) { + if (_s < demandedCommands._.min) { + if (demandedCommands._.minMsg !== undefined) { + usage.fail(demandedCommands._.minMsg + ? demandedCommands._.minMsg + .replace(/\$0/g, _s.toString()) + .replace(/\$1/, demandedCommands._.min.toString()) + : null); + } + else { + usage.fail(__n('Not enough non-option arguments: got %s, need at least %s', 'Not enough non-option arguments: got %s, need at least %s', _s, _s.toString(), demandedCommands._.min.toString())); + } + } + else if (_s > demandedCommands._.max) { + if (demandedCommands._.maxMsg !== undefined) { + usage.fail(demandedCommands._.maxMsg + ? demandedCommands._.maxMsg + .replace(/\$0/g, _s.toString()) + .replace(/\$1/, demandedCommands._.max.toString()) + : null); + } + else { + usage.fail(__n('Too many non-option arguments: got %s, maximum of %s', 'Too many non-option arguments: got %s, maximum of %s', _s, _s.toString(), demandedCommands._.max.toString())); + } + } + } + }; + self.positionalCount = function positionalCount(required, observed) { + if (observed < required) { + usage.fail(__n('Not enough non-option arguments: got %s, need at least %s', 'Not enough non-option arguments: got %s, need at least %s', observed, observed + '', required + '')); + } + }; + self.requiredArguments = function requiredArguments(argv, demandedOptions) { + let missing = null; + for (const key of Object.keys(demandedOptions)) { + if (!Object.prototype.hasOwnProperty.call(argv, key) || + typeof argv[key] === 'undefined') { + missing = missing || {}; + missing[key] = demandedOptions[key]; + } + } + if (missing) { + const customMsgs = []; + for (const key of Object.keys(missing)) { + const msg = missing[key]; + if (msg && customMsgs.indexOf(msg) < 0) { + customMsgs.push(msg); + } + } + const customMsg = customMsgs.length ? `\n${customMsgs.join('\n')}` : ''; + usage.fail(__n('Missing required argument: %s', 'Missing required arguments: %s', Object.keys(missing).length, Object.keys(missing).join(', ') + customMsg)); + } + }; + self.unknownArguments = function unknownArguments(argv, aliases, positionalMap, isDefaultCommand, checkPositionals = true) { + var _a; + const commandKeys = yargs + .getInternalMethods() + .getCommandInstance() + .getCommands(); + const unknown = []; + const currentContext = yargs.getInternalMethods().getContext(); + Object.keys(argv).forEach(key => { + if (!specialKeys.includes(key) && + !Object.prototype.hasOwnProperty.call(positionalMap, key) && + !Object.prototype.hasOwnProperty.call(yargs.getInternalMethods().getParseContext(), key) && + !self.isValidAndSomeAliasIsNotNew(key, aliases)) { + unknown.push(key); + } + }); + if (checkPositionals && + (currentContext.commands.length > 0 || + commandKeys.length > 0 || + isDefaultCommand)) { + argv._.slice(currentContext.commands.length).forEach(key => { + if (!commandKeys.includes('' + key)) { + unknown.push('' + key); + } + }); + } + if (checkPositionals) { + const demandedCommands = yargs.getDemandedCommands(); + const maxNonOptDemanded = ((_a = demandedCommands._) === null || _a === void 0 ? void 0 : _a.max) || 0; + const expected = currentContext.commands.length + maxNonOptDemanded; + if (expected < argv._.length) { + argv._.slice(expected).forEach(key => { + key = String(key); + if (!currentContext.commands.includes(key) && + !unknown.includes(key)) { + unknown.push(key); + } + }); + } + } + if (unknown.length) { + usage.fail(__n('Unknown argument: %s', 'Unknown arguments: %s', unknown.length, unknown.map(s => (s.trim() ? s : `"${s}"`)).join(', '))); + } + }; + self.unknownCommands = function unknownCommands(argv) { + const commandKeys = yargs + .getInternalMethods() + .getCommandInstance() + .getCommands(); + const unknown = []; + const currentContext = yargs.getInternalMethods().getContext(); + if (currentContext.commands.length > 0 || commandKeys.length > 0) { + argv._.slice(currentContext.commands.length).forEach(key => { + if (!commandKeys.includes('' + key)) { + unknown.push('' + key); + } + }); + } + if (unknown.length > 0) { + usage.fail(__n('Unknown command: %s', 'Unknown commands: %s', unknown.length, unknown.join(', '))); + return true; + } + else { + return false; + } + }; + self.isValidAndSomeAliasIsNotNew = function isValidAndSomeAliasIsNotNew(key, aliases) { + if (!Object.prototype.hasOwnProperty.call(aliases, key)) { + return false; + } + const newAliases = yargs.parsed.newAliases; + return [key, ...aliases[key]].some(a => !Object.prototype.hasOwnProperty.call(newAliases, a) || !newAliases[key]); + }; + self.limitedChoices = function limitedChoices(argv) { + const options = yargs.getOptions(); + const invalid = {}; + if (!Object.keys(options.choices).length) + return; + Object.keys(argv).forEach(key => { + if (specialKeys.indexOf(key) === -1 && + Object.prototype.hasOwnProperty.call(options.choices, key)) { + [].concat(argv[key]).forEach(value => { + if (options.choices[key].indexOf(value) === -1 && + value !== undefined) { + invalid[key] = (invalid[key] || []).concat(value); + } + }); + } + }); + const invalidKeys = Object.keys(invalid); + if (!invalidKeys.length) + return; + let msg = __('Invalid values:'); + invalidKeys.forEach(key => { + msg += `\n ${__('Argument: %s, Given: %s, Choices: %s', key, usage.stringifiedValues(invalid[key]), usage.stringifiedValues(options.choices[key]))}`; + }); + usage.fail(msg); + }; + let implied = {}; + self.implies = function implies(key, value) { + argsert(' [array|number|string]', [key, value], arguments.length); + if (typeof key === 'object') { + Object.keys(key).forEach(k => { + self.implies(k, key[k]); + }); + } + else { + yargs.global(key); + if (!implied[key]) { + implied[key] = []; + } + if (Array.isArray(value)) { + value.forEach(i => self.implies(key, i)); + } + else { + assertNotStrictEqual(value, undefined, shim); + implied[key].push(value); + } + } + }; + self.getImplied = function getImplied() { + return implied; + }; + function keyExists(argv, val) { + const num = Number(val); + val = isNaN(num) ? val : num; + if (typeof val === 'number') { + val = argv._.length >= val; + } + else if (val.match(/^--no-.+/)) { + val = val.match(/^--no-(.+)/)[1]; + val = !Object.prototype.hasOwnProperty.call(argv, val); + } + else { + val = Object.prototype.hasOwnProperty.call(argv, val); + } + return val; + } + self.implications = function implications(argv) { + const implyFail = []; + Object.keys(implied).forEach(key => { + const origKey = key; + (implied[key] || []).forEach(value => { + let key = origKey; + const origValue = value; + key = keyExists(argv, key); + value = keyExists(argv, value); + if (key && !value) { + implyFail.push(` ${origKey} -> ${origValue}`); + } + }); + }); + if (implyFail.length) { + let msg = `${__('Implications failed:')}\n`; + implyFail.forEach(value => { + msg += value; + }); + usage.fail(msg); + } + }; + let conflicting = {}; + self.conflicts = function conflicts(key, value) { + argsert(' [array|string]', [key, value], arguments.length); + if (typeof key === 'object') { + Object.keys(key).forEach(k => { + self.conflicts(k, key[k]); + }); + } + else { + yargs.global(key); + if (!conflicting[key]) { + conflicting[key] = []; + } + if (Array.isArray(value)) { + value.forEach(i => self.conflicts(key, i)); + } + else { + conflicting[key].push(value); + } + } + }; + self.getConflicting = () => conflicting; + self.conflicting = function conflictingFn(argv) { + Object.keys(argv).forEach(key => { + if (conflicting[key]) { + conflicting[key].forEach(value => { + if (value && argv[key] !== undefined && argv[value] !== undefined) { + usage.fail(__('Arguments %s and %s are mutually exclusive', key, value)); + } + }); + } + }); + if (yargs.getInternalMethods().getParserConfiguration()['strip-dashed']) { + Object.keys(conflicting).forEach(key => { + conflicting[key].forEach(value => { + if (value && + argv[shim.Parser.camelCase(key)] !== undefined && + argv[shim.Parser.camelCase(value)] !== undefined) { + usage.fail(__('Arguments %s and %s are mutually exclusive', key, value)); + } + }); + }); + } + }; + self.recommendCommands = function recommendCommands(cmd, potentialCommands) { + const threshold = 3; + potentialCommands = potentialCommands.sort((a, b) => b.length - a.length); + let recommended = null; + let bestDistance = Infinity; + for (let i = 0, candidate; (candidate = potentialCommands[i]) !== undefined; i++) { + const d = distance(cmd, candidate); + if (d <= threshold && d < bestDistance) { + bestDistance = d; + recommended = candidate; + } + } + if (recommended) + usage.fail(__('Did you mean %s?', recommended)); + }; + self.reset = function reset(localLookup) { + implied = objFilter(implied, k => !localLookup[k]); + conflicting = objFilter(conflicting, k => !localLookup[k]); + return self; + }; + const frozens = []; + self.freeze = function freeze() { + frozens.push({ + implied, + conflicting, + }); + }; + self.unfreeze = function unfreeze() { + const frozen = frozens.pop(); + assertNotStrictEqual(frozen, undefined, shim); + ({ implied, conflicting } = frozen); + }; + return self; +} diff --git a/node_modules/yargs/build/lib/yargs-factory.js b/node_modules/yargs/build/lib/yargs-factory.js new file mode 100644 index 0000000000000000000000000000000000000000..c4b1d5098a27c23d32614af4486452d991272b07 --- /dev/null +++ b/node_modules/yargs/build/lib/yargs-factory.js @@ -0,0 +1,1512 @@ +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _YargsInstance_command, _YargsInstance_cwd, _YargsInstance_context, _YargsInstance_completion, _YargsInstance_completionCommand, _YargsInstance_defaultShowHiddenOpt, _YargsInstance_exitError, _YargsInstance_detectLocale, _YargsInstance_emittedWarnings, _YargsInstance_exitProcess, _YargsInstance_frozens, _YargsInstance_globalMiddleware, _YargsInstance_groups, _YargsInstance_hasOutput, _YargsInstance_helpOpt, _YargsInstance_isGlobalContext, _YargsInstance_logger, _YargsInstance_output, _YargsInstance_options, _YargsInstance_parentRequire, _YargsInstance_parserConfig, _YargsInstance_parseFn, _YargsInstance_parseContext, _YargsInstance_pkgs, _YargsInstance_preservedGroups, _YargsInstance_processArgs, _YargsInstance_recommendCommands, _YargsInstance_shim, _YargsInstance_strict, _YargsInstance_strictCommands, _YargsInstance_strictOptions, _YargsInstance_usage, _YargsInstance_usageConfig, _YargsInstance_versionOpt, _YargsInstance_validation; +import { command as Command, } from './command.js'; +import { assertNotStrictEqual, assertSingleKey, objectKeys, } from './typings/common-types.js'; +import { YError } from './yerror.js'; +import { usage as Usage } from './usage.js'; +import { argsert } from './argsert.js'; +import { completion as Completion, } from './completion.js'; +import { validation as Validation, } from './validation.js'; +import { objFilter } from './utils/obj-filter.js'; +import { applyExtends } from './utils/apply-extends.js'; +import { applyMiddleware, GlobalMiddleware, } from './middleware.js'; +import { isPromise } from './utils/is-promise.js'; +import { maybeAsyncResult } from './utils/maybe-async-result.js'; +import setBlocking from './utils/set-blocking.js'; +export function YargsFactory(_shim) { + return (processArgs = [], cwd = _shim.process.cwd(), parentRequire) => { + const yargs = new YargsInstance(processArgs, cwd, parentRequire, _shim); + Object.defineProperty(yargs, 'argv', { + get: () => { + return yargs.parse(); + }, + enumerable: true, + }); + yargs.help(); + yargs.version(); + return yargs; + }; +} +const kCopyDoubleDash = Symbol('copyDoubleDash'); +const kCreateLogger = Symbol('copyDoubleDash'); +const kDeleteFromParserHintObject = Symbol('deleteFromParserHintObject'); +const kEmitWarning = Symbol('emitWarning'); +const kFreeze = Symbol('freeze'); +const kGetDollarZero = Symbol('getDollarZero'); +const kGetParserConfiguration = Symbol('getParserConfiguration'); +const kGetUsageConfiguration = Symbol('getUsageConfiguration'); +const kGuessLocale = Symbol('guessLocale'); +const kGuessVersion = Symbol('guessVersion'); +const kParsePositionalNumbers = Symbol('parsePositionalNumbers'); +const kPkgUp = Symbol('pkgUp'); +const kPopulateParserHintArray = Symbol('populateParserHintArray'); +const kPopulateParserHintSingleValueDictionary = Symbol('populateParserHintSingleValueDictionary'); +const kPopulateParserHintArrayDictionary = Symbol('populateParserHintArrayDictionary'); +const kPopulateParserHintDictionary = Symbol('populateParserHintDictionary'); +const kSanitizeKey = Symbol('sanitizeKey'); +const kSetKey = Symbol('setKey'); +const kUnfreeze = Symbol('unfreeze'); +const kValidateAsync = Symbol('validateAsync'); +const kGetCommandInstance = Symbol('getCommandInstance'); +const kGetContext = Symbol('getContext'); +const kGetHasOutput = Symbol('getHasOutput'); +const kGetLoggerInstance = Symbol('getLoggerInstance'); +const kGetParseContext = Symbol('getParseContext'); +const kGetUsageInstance = Symbol('getUsageInstance'); +const kGetValidationInstance = Symbol('getValidationInstance'); +const kHasParseCallback = Symbol('hasParseCallback'); +const kIsGlobalContext = Symbol('isGlobalContext'); +const kPostProcess = Symbol('postProcess'); +const kRebase = Symbol('rebase'); +const kReset = Symbol('reset'); +const kRunYargsParserAndExecuteCommands = Symbol('runYargsParserAndExecuteCommands'); +const kRunValidation = Symbol('runValidation'); +const kSetHasOutput = Symbol('setHasOutput'); +const kTrackManuallySetKeys = Symbol('kTrackManuallySetKeys'); +export class YargsInstance { + constructor(processArgs = [], cwd, parentRequire, shim) { + this.customScriptName = false; + this.parsed = false; + _YargsInstance_command.set(this, void 0); + _YargsInstance_cwd.set(this, void 0); + _YargsInstance_context.set(this, { commands: [], fullCommands: [] }); + _YargsInstance_completion.set(this, null); + _YargsInstance_completionCommand.set(this, null); + _YargsInstance_defaultShowHiddenOpt.set(this, 'show-hidden'); + _YargsInstance_exitError.set(this, null); + _YargsInstance_detectLocale.set(this, true); + _YargsInstance_emittedWarnings.set(this, {}); + _YargsInstance_exitProcess.set(this, true); + _YargsInstance_frozens.set(this, []); + _YargsInstance_globalMiddleware.set(this, void 0); + _YargsInstance_groups.set(this, {}); + _YargsInstance_hasOutput.set(this, false); + _YargsInstance_helpOpt.set(this, null); + _YargsInstance_isGlobalContext.set(this, true); + _YargsInstance_logger.set(this, void 0); + _YargsInstance_output.set(this, ''); + _YargsInstance_options.set(this, void 0); + _YargsInstance_parentRequire.set(this, void 0); + _YargsInstance_parserConfig.set(this, {}); + _YargsInstance_parseFn.set(this, null); + _YargsInstance_parseContext.set(this, null); + _YargsInstance_pkgs.set(this, {}); + _YargsInstance_preservedGroups.set(this, {}); + _YargsInstance_processArgs.set(this, void 0); + _YargsInstance_recommendCommands.set(this, false); + _YargsInstance_shim.set(this, void 0); + _YargsInstance_strict.set(this, false); + _YargsInstance_strictCommands.set(this, false); + _YargsInstance_strictOptions.set(this, false); + _YargsInstance_usage.set(this, void 0); + _YargsInstance_usageConfig.set(this, {}); + _YargsInstance_versionOpt.set(this, null); + _YargsInstance_validation.set(this, void 0); + __classPrivateFieldSet(this, _YargsInstance_shim, shim, "f"); + __classPrivateFieldSet(this, _YargsInstance_processArgs, processArgs, "f"); + __classPrivateFieldSet(this, _YargsInstance_cwd, cwd, "f"); + __classPrivateFieldSet(this, _YargsInstance_parentRequire, parentRequire, "f"); + __classPrivateFieldSet(this, _YargsInstance_globalMiddleware, new GlobalMiddleware(this), "f"); + this.$0 = this[kGetDollarZero](); + this[kReset](); + __classPrivateFieldSet(this, _YargsInstance_command, __classPrivateFieldGet(this, _YargsInstance_command, "f"), "f"); + __classPrivateFieldSet(this, _YargsInstance_usage, __classPrivateFieldGet(this, _YargsInstance_usage, "f"), "f"); + __classPrivateFieldSet(this, _YargsInstance_validation, __classPrivateFieldGet(this, _YargsInstance_validation, "f"), "f"); + __classPrivateFieldSet(this, _YargsInstance_options, __classPrivateFieldGet(this, _YargsInstance_options, "f"), "f"); + __classPrivateFieldGet(this, _YargsInstance_options, "f").showHiddenOpt = __classPrivateFieldGet(this, _YargsInstance_defaultShowHiddenOpt, "f"); + __classPrivateFieldSet(this, _YargsInstance_logger, this[kCreateLogger](), "f"); + } + addHelpOpt(opt, msg) { + const defaultHelpOpt = 'help'; + argsert('[string|boolean] [string]', [opt, msg], arguments.length); + if (__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")) { + this[kDeleteFromParserHintObject](__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")); + __classPrivateFieldSet(this, _YargsInstance_helpOpt, null, "f"); + } + if (opt === false && msg === undefined) + return this; + __classPrivateFieldSet(this, _YargsInstance_helpOpt, typeof opt === 'string' ? opt : defaultHelpOpt, "f"); + this.boolean(__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")); + this.describe(__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f"), msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup('Show help')); + return this; + } + help(opt, msg) { + return this.addHelpOpt(opt, msg); + } + addShowHiddenOpt(opt, msg) { + argsert('[string|boolean] [string]', [opt, msg], arguments.length); + if (opt === false && msg === undefined) + return this; + const showHiddenOpt = typeof opt === 'string' ? opt : __classPrivateFieldGet(this, _YargsInstance_defaultShowHiddenOpt, "f"); + this.boolean(showHiddenOpt); + this.describe(showHiddenOpt, msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup('Show hidden options')); + __classPrivateFieldGet(this, _YargsInstance_options, "f").showHiddenOpt = showHiddenOpt; + return this; + } + showHidden(opt, msg) { + return this.addShowHiddenOpt(opt, msg); + } + alias(key, value) { + argsert(' [string|array]', [key, value], arguments.length); + this[kPopulateParserHintArrayDictionary](this.alias.bind(this), 'alias', key, value); + return this; + } + array(keys) { + argsert('', [keys], arguments.length); + this[kPopulateParserHintArray]('array', keys); + this[kTrackManuallySetKeys](keys); + return this; + } + boolean(keys) { + argsert('', [keys], arguments.length); + this[kPopulateParserHintArray]('boolean', keys); + this[kTrackManuallySetKeys](keys); + return this; + } + check(f, global) { + argsert(' [boolean]', [f, global], arguments.length); + this.middleware((argv, _yargs) => { + return maybeAsyncResult(() => { + return f(argv, _yargs.getOptions()); + }, (result) => { + if (!result) { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(__classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.__('Argument check failed: %s', f.toString())); + } + else if (typeof result === 'string' || result instanceof Error) { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(result.toString(), result); + } + return argv; + }, (err) => { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(err.message ? err.message : err.toString(), err); + return argv; + }); + }, false, global); + return this; + } + choices(key, value) { + argsert(' [string|array]', [key, value], arguments.length); + this[kPopulateParserHintArrayDictionary](this.choices.bind(this), 'choices', key, value); + return this; + } + coerce(keys, value) { + argsert(' [function]', [keys, value], arguments.length); + if (Array.isArray(keys)) { + if (!value) { + throw new YError('coerce callback must be provided'); + } + for (const key of keys) { + this.coerce(key, value); + } + return this; + } + else if (typeof keys === 'object') { + for (const key of Object.keys(keys)) { + this.coerce(key, keys[key]); + } + return this; + } + if (!value) { + throw new YError('coerce callback must be provided'); + } + __classPrivateFieldGet(this, _YargsInstance_options, "f").key[keys] = true; + __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").addCoerceMiddleware((argv, yargs) => { + let aliases; + const shouldCoerce = Object.prototype.hasOwnProperty.call(argv, keys); + if (!shouldCoerce) { + return argv; + } + return maybeAsyncResult(() => { + aliases = yargs.getAliases(); + return value(argv[keys]); + }, (result) => { + argv[keys] = result; + const stripAliased = yargs + .getInternalMethods() + .getParserConfiguration()['strip-aliased']; + if (aliases[keys] && stripAliased !== true) { + for (const alias of aliases[keys]) { + argv[alias] = result; + } + } + return argv; + }, (err) => { + throw new YError(err.message); + }); + }, keys); + return this; + } + conflicts(key1, key2) { + argsert(' [string|array]', [key1, key2], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").conflicts(key1, key2); + return this; + } + config(key = 'config', msg, parseFn) { + argsert('[object|string] [string|function] [function]', [key, msg, parseFn], arguments.length); + if (typeof key === 'object' && !Array.isArray(key)) { + key = applyExtends(key, __classPrivateFieldGet(this, _YargsInstance_cwd, "f"), this[kGetParserConfiguration]()['deep-merge-config'] || false, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects = (__classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects || []).concat(key); + return this; + } + if (typeof msg === 'function') { + parseFn = msg; + msg = undefined; + } + this.describe(key, msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup('Path to JSON config file')); + (Array.isArray(key) ? key : [key]).forEach(k => { + __classPrivateFieldGet(this, _YargsInstance_options, "f").config[k] = parseFn || true; + }); + return this; + } + completion(cmd, desc, fn) { + argsert('[string] [string|boolean|function] [function]', [cmd, desc, fn], arguments.length); + if (typeof desc === 'function') { + fn = desc; + desc = undefined; + } + __classPrivateFieldSet(this, _YargsInstance_completionCommand, cmd || __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f") || 'completion', "f"); + if (!desc && desc !== false) { + desc = 'generate completion script'; + } + this.command(__classPrivateFieldGet(this, _YargsInstance_completionCommand, "f"), desc); + if (fn) + __classPrivateFieldGet(this, _YargsInstance_completion, "f").registerFunction(fn); + return this; + } + command(cmd, description, builder, handler, middlewares, deprecated) { + argsert(' [string|boolean] [function|object] [function] [array] [boolean|string]', [cmd, description, builder, handler, middlewares, deprecated], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_command, "f").addHandler(cmd, description, builder, handler, middlewares, deprecated); + return this; + } + commands(cmd, description, builder, handler, middlewares, deprecated) { + return this.command(cmd, description, builder, handler, middlewares, deprecated); + } + commandDir(dir, opts) { + argsert(' [object]', [dir, opts], arguments.length); + const req = __classPrivateFieldGet(this, _YargsInstance_parentRequire, "f") || __classPrivateFieldGet(this, _YargsInstance_shim, "f").require; + __classPrivateFieldGet(this, _YargsInstance_command, "f").addDirectory(dir, req, __classPrivateFieldGet(this, _YargsInstance_shim, "f").getCallerFile(), opts); + return this; + } + count(keys) { + argsert('', [keys], arguments.length); + this[kPopulateParserHintArray]('count', keys); + this[kTrackManuallySetKeys](keys); + return this; + } + default(key, value, defaultDescription) { + argsert(' [*] [string]', [key, value, defaultDescription], arguments.length); + if (defaultDescription) { + assertSingleKey(key, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + __classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key] = defaultDescription; + } + if (typeof value === 'function') { + assertSingleKey(key, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + if (!__classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key]) + __classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key] = + __classPrivateFieldGet(this, _YargsInstance_usage, "f").functionDescription(value); + value = value.call(); + } + this[kPopulateParserHintSingleValueDictionary](this.default.bind(this), 'default', key, value); + return this; + } + defaults(key, value, defaultDescription) { + return this.default(key, value, defaultDescription); + } + demandCommand(min = 1, max, minMsg, maxMsg) { + argsert('[number] [number|string] [string|null|undefined] [string|null|undefined]', [min, max, minMsg, maxMsg], arguments.length); + if (typeof max !== 'number') { + minMsg = max; + max = Infinity; + } + this.global('_', false); + __classPrivateFieldGet(this, _YargsInstance_options, "f").demandedCommands._ = { + min, + max, + minMsg, + maxMsg, + }; + return this; + } + demand(keys, max, msg) { + if (Array.isArray(max)) { + max.forEach(key => { + assertNotStrictEqual(msg, true, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + this.demandOption(key, msg); + }); + max = Infinity; + } + else if (typeof max !== 'number') { + msg = max; + max = Infinity; + } + if (typeof keys === 'number') { + assertNotStrictEqual(msg, true, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + this.demandCommand(keys, max, msg, msg); + } + else if (Array.isArray(keys)) { + keys.forEach(key => { + assertNotStrictEqual(msg, true, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + this.demandOption(key, msg); + }); + } + else { + if (typeof msg === 'string') { + this.demandOption(keys, msg); + } + else if (msg === true || typeof msg === 'undefined') { + this.demandOption(keys); + } + } + return this; + } + demandOption(keys, msg) { + argsert(' [string]', [keys, msg], arguments.length); + this[kPopulateParserHintSingleValueDictionary](this.demandOption.bind(this), 'demandedOptions', keys, msg); + return this; + } + deprecateOption(option, message) { + argsert(' [string|boolean]', [option, message], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_options, "f").deprecatedOptions[option] = message; + return this; + } + describe(keys, description) { + argsert(' [string]', [keys, description], arguments.length); + this[kSetKey](keys, true); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").describe(keys, description); + return this; + } + detectLocale(detect) { + argsert('', [detect], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_detectLocale, detect, "f"); + return this; + } + env(prefix) { + argsert('[string|boolean]', [prefix], arguments.length); + if (prefix === false) + delete __classPrivateFieldGet(this, _YargsInstance_options, "f").envPrefix; + else + __classPrivateFieldGet(this, _YargsInstance_options, "f").envPrefix = prefix || ''; + return this; + } + epilogue(msg) { + argsert('', [msg], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").epilog(msg); + return this; + } + epilog(msg) { + return this.epilogue(msg); + } + example(cmd, description) { + argsert(' [string]', [cmd, description], arguments.length); + if (Array.isArray(cmd)) { + cmd.forEach(exampleParams => this.example(...exampleParams)); + } + else { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").example(cmd, description); + } + return this; + } + exit(code, err) { + __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); + __classPrivateFieldSet(this, _YargsInstance_exitError, err, "f"); + if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f")) + __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.exit(code); + } + exitProcess(enabled = true) { + argsert('[boolean]', [enabled], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_exitProcess, enabled, "f"); + return this; + } + fail(f) { + argsert('', [f], arguments.length); + if (typeof f === 'boolean' && f !== false) { + throw new YError("Invalid first argument. Expected function or boolean 'false'"); + } + __classPrivateFieldGet(this, _YargsInstance_usage, "f").failFn(f); + return this; + } + getAliases() { + return this.parsed ? this.parsed.aliases : {}; + } + async getCompletion(args, done) { + argsert(' [function]', [args, done], arguments.length); + if (!done) { + return new Promise((resolve, reject) => { + __classPrivateFieldGet(this, _YargsInstance_completion, "f").getCompletion(args, (err, completions) => { + if (err) + reject(err); + else + resolve(completions); + }); + }); + } + else { + return __classPrivateFieldGet(this, _YargsInstance_completion, "f").getCompletion(args, done); + } + } + getDemandedOptions() { + argsert([], 0); + return __classPrivateFieldGet(this, _YargsInstance_options, "f").demandedOptions; + } + getDemandedCommands() { + argsert([], 0); + return __classPrivateFieldGet(this, _YargsInstance_options, "f").demandedCommands; + } + getDeprecatedOptions() { + argsert([], 0); + return __classPrivateFieldGet(this, _YargsInstance_options, "f").deprecatedOptions; + } + getDetectLocale() { + return __classPrivateFieldGet(this, _YargsInstance_detectLocale, "f"); + } + getExitProcess() { + return __classPrivateFieldGet(this, _YargsInstance_exitProcess, "f"); + } + getGroups() { + return Object.assign({}, __classPrivateFieldGet(this, _YargsInstance_groups, "f"), __classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f")); + } + getHelp() { + __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); + if (!__classPrivateFieldGet(this, _YargsInstance_usage, "f").hasCachedHelpMessage()) { + if (!this.parsed) { + const parse = this[kRunYargsParserAndExecuteCommands](__classPrivateFieldGet(this, _YargsInstance_processArgs, "f"), undefined, undefined, 0, true); + if (isPromise(parse)) { + return parse.then(() => { + return __classPrivateFieldGet(this, _YargsInstance_usage, "f").help(); + }); + } + } + const builderResponse = __classPrivateFieldGet(this, _YargsInstance_command, "f").runDefaultBuilderOn(this); + if (isPromise(builderResponse)) { + return builderResponse.then(() => { + return __classPrivateFieldGet(this, _YargsInstance_usage, "f").help(); + }); + } + } + return Promise.resolve(__classPrivateFieldGet(this, _YargsInstance_usage, "f").help()); + } + getOptions() { + return __classPrivateFieldGet(this, _YargsInstance_options, "f"); + } + getStrict() { + return __classPrivateFieldGet(this, _YargsInstance_strict, "f"); + } + getStrictCommands() { + return __classPrivateFieldGet(this, _YargsInstance_strictCommands, "f"); + } + getStrictOptions() { + return __classPrivateFieldGet(this, _YargsInstance_strictOptions, "f"); + } + global(globals, global) { + argsert(' [boolean]', [globals, global], arguments.length); + globals = [].concat(globals); + if (global !== false) { + __classPrivateFieldGet(this, _YargsInstance_options, "f").local = __classPrivateFieldGet(this, _YargsInstance_options, "f").local.filter(l => globals.indexOf(l) === -1); + } + else { + globals.forEach(g => { + if (!__classPrivateFieldGet(this, _YargsInstance_options, "f").local.includes(g)) + __classPrivateFieldGet(this, _YargsInstance_options, "f").local.push(g); + }); + } + return this; + } + group(opts, groupName) { + argsert(' ', [opts, groupName], arguments.length); + const existing = __classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f")[groupName] || __classPrivateFieldGet(this, _YargsInstance_groups, "f")[groupName]; + if (__classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f")[groupName]) { + delete __classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f")[groupName]; + } + const seen = {}; + __classPrivateFieldGet(this, _YargsInstance_groups, "f")[groupName] = (existing || []).concat(opts).filter(key => { + if (seen[key]) + return false; + return (seen[key] = true); + }); + return this; + } + hide(key) { + argsert('', [key], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_options, "f").hiddenOptions.push(key); + return this; + } + implies(key, value) { + argsert(' [number|string|array]', [key, value], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").implies(key, value); + return this; + } + locale(locale) { + argsert('[string]', [locale], arguments.length); + if (locale === undefined) { + this[kGuessLocale](); + return __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.getLocale(); + } + __classPrivateFieldSet(this, _YargsInstance_detectLocale, false, "f"); + __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.setLocale(locale); + return this; + } + middleware(callback, applyBeforeValidation, global) { + return __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").addMiddleware(callback, !!applyBeforeValidation, global); + } + nargs(key, value) { + argsert(' [number]', [key, value], arguments.length); + this[kPopulateParserHintSingleValueDictionary](this.nargs.bind(this), 'narg', key, value); + return this; + } + normalize(keys) { + argsert('', [keys], arguments.length); + this[kPopulateParserHintArray]('normalize', keys); + return this; + } + number(keys) { + argsert('', [keys], arguments.length); + this[kPopulateParserHintArray]('number', keys); + this[kTrackManuallySetKeys](keys); + return this; + } + option(key, opt) { + argsert(' [object]', [key, opt], arguments.length); + if (typeof key === 'object') { + Object.keys(key).forEach(k => { + this.options(k, key[k]); + }); + } + else { + if (typeof opt !== 'object') { + opt = {}; + } + this[kTrackManuallySetKeys](key); + if (__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f") && (key === 'version' || (opt === null || opt === void 0 ? void 0 : opt.alias) === 'version')) { + this[kEmitWarning]([ + '"version" is a reserved word.', + 'Please do one of the following:', + '- Disable version with `yargs.version(false)` if using "version" as an option', + '- Use the built-in `yargs.version` method instead (if applicable)', + '- Use a different option key', + 'https://yargs.js.org/docs/#api-reference-version', + ].join('\n'), undefined, 'versionWarning'); + } + __classPrivateFieldGet(this, _YargsInstance_options, "f").key[key] = true; + if (opt.alias) + this.alias(key, opt.alias); + const deprecate = opt.deprecate || opt.deprecated; + if (deprecate) { + this.deprecateOption(key, deprecate); + } + const demand = opt.demand || opt.required || opt.require; + if (demand) { + this.demand(key, demand); + } + if (opt.demandOption) { + this.demandOption(key, typeof opt.demandOption === 'string' ? opt.demandOption : undefined); + } + if (opt.conflicts) { + this.conflicts(key, opt.conflicts); + } + if ('default' in opt) { + this.default(key, opt.default); + } + if (opt.implies !== undefined) { + this.implies(key, opt.implies); + } + if (opt.nargs !== undefined) { + this.nargs(key, opt.nargs); + } + if (opt.config) { + this.config(key, opt.configParser); + } + if (opt.normalize) { + this.normalize(key); + } + if (opt.choices) { + this.choices(key, opt.choices); + } + if (opt.coerce) { + this.coerce(key, opt.coerce); + } + if (opt.group) { + this.group(key, opt.group); + } + if (opt.boolean || opt.type === 'boolean') { + this.boolean(key); + if (opt.alias) + this.boolean(opt.alias); + } + if (opt.array || opt.type === 'array') { + this.array(key); + if (opt.alias) + this.array(opt.alias); + } + if (opt.number || opt.type === 'number') { + this.number(key); + if (opt.alias) + this.number(opt.alias); + } + if (opt.string || opt.type === 'string') { + this.string(key); + if (opt.alias) + this.string(opt.alias); + } + if (opt.count || opt.type === 'count') { + this.count(key); + } + if (typeof opt.global === 'boolean') { + this.global(key, opt.global); + } + if (opt.defaultDescription) { + __classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key] = opt.defaultDescription; + } + if (opt.skipValidation) { + this.skipValidation(key); + } + const desc = opt.describe || opt.description || opt.desc; + const descriptions = __classPrivateFieldGet(this, _YargsInstance_usage, "f").getDescriptions(); + if (!Object.prototype.hasOwnProperty.call(descriptions, key) || + typeof desc === 'string') { + this.describe(key, desc); + } + if (opt.hidden) { + this.hide(key); + } + if (opt.requiresArg) { + this.requiresArg(key); + } + } + return this; + } + options(key, opt) { + return this.option(key, opt); + } + parse(args, shortCircuit, _parseFn) { + argsert('[string|array] [function|boolean|object] [function]', [args, shortCircuit, _parseFn], arguments.length); + this[kFreeze](); + if (typeof args === 'undefined') { + args = __classPrivateFieldGet(this, _YargsInstance_processArgs, "f"); + } + if (typeof shortCircuit === 'object') { + __classPrivateFieldSet(this, _YargsInstance_parseContext, shortCircuit, "f"); + shortCircuit = _parseFn; + } + if (typeof shortCircuit === 'function') { + __classPrivateFieldSet(this, _YargsInstance_parseFn, shortCircuit, "f"); + shortCircuit = false; + } + if (!shortCircuit) + __classPrivateFieldSet(this, _YargsInstance_processArgs, args, "f"); + if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f")) + __classPrivateFieldSet(this, _YargsInstance_exitProcess, false, "f"); + const parsed = this[kRunYargsParserAndExecuteCommands](args, !!shortCircuit); + const tmpParsed = this.parsed; + __classPrivateFieldGet(this, _YargsInstance_completion, "f").setParsed(this.parsed); + if (isPromise(parsed)) { + return parsed + .then(argv => { + if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f")) + __classPrivateFieldGet(this, _YargsInstance_parseFn, "f").call(this, __classPrivateFieldGet(this, _YargsInstance_exitError, "f"), argv, __classPrivateFieldGet(this, _YargsInstance_output, "f")); + return argv; + }) + .catch(err => { + if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f")) { + __classPrivateFieldGet(this, _YargsInstance_parseFn, "f")(err, this.parsed.argv, __classPrivateFieldGet(this, _YargsInstance_output, "f")); + } + throw err; + }) + .finally(() => { + this[kUnfreeze](); + this.parsed = tmpParsed; + }); + } + else { + if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f")) + __classPrivateFieldGet(this, _YargsInstance_parseFn, "f").call(this, __classPrivateFieldGet(this, _YargsInstance_exitError, "f"), parsed, __classPrivateFieldGet(this, _YargsInstance_output, "f")); + this[kUnfreeze](); + this.parsed = tmpParsed; + } + return parsed; + } + parseAsync(args, shortCircuit, _parseFn) { + const maybePromise = this.parse(args, shortCircuit, _parseFn); + return !isPromise(maybePromise) + ? Promise.resolve(maybePromise) + : maybePromise; + } + parseSync(args, shortCircuit, _parseFn) { + const maybePromise = this.parse(args, shortCircuit, _parseFn); + if (isPromise(maybePromise)) { + throw new YError('.parseSync() must not be used with asynchronous builders, handlers, or middleware'); + } + return maybePromise; + } + parserConfiguration(config) { + argsert('', [config], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_parserConfig, config, "f"); + return this; + } + pkgConf(key, rootPath) { + argsert(' [string]', [key, rootPath], arguments.length); + let conf = null; + const obj = this[kPkgUp](rootPath || __classPrivateFieldGet(this, _YargsInstance_cwd, "f")); + if (obj[key] && typeof obj[key] === 'object') { + conf = applyExtends(obj[key], rootPath || __classPrivateFieldGet(this, _YargsInstance_cwd, "f"), this[kGetParserConfiguration]()['deep-merge-config'] || false, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects = (__classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects || []).concat(conf); + } + return this; + } + positional(key, opts) { + argsert(' ', [key, opts], arguments.length); + const supportedOpts = [ + 'default', + 'defaultDescription', + 'implies', + 'normalize', + 'choices', + 'conflicts', + 'coerce', + 'type', + 'describe', + 'desc', + 'description', + 'alias', + ]; + opts = objFilter(opts, (k, v) => { + if (k === 'type' && !['string', 'number', 'boolean'].includes(v)) + return false; + return supportedOpts.includes(k); + }); + const fullCommand = __classPrivateFieldGet(this, _YargsInstance_context, "f").fullCommands[__classPrivateFieldGet(this, _YargsInstance_context, "f").fullCommands.length - 1]; + const parseOptions = fullCommand + ? __classPrivateFieldGet(this, _YargsInstance_command, "f").cmdToParseOptions(fullCommand) + : { + array: [], + alias: {}, + default: {}, + demand: {}, + }; + objectKeys(parseOptions).forEach(pk => { + const parseOption = parseOptions[pk]; + if (Array.isArray(parseOption)) { + if (parseOption.indexOf(key) !== -1) + opts[pk] = true; + } + else { + if (parseOption[key] && !(pk in opts)) + opts[pk] = parseOption[key]; + } + }); + this.group(key, __classPrivateFieldGet(this, _YargsInstance_usage, "f").getPositionalGroupName()); + return this.option(key, opts); + } + recommendCommands(recommend = true) { + argsert('[boolean]', [recommend], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_recommendCommands, recommend, "f"); + return this; + } + required(keys, max, msg) { + return this.demand(keys, max, msg); + } + require(keys, max, msg) { + return this.demand(keys, max, msg); + } + requiresArg(keys) { + argsert(' [number]', [keys], arguments.length); + if (typeof keys === 'string' && __classPrivateFieldGet(this, _YargsInstance_options, "f").narg[keys]) { + return this; + } + else { + this[kPopulateParserHintSingleValueDictionary](this.requiresArg.bind(this), 'narg', keys, NaN); + } + return this; + } + showCompletionScript($0, cmd) { + argsert('[string] [string]', [$0, cmd], arguments.length); + $0 = $0 || this.$0; + __classPrivateFieldGet(this, _YargsInstance_logger, "f").log(__classPrivateFieldGet(this, _YargsInstance_completion, "f").generateCompletionScript($0, cmd || __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f") || 'completion')); + return this; + } + showHelp(level) { + argsert('[string|function]', [level], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); + if (!__classPrivateFieldGet(this, _YargsInstance_usage, "f").hasCachedHelpMessage()) { + if (!this.parsed) { + const parse = this[kRunYargsParserAndExecuteCommands](__classPrivateFieldGet(this, _YargsInstance_processArgs, "f"), undefined, undefined, 0, true); + if (isPromise(parse)) { + parse.then(() => { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelp(level); + }); + return this; + } + } + const builderResponse = __classPrivateFieldGet(this, _YargsInstance_command, "f").runDefaultBuilderOn(this); + if (isPromise(builderResponse)) { + builderResponse.then(() => { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelp(level); + }); + return this; + } + } + __classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelp(level); + return this; + } + scriptName(scriptName) { + this.customScriptName = true; + this.$0 = scriptName; + return this; + } + showHelpOnFail(enabled, message) { + argsert('[boolean|string] [string]', [enabled, message], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelpOnFail(enabled, message); + return this; + } + showVersion(level) { + argsert('[string|function]', [level], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").showVersion(level); + return this; + } + skipValidation(keys) { + argsert('', [keys], arguments.length); + this[kPopulateParserHintArray]('skipValidation', keys); + return this; + } + strict(enabled) { + argsert('[boolean]', [enabled], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_strict, enabled !== false, "f"); + return this; + } + strictCommands(enabled) { + argsert('[boolean]', [enabled], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_strictCommands, enabled !== false, "f"); + return this; + } + strictOptions(enabled) { + argsert('[boolean]', [enabled], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_strictOptions, enabled !== false, "f"); + return this; + } + string(keys) { + argsert('', [keys], arguments.length); + this[kPopulateParserHintArray]('string', keys); + this[kTrackManuallySetKeys](keys); + return this; + } + terminalWidth() { + argsert([], 0); + return __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.stdColumns; + } + updateLocale(obj) { + return this.updateStrings(obj); + } + updateStrings(obj) { + argsert('', [obj], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_detectLocale, false, "f"); + __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.updateLocale(obj); + return this; + } + usage(msg, description, builder, handler) { + argsert(' [string|boolean] [function|object] [function]', [msg, description, builder, handler], arguments.length); + if (description !== undefined) { + assertNotStrictEqual(msg, null, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + if ((msg || '').match(/^\$0( |$)/)) { + return this.command(msg, description, builder, handler); + } + else { + throw new YError('.usage() description must start with $0 if being used as alias for .command()'); + } + } + else { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").usage(msg); + return this; + } + } + usageConfiguration(config) { + argsert('', [config], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_usageConfig, config, "f"); + return this; + } + version(opt, msg, ver) { + const defaultVersionOpt = 'version'; + argsert('[boolean|string] [string] [string]', [opt, msg, ver], arguments.length); + if (__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f")) { + this[kDeleteFromParserHintObject](__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f")); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").version(undefined); + __classPrivateFieldSet(this, _YargsInstance_versionOpt, null, "f"); + } + if (arguments.length === 0) { + ver = this[kGuessVersion](); + opt = defaultVersionOpt; + } + else if (arguments.length === 1) { + if (opt === false) { + return this; + } + ver = opt; + opt = defaultVersionOpt; + } + else if (arguments.length === 2) { + ver = msg; + msg = undefined; + } + __classPrivateFieldSet(this, _YargsInstance_versionOpt, typeof opt === 'string' ? opt : defaultVersionOpt, "f"); + msg = msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup('Show version number'); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").version(ver || undefined); + this.boolean(__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f")); + this.describe(__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f"), msg); + return this; + } + wrap(cols) { + argsert('', [cols], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").wrap(cols); + return this; + } + [(_YargsInstance_command = new WeakMap(), _YargsInstance_cwd = new WeakMap(), _YargsInstance_context = new WeakMap(), _YargsInstance_completion = new WeakMap(), _YargsInstance_completionCommand = new WeakMap(), _YargsInstance_defaultShowHiddenOpt = new WeakMap(), _YargsInstance_exitError = new WeakMap(), _YargsInstance_detectLocale = new WeakMap(), _YargsInstance_emittedWarnings = new WeakMap(), _YargsInstance_exitProcess = new WeakMap(), _YargsInstance_frozens = new WeakMap(), _YargsInstance_globalMiddleware = new WeakMap(), _YargsInstance_groups = new WeakMap(), _YargsInstance_hasOutput = new WeakMap(), _YargsInstance_helpOpt = new WeakMap(), _YargsInstance_isGlobalContext = new WeakMap(), _YargsInstance_logger = new WeakMap(), _YargsInstance_output = new WeakMap(), _YargsInstance_options = new WeakMap(), _YargsInstance_parentRequire = new WeakMap(), _YargsInstance_parserConfig = new WeakMap(), _YargsInstance_parseFn = new WeakMap(), _YargsInstance_parseContext = new WeakMap(), _YargsInstance_pkgs = new WeakMap(), _YargsInstance_preservedGroups = new WeakMap(), _YargsInstance_processArgs = new WeakMap(), _YargsInstance_recommendCommands = new WeakMap(), _YargsInstance_shim = new WeakMap(), _YargsInstance_strict = new WeakMap(), _YargsInstance_strictCommands = new WeakMap(), _YargsInstance_strictOptions = new WeakMap(), _YargsInstance_usage = new WeakMap(), _YargsInstance_usageConfig = new WeakMap(), _YargsInstance_versionOpt = new WeakMap(), _YargsInstance_validation = new WeakMap(), kCopyDoubleDash)](argv) { + if (!argv._ || !argv['--']) + return argv; + argv._.push.apply(argv._, argv['--']); + try { + delete argv['--']; + } + catch (_err) { } + return argv; + } + [kCreateLogger]() { + return { + log: (...args) => { + if (!this[kHasParseCallback]()) + console.log(...args); + __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); + if (__classPrivateFieldGet(this, _YargsInstance_output, "f").length) + __classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + '\n', "f"); + __classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + args.join(' '), "f"); + }, + error: (...args) => { + if (!this[kHasParseCallback]()) + console.error(...args); + __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); + if (__classPrivateFieldGet(this, _YargsInstance_output, "f").length) + __classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + '\n', "f"); + __classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + args.join(' '), "f"); + }, + }; + } + [kDeleteFromParserHintObject](optionKey) { + objectKeys(__classPrivateFieldGet(this, _YargsInstance_options, "f")).forEach((hintKey) => { + if (((key) => key === 'configObjects')(hintKey)) + return; + const hint = __classPrivateFieldGet(this, _YargsInstance_options, "f")[hintKey]; + if (Array.isArray(hint)) { + if (hint.includes(optionKey)) + hint.splice(hint.indexOf(optionKey), 1); + } + else if (typeof hint === 'object') { + delete hint[optionKey]; + } + }); + delete __classPrivateFieldGet(this, _YargsInstance_usage, "f").getDescriptions()[optionKey]; + } + [kEmitWarning](warning, type, deduplicationId) { + if (!__classPrivateFieldGet(this, _YargsInstance_emittedWarnings, "f")[deduplicationId]) { + __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.emitWarning(warning, type); + __classPrivateFieldGet(this, _YargsInstance_emittedWarnings, "f")[deduplicationId] = true; + } + } + [kFreeze]() { + __classPrivateFieldGet(this, _YargsInstance_frozens, "f").push({ + options: __classPrivateFieldGet(this, _YargsInstance_options, "f"), + configObjects: __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects.slice(0), + exitProcess: __classPrivateFieldGet(this, _YargsInstance_exitProcess, "f"), + groups: __classPrivateFieldGet(this, _YargsInstance_groups, "f"), + strict: __classPrivateFieldGet(this, _YargsInstance_strict, "f"), + strictCommands: __classPrivateFieldGet(this, _YargsInstance_strictCommands, "f"), + strictOptions: __classPrivateFieldGet(this, _YargsInstance_strictOptions, "f"), + completionCommand: __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f"), + output: __classPrivateFieldGet(this, _YargsInstance_output, "f"), + exitError: __classPrivateFieldGet(this, _YargsInstance_exitError, "f"), + hasOutput: __classPrivateFieldGet(this, _YargsInstance_hasOutput, "f"), + parsed: this.parsed, + parseFn: __classPrivateFieldGet(this, _YargsInstance_parseFn, "f"), + parseContext: __classPrivateFieldGet(this, _YargsInstance_parseContext, "f"), + }); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").freeze(); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").freeze(); + __classPrivateFieldGet(this, _YargsInstance_command, "f").freeze(); + __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").freeze(); + } + [kGetDollarZero]() { + let $0 = ''; + let default$0; + if (/\b(node|iojs|electron)(\.exe)?$/.test(__classPrivateFieldGet(this, _YargsInstance_shim, "f").process.argv()[0])) { + default$0 = __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.argv().slice(1, 2); + } + else { + default$0 = __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.argv().slice(0, 1); + } + $0 = default$0 + .map(x => { + const b = this[kRebase](__classPrivateFieldGet(this, _YargsInstance_cwd, "f"), x); + return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x; + }) + .join(' ') + .trim(); + if (__classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('_') && + __classPrivateFieldGet(this, _YargsInstance_shim, "f").getProcessArgvBin() === __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('_')) { + $0 = __classPrivateFieldGet(this, _YargsInstance_shim, "f") + .getEnv('_') + .replace(`${__classPrivateFieldGet(this, _YargsInstance_shim, "f").path.dirname(__classPrivateFieldGet(this, _YargsInstance_shim, "f").process.execPath())}/`, ''); + } + return $0; + } + [kGetParserConfiguration]() { + return __classPrivateFieldGet(this, _YargsInstance_parserConfig, "f"); + } + [kGetUsageConfiguration]() { + return __classPrivateFieldGet(this, _YargsInstance_usageConfig, "f"); + } + [kGuessLocale]() { + if (!__classPrivateFieldGet(this, _YargsInstance_detectLocale, "f")) + return; + const locale = __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('LC_ALL') || + __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('LC_MESSAGES') || + __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('LANG') || + __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('LANGUAGE') || + 'en_US'; + this.locale(locale.replace(/[.:].*/, '')); + } + [kGuessVersion]() { + const obj = this[kPkgUp](); + return obj.version || 'unknown'; + } + [kParsePositionalNumbers](argv) { + const args = argv['--'] ? argv['--'] : argv._; + for (let i = 0, arg; (arg = args[i]) !== undefined; i++) { + if (__classPrivateFieldGet(this, _YargsInstance_shim, "f").Parser.looksLikeNumber(arg) && + Number.isSafeInteger(Math.floor(parseFloat(`${arg}`)))) { + args[i] = Number(arg); + } + } + return argv; + } + [kPkgUp](rootPath) { + const npath = rootPath || '*'; + if (__classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath]) + return __classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath]; + let obj = {}; + try { + let startDir = rootPath || __classPrivateFieldGet(this, _YargsInstance_shim, "f").mainFilename; + if (!rootPath && __classPrivateFieldGet(this, _YargsInstance_shim, "f").path.extname(startDir)) { + startDir = __classPrivateFieldGet(this, _YargsInstance_shim, "f").path.dirname(startDir); + } + const pkgJsonPath = __classPrivateFieldGet(this, _YargsInstance_shim, "f").findUp(startDir, (dir, names) => { + if (names.includes('package.json')) { + return 'package.json'; + } + else { + return undefined; + } + }); + assertNotStrictEqual(pkgJsonPath, undefined, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + obj = JSON.parse(__classPrivateFieldGet(this, _YargsInstance_shim, "f").readFileSync(pkgJsonPath, 'utf8')); + } + catch (_noop) { } + __classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath] = obj || {}; + return __classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath]; + } + [kPopulateParserHintArray](type, keys) { + keys = [].concat(keys); + keys.forEach(key => { + key = this[kSanitizeKey](key); + __classPrivateFieldGet(this, _YargsInstance_options, "f")[type].push(key); + }); + } + [kPopulateParserHintSingleValueDictionary](builder, type, key, value) { + this[kPopulateParserHintDictionary](builder, type, key, value, (type, key, value) => { + __classPrivateFieldGet(this, _YargsInstance_options, "f")[type][key] = value; + }); + } + [kPopulateParserHintArrayDictionary](builder, type, key, value) { + this[kPopulateParserHintDictionary](builder, type, key, value, (type, key, value) => { + __classPrivateFieldGet(this, _YargsInstance_options, "f")[type][key] = (__classPrivateFieldGet(this, _YargsInstance_options, "f")[type][key] || []).concat(value); + }); + } + [kPopulateParserHintDictionary](builder, type, key, value, singleKeyHandler) { + if (Array.isArray(key)) { + key.forEach(k => { + builder(k, value); + }); + } + else if (((key) => typeof key === 'object')(key)) { + for (const k of objectKeys(key)) { + builder(k, key[k]); + } + } + else { + singleKeyHandler(type, this[kSanitizeKey](key), value); + } + } + [kSanitizeKey](key) { + if (key === '__proto__') + return '___proto___'; + return key; + } + [kSetKey](key, set) { + this[kPopulateParserHintSingleValueDictionary](this[kSetKey].bind(this), 'key', key, set); + return this; + } + [kUnfreeze]() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m; + const frozen = __classPrivateFieldGet(this, _YargsInstance_frozens, "f").pop(); + assertNotStrictEqual(frozen, undefined, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + let configObjects; + (_a = this, _b = this, _c = this, _d = this, _e = this, _f = this, _g = this, _h = this, _j = this, _k = this, _l = this, _m = this, { + options: ({ set value(_o) { __classPrivateFieldSet(_a, _YargsInstance_options, _o, "f"); } }).value, + configObjects, + exitProcess: ({ set value(_o) { __classPrivateFieldSet(_b, _YargsInstance_exitProcess, _o, "f"); } }).value, + groups: ({ set value(_o) { __classPrivateFieldSet(_c, _YargsInstance_groups, _o, "f"); } }).value, + output: ({ set value(_o) { __classPrivateFieldSet(_d, _YargsInstance_output, _o, "f"); } }).value, + exitError: ({ set value(_o) { __classPrivateFieldSet(_e, _YargsInstance_exitError, _o, "f"); } }).value, + hasOutput: ({ set value(_o) { __classPrivateFieldSet(_f, _YargsInstance_hasOutput, _o, "f"); } }).value, + parsed: this.parsed, + strict: ({ set value(_o) { __classPrivateFieldSet(_g, _YargsInstance_strict, _o, "f"); } }).value, + strictCommands: ({ set value(_o) { __classPrivateFieldSet(_h, _YargsInstance_strictCommands, _o, "f"); } }).value, + strictOptions: ({ set value(_o) { __classPrivateFieldSet(_j, _YargsInstance_strictOptions, _o, "f"); } }).value, + completionCommand: ({ set value(_o) { __classPrivateFieldSet(_k, _YargsInstance_completionCommand, _o, "f"); } }).value, + parseFn: ({ set value(_o) { __classPrivateFieldSet(_l, _YargsInstance_parseFn, _o, "f"); } }).value, + parseContext: ({ set value(_o) { __classPrivateFieldSet(_m, _YargsInstance_parseContext, _o, "f"); } }).value, + } = frozen); + __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects = configObjects; + __classPrivateFieldGet(this, _YargsInstance_usage, "f").unfreeze(); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").unfreeze(); + __classPrivateFieldGet(this, _YargsInstance_command, "f").unfreeze(); + __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").unfreeze(); + } + [kValidateAsync](validation, argv) { + return maybeAsyncResult(argv, result => { + validation(result); + return result; + }); + } + getInternalMethods() { + return { + getCommandInstance: this[kGetCommandInstance].bind(this), + getContext: this[kGetContext].bind(this), + getHasOutput: this[kGetHasOutput].bind(this), + getLoggerInstance: this[kGetLoggerInstance].bind(this), + getParseContext: this[kGetParseContext].bind(this), + getParserConfiguration: this[kGetParserConfiguration].bind(this), + getUsageConfiguration: this[kGetUsageConfiguration].bind(this), + getUsageInstance: this[kGetUsageInstance].bind(this), + getValidationInstance: this[kGetValidationInstance].bind(this), + hasParseCallback: this[kHasParseCallback].bind(this), + isGlobalContext: this[kIsGlobalContext].bind(this), + postProcess: this[kPostProcess].bind(this), + reset: this[kReset].bind(this), + runValidation: this[kRunValidation].bind(this), + runYargsParserAndExecuteCommands: this[kRunYargsParserAndExecuteCommands].bind(this), + setHasOutput: this[kSetHasOutput].bind(this), + }; + } + [kGetCommandInstance]() { + return __classPrivateFieldGet(this, _YargsInstance_command, "f"); + } + [kGetContext]() { + return __classPrivateFieldGet(this, _YargsInstance_context, "f"); + } + [kGetHasOutput]() { + return __classPrivateFieldGet(this, _YargsInstance_hasOutput, "f"); + } + [kGetLoggerInstance]() { + return __classPrivateFieldGet(this, _YargsInstance_logger, "f"); + } + [kGetParseContext]() { + return __classPrivateFieldGet(this, _YargsInstance_parseContext, "f") || {}; + } + [kGetUsageInstance]() { + return __classPrivateFieldGet(this, _YargsInstance_usage, "f"); + } + [kGetValidationInstance]() { + return __classPrivateFieldGet(this, _YargsInstance_validation, "f"); + } + [kHasParseCallback]() { + return !!__classPrivateFieldGet(this, _YargsInstance_parseFn, "f"); + } + [kIsGlobalContext]() { + return __classPrivateFieldGet(this, _YargsInstance_isGlobalContext, "f"); + } + [kPostProcess](argv, populateDoubleDash, calledFromCommand, runGlobalMiddleware) { + if (calledFromCommand) + return argv; + if (isPromise(argv)) + return argv; + if (!populateDoubleDash) { + argv = this[kCopyDoubleDash](argv); + } + const parsePositionalNumbers = this[kGetParserConfiguration]()['parse-positional-numbers'] || + this[kGetParserConfiguration]()['parse-positional-numbers'] === undefined; + if (parsePositionalNumbers) { + argv = this[kParsePositionalNumbers](argv); + } + if (runGlobalMiddleware) { + argv = applyMiddleware(argv, this, __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), false); + } + return argv; + } + [kReset](aliases = {}) { + __classPrivateFieldSet(this, _YargsInstance_options, __classPrivateFieldGet(this, _YargsInstance_options, "f") || {}, "f"); + const tmpOptions = {}; + tmpOptions.local = __classPrivateFieldGet(this, _YargsInstance_options, "f").local || []; + tmpOptions.configObjects = __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects || []; + const localLookup = {}; + tmpOptions.local.forEach(l => { + localLookup[l] = true; + (aliases[l] || []).forEach(a => { + localLookup[a] = true; + }); + }); + Object.assign(__classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f"), Object.keys(__classPrivateFieldGet(this, _YargsInstance_groups, "f")).reduce((acc, groupName) => { + const keys = __classPrivateFieldGet(this, _YargsInstance_groups, "f")[groupName].filter(key => !(key in localLookup)); + if (keys.length > 0) { + acc[groupName] = keys; + } + return acc; + }, {})); + __classPrivateFieldSet(this, _YargsInstance_groups, {}, "f"); + const arrayOptions = [ + 'array', + 'boolean', + 'string', + 'skipValidation', + 'count', + 'normalize', + 'number', + 'hiddenOptions', + ]; + const objectOptions = [ + 'narg', + 'key', + 'alias', + 'default', + 'defaultDescription', + 'config', + 'choices', + 'demandedOptions', + 'demandedCommands', + 'deprecatedOptions', + ]; + arrayOptions.forEach(k => { + tmpOptions[k] = (__classPrivateFieldGet(this, _YargsInstance_options, "f")[k] || []).filter((k) => !localLookup[k]); + }); + objectOptions.forEach((k) => { + tmpOptions[k] = objFilter(__classPrivateFieldGet(this, _YargsInstance_options, "f")[k], k => !localLookup[k]); + }); + tmpOptions.envPrefix = __classPrivateFieldGet(this, _YargsInstance_options, "f").envPrefix; + __classPrivateFieldSet(this, _YargsInstance_options, tmpOptions, "f"); + __classPrivateFieldSet(this, _YargsInstance_usage, __classPrivateFieldGet(this, _YargsInstance_usage, "f") + ? __classPrivateFieldGet(this, _YargsInstance_usage, "f").reset(localLookup) + : Usage(this, __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f"); + __classPrivateFieldSet(this, _YargsInstance_validation, __classPrivateFieldGet(this, _YargsInstance_validation, "f") + ? __classPrivateFieldGet(this, _YargsInstance_validation, "f").reset(localLookup) + : Validation(this, __classPrivateFieldGet(this, _YargsInstance_usage, "f"), __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f"); + __classPrivateFieldSet(this, _YargsInstance_command, __classPrivateFieldGet(this, _YargsInstance_command, "f") + ? __classPrivateFieldGet(this, _YargsInstance_command, "f").reset() + : Command(__classPrivateFieldGet(this, _YargsInstance_usage, "f"), __classPrivateFieldGet(this, _YargsInstance_validation, "f"), __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f"), __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f"); + if (!__classPrivateFieldGet(this, _YargsInstance_completion, "f")) + __classPrivateFieldSet(this, _YargsInstance_completion, Completion(this, __classPrivateFieldGet(this, _YargsInstance_usage, "f"), __classPrivateFieldGet(this, _YargsInstance_command, "f"), __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f"); + __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").reset(); + __classPrivateFieldSet(this, _YargsInstance_completionCommand, null, "f"); + __classPrivateFieldSet(this, _YargsInstance_output, '', "f"); + __classPrivateFieldSet(this, _YargsInstance_exitError, null, "f"); + __classPrivateFieldSet(this, _YargsInstance_hasOutput, false, "f"); + this.parsed = false; + return this; + } + [kRebase](base, dir) { + return __classPrivateFieldGet(this, _YargsInstance_shim, "f").path.relative(base, dir); + } + [kRunYargsParserAndExecuteCommands](args, shortCircuit, calledFromCommand, commandIndex = 0, helpOnly = false) { + let skipValidation = !!calledFromCommand || helpOnly; + args = args || __classPrivateFieldGet(this, _YargsInstance_processArgs, "f"); + __classPrivateFieldGet(this, _YargsInstance_options, "f").__ = __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.__; + __classPrivateFieldGet(this, _YargsInstance_options, "f").configuration = this[kGetParserConfiguration](); + const populateDoubleDash = !!__classPrivateFieldGet(this, _YargsInstance_options, "f").configuration['populate--']; + const config = Object.assign({}, __classPrivateFieldGet(this, _YargsInstance_options, "f").configuration, { + 'populate--': true, + }); + const parsed = __classPrivateFieldGet(this, _YargsInstance_shim, "f").Parser.detailed(args, Object.assign({}, __classPrivateFieldGet(this, _YargsInstance_options, "f"), { + configuration: { 'parse-positional-numbers': false, ...config }, + })); + const argv = Object.assign(parsed.argv, __classPrivateFieldGet(this, _YargsInstance_parseContext, "f")); + let argvPromise = undefined; + const aliases = parsed.aliases; + let helpOptSet = false; + let versionOptSet = false; + Object.keys(argv).forEach(key => { + if (key === __classPrivateFieldGet(this, _YargsInstance_helpOpt, "f") && argv[key]) { + helpOptSet = true; + } + else if (key === __classPrivateFieldGet(this, _YargsInstance_versionOpt, "f") && argv[key]) { + versionOptSet = true; + } + }); + argv.$0 = this.$0; + this.parsed = parsed; + if (commandIndex === 0) { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").clearCachedHelpMessage(); + } + try { + this[kGuessLocale](); + if (shortCircuit) { + return this[kPostProcess](argv, populateDoubleDash, !!calledFromCommand, false); + } + if (__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")) { + const helpCmds = [__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")] + .concat(aliases[__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")] || []) + .filter(k => k.length > 1); + if (helpCmds.includes('' + argv._[argv._.length - 1])) { + argv._.pop(); + helpOptSet = true; + } + } + __classPrivateFieldSet(this, _YargsInstance_isGlobalContext, false, "f"); + const handlerKeys = __classPrivateFieldGet(this, _YargsInstance_command, "f").getCommands(); + const requestCompletions = __classPrivateFieldGet(this, _YargsInstance_completion, "f").completionKey in argv; + const skipRecommendation = helpOptSet || requestCompletions || helpOnly; + if (argv._.length) { + if (handlerKeys.length) { + let firstUnknownCommand; + for (let i = commandIndex || 0, cmd; argv._[i] !== undefined; i++) { + cmd = String(argv._[i]); + if (handlerKeys.includes(cmd) && cmd !== __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f")) { + const innerArgv = __classPrivateFieldGet(this, _YargsInstance_command, "f").runCommand(cmd, this, parsed, i + 1, helpOnly, helpOptSet || versionOptSet || helpOnly); + return this[kPostProcess](innerArgv, populateDoubleDash, !!calledFromCommand, false); + } + else if (!firstUnknownCommand && + cmd !== __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f")) { + firstUnknownCommand = cmd; + break; + } + } + if (!__classPrivateFieldGet(this, _YargsInstance_command, "f").hasDefaultCommand() && + __classPrivateFieldGet(this, _YargsInstance_recommendCommands, "f") && + firstUnknownCommand && + !skipRecommendation) { + __classPrivateFieldGet(this, _YargsInstance_validation, "f").recommendCommands(firstUnknownCommand, handlerKeys); + } + } + if (__classPrivateFieldGet(this, _YargsInstance_completionCommand, "f") && + argv._.includes(__classPrivateFieldGet(this, _YargsInstance_completionCommand, "f")) && + !requestCompletions) { + if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f")) + setBlocking(true); + this.showCompletionScript(); + this.exit(0); + } + } + if (__classPrivateFieldGet(this, _YargsInstance_command, "f").hasDefaultCommand() && !skipRecommendation) { + const innerArgv = __classPrivateFieldGet(this, _YargsInstance_command, "f").runCommand(null, this, parsed, 0, helpOnly, helpOptSet || versionOptSet || helpOnly); + return this[kPostProcess](innerArgv, populateDoubleDash, !!calledFromCommand, false); + } + if (requestCompletions) { + if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f")) + setBlocking(true); + args = [].concat(args); + const completionArgs = args.slice(args.indexOf(`--${__classPrivateFieldGet(this, _YargsInstance_completion, "f").completionKey}`) + 1); + __classPrivateFieldGet(this, _YargsInstance_completion, "f").getCompletion(completionArgs, (err, completions) => { + if (err) + throw new YError(err.message); + (completions || []).forEach(completion => { + __classPrivateFieldGet(this, _YargsInstance_logger, "f").log(completion); + }); + this.exit(0); + }); + return this[kPostProcess](argv, !populateDoubleDash, !!calledFromCommand, false); + } + if (!__classPrivateFieldGet(this, _YargsInstance_hasOutput, "f")) { + if (helpOptSet) { + if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f")) + setBlocking(true); + skipValidation = true; + this.showHelp('log'); + this.exit(0); + } + else if (versionOptSet) { + if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f")) + setBlocking(true); + skipValidation = true; + __classPrivateFieldGet(this, _YargsInstance_usage, "f").showVersion('log'); + this.exit(0); + } + } + if (!skipValidation && __classPrivateFieldGet(this, _YargsInstance_options, "f").skipValidation.length > 0) { + skipValidation = Object.keys(argv).some(key => __classPrivateFieldGet(this, _YargsInstance_options, "f").skipValidation.indexOf(key) >= 0 && argv[key] === true); + } + if (!skipValidation) { + if (parsed.error) + throw new YError(parsed.error.message); + if (!requestCompletions) { + const validation = this[kRunValidation](aliases, {}, parsed.error); + if (!calledFromCommand) { + argvPromise = applyMiddleware(argv, this, __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), true); + } + argvPromise = this[kValidateAsync](validation, argvPromise !== null && argvPromise !== void 0 ? argvPromise : argv); + if (isPromise(argvPromise) && !calledFromCommand) { + argvPromise = argvPromise.then(() => { + return applyMiddleware(argv, this, __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), false); + }); + } + } + } + } + catch (err) { + if (err instanceof YError) + __classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(err.message, err); + else + throw err; + } + return this[kPostProcess](argvPromise !== null && argvPromise !== void 0 ? argvPromise : argv, populateDoubleDash, !!calledFromCommand, true); + } + [kRunValidation](aliases, positionalMap, parseErrors, isDefaultCommand) { + const demandedOptions = { ...this.getDemandedOptions() }; + return (argv) => { + if (parseErrors) + throw new YError(parseErrors.message); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").nonOptionCount(argv); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").requiredArguments(argv, demandedOptions); + let failedStrictCommands = false; + if (__classPrivateFieldGet(this, _YargsInstance_strictCommands, "f")) { + failedStrictCommands = __classPrivateFieldGet(this, _YargsInstance_validation, "f").unknownCommands(argv); + } + if (__classPrivateFieldGet(this, _YargsInstance_strict, "f") && !failedStrictCommands) { + __classPrivateFieldGet(this, _YargsInstance_validation, "f").unknownArguments(argv, aliases, positionalMap, !!isDefaultCommand); + } + else if (__classPrivateFieldGet(this, _YargsInstance_strictOptions, "f")) { + __classPrivateFieldGet(this, _YargsInstance_validation, "f").unknownArguments(argv, aliases, {}, false, false); + } + __classPrivateFieldGet(this, _YargsInstance_validation, "f").limitedChoices(argv); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").implications(argv); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").conflicting(argv); + }; + } + [kSetHasOutput]() { + __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); + } + [kTrackManuallySetKeys](keys) { + if (typeof keys === 'string') { + __classPrivateFieldGet(this, _YargsInstance_options, "f").key[keys] = true; + } + else { + for (const k of keys) { + __classPrivateFieldGet(this, _YargsInstance_options, "f").key[k] = true; + } + } + } +} +export function isYargsInstance(y) { + return !!y && typeof y.getInternalMethods === 'function'; +} diff --git a/node_modules/yargs/build/lib/yerror.js b/node_modules/yargs/build/lib/yerror.js new file mode 100644 index 0000000000000000000000000000000000000000..7a36684da8dbfb687f8d8dacfd69fbd8e1dab931 --- /dev/null +++ b/node_modules/yargs/build/lib/yerror.js @@ -0,0 +1,9 @@ +export class YError extends Error { + constructor(msg) { + super(msg || 'yargs error'); + this.name = 'YError'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, YError); + } + } +} diff --git a/node_modules/yargs/helpers/helpers.mjs b/node_modules/yargs/helpers/helpers.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3f96b3db80ff7a486abaca3683947a54b659a2e2 --- /dev/null +++ b/node_modules/yargs/helpers/helpers.mjs @@ -0,0 +1,10 @@ +import {applyExtends as _applyExtends} from '../build/lib/utils/apply-extends.js'; +import {hideBin} from '../build/lib/utils/process-argv.js'; +import Parser from 'yargs-parser'; +import shim from '../lib/platform-shims/esm.mjs'; + +const applyExtends = (config, cwd, mergeExtends) => { + return _applyExtends(config, cwd, mergeExtends, shim); +}; + +export {applyExtends, hideBin, Parser}; diff --git a/node_modules/yargs/helpers/index.js b/node_modules/yargs/helpers/index.js new file mode 100644 index 0000000000000000000000000000000000000000..8ab79a33774dbe17147d469c454d5e59e45d2c73 --- /dev/null +++ b/node_modules/yargs/helpers/index.js @@ -0,0 +1,14 @@ +const { + applyExtends, + cjsPlatformShim, + Parser, + processArgv, +} = require('../build/index.cjs'); + +module.exports = { + applyExtends: (config, cwd, mergeExtends) => { + return applyExtends(config, cwd, mergeExtends, cjsPlatformShim); + }, + hideBin: processArgv.hideBin, + Parser, +}; diff --git a/node_modules/yargs/helpers/package.json b/node_modules/yargs/helpers/package.json new file mode 100644 index 0000000000000000000000000000000000000000..5bbefffbabee392d1855491b84dc0a716b6a3bf2 --- /dev/null +++ b/node_modules/yargs/helpers/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/node_modules/yargs/index.cjs b/node_modules/yargs/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..d1eee821e7dced093633caa40c29558ec2f5f93a --- /dev/null +++ b/node_modules/yargs/index.cjs @@ -0,0 +1,53 @@ +'use strict'; +// classic singleton yargs API, to use yargs +// without running as a singleton do: +// require('yargs/yargs')(process.argv.slice(2)) +const {Yargs, processArgv} = require('./build/index.cjs'); + +Argv(processArgv.hideBin(process.argv)); + +module.exports = Argv; + +function Argv(processArgs, cwd) { + const argv = Yargs(processArgs, cwd, require); + singletonify(argv); + // TODO(bcoe): warn if argv.parse() or argv.argv is used directly. + return argv; +} + +function defineGetter(obj, key, getter) { + Object.defineProperty(obj, key, { + configurable: true, + enumerable: true, + get: getter, + }); +} +function lookupGetter(obj, key) { + const desc = Object.getOwnPropertyDescriptor(obj, key); + if (typeof desc !== 'undefined') { + return desc.get; + } +} + +/* Hack an instance of Argv with process.argv into Argv + so people can do + require('yargs')(['--beeble=1','-z','zizzle']).argv + to parse a list of args and + require('yargs').argv + to get a parsed version of process.argv. +*/ +function singletonify(inst) { + [ + ...Object.keys(inst), + ...Object.getOwnPropertyNames(inst.constructor.prototype), + ].forEach(key => { + if (key === 'argv') { + defineGetter(Argv, key, lookupGetter(inst, key)); + } else if (typeof inst[key] === 'function') { + Argv[key] = inst[key].bind(inst); + } else { + defineGetter(Argv, '$0', () => inst.$0); + defineGetter(Argv, 'parsed', () => inst.parsed); + } + }); +} diff --git a/node_modules/yargs/index.mjs b/node_modules/yargs/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c6440b9edca315488f1976061edf88803ecac954 --- /dev/null +++ b/node_modules/yargs/index.mjs @@ -0,0 +1,8 @@ +'use strict'; + +// Bootstraps yargs for ESM: +import esmPlatformShim from './lib/platform-shims/esm.mjs'; +import {YargsFactory} from './build/lib/yargs-factory.js'; + +const Yargs = YargsFactory(esmPlatformShim); +export default Yargs; diff --git a/node_modules/yargs/lib/platform-shims/browser.mjs b/node_modules/yargs/lib/platform-shims/browser.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5f8ec61f449a10d0281268b409cf026da6468333 --- /dev/null +++ b/node_modules/yargs/lib/platform-shims/browser.mjs @@ -0,0 +1,95 @@ +/* eslint-disable no-unused-vars */ +'use strict'; + +import cliui from 'https://unpkg.com/cliui@7.0.1/index.mjs'; // eslint-disable-line +import Parser from 'https://unpkg.com/yargs-parser@19.0.0/browser.js'; // eslint-disable-line +import {getProcessArgvBin} from '../../build/lib/utils/process-argv.js'; +import {YError} from '../../build/lib/yerror.js'; + +const REQUIRE_ERROR = 'require is not supported in browser'; +const REQUIRE_DIRECTORY_ERROR = + 'loading a directory of commands is not supported in browser'; + +export default { + assert: { + notStrictEqual: (a, b) => { + // noop. + }, + strictEqual: (a, b) => { + // noop. + }, + }, + cliui, + findUp: () => undefined, + getEnv: key => { + // There is no environment in browser: + return undefined; + }, + inspect: console.log, + getCallerFile: () => { + throw new YError(REQUIRE_DIRECTORY_ERROR); + }, + getProcessArgvBin, + mainFilename: 'yargs', + Parser, + path: { + basename: str => str, + dirname: str => str, + extname: str => str, + relative: str => str, + }, + process: { + argv: () => [], + cwd: () => '', + emitWarning: (warning, name) => {}, + execPath: () => '', + // exit is noop browser: + exit: () => {}, + nextTick: cb => { + // eslint-disable-next-line no-undef + window.setTimeout(cb, 1); + }, + stdColumns: 80, + }, + readFileSync: () => { + return ''; + }, + require: () => { + throw new YError(REQUIRE_ERROR); + }, + requireDirectory: () => { + throw new YError(REQUIRE_DIRECTORY_ERROR); + }, + stringWidth: str => { + return [...str].length; + }, + // TODO: replace this with y18n once it's ported to ESM: + y18n: { + __: (...str) => { + if (str.length === 0) return ''; + const args = str.slice(1); + return sprintf(str[0], ...args); + }, + __n: (str1, str2, count, ...args) => { + if (count === 1) { + return sprintf(str1, ...args); + } else { + return sprintf(str2, ...args); + } + }, + getLocale: () => { + return 'en_US'; + }, + setLocale: () => {}, + updateLocale: () => {}, + }, +}; + +function sprintf(_str, ...args) { + let str = ''; + const split = _str.split('%s'); + split.forEach((token, i) => { + str += `${token}${split[i + 1] !== undefined && args[i] ? args[i] : ''}`; + }); + return str; +} diff --git a/node_modules/yargs/lib/platform-shims/esm.mjs b/node_modules/yargs/lib/platform-shims/esm.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c25baa5a31572f4f296254d95cebe749b6085be3 --- /dev/null +++ b/node_modules/yargs/lib/platform-shims/esm.mjs @@ -0,0 +1,73 @@ +'use strict' + +import { notStrictEqual, strictEqual } from 'assert' +import cliui from 'cliui' +import escalade from 'escalade/sync' +import { inspect } from 'util' +import { readFileSync } from 'fs' +import { fileURLToPath } from 'url'; +import Parser from 'yargs-parser' +import { basename, dirname, extname, relative, resolve } from 'path' +import { getProcessArgvBin } from '../../build/lib/utils/process-argv.js' +import { YError } from '../../build/lib/yerror.js' +import y18n from 'y18n' + +const REQUIRE_ERROR = 'require is not supported by ESM' +const REQUIRE_DIRECTORY_ERROR = 'loading a directory of commands is not supported yet for ESM' + +let __dirname; +try { + __dirname = fileURLToPath(import.meta.url); +} catch (e) { + __dirname = process.cwd(); +} +const mainFilename = __dirname.substring(0, __dirname.lastIndexOf('node_modules')); + +export default { + assert: { + notStrictEqual, + strictEqual + }, + cliui, + findUp: escalade, + getEnv: (key) => { + return process.env[key] + }, + inspect, + getCallerFile: () => { + throw new YError(REQUIRE_DIRECTORY_ERROR) + }, + getProcessArgvBin, + mainFilename: mainFilename || process.cwd(), + Parser, + path: { + basename, + dirname, + extname, + relative, + resolve + }, + process: { + argv: () => process.argv, + cwd: process.cwd, + emitWarning: (warning, type) => process.emitWarning(warning, type), + execPath: () => process.execPath, + exit: process.exit, + nextTick: process.nextTick, + stdColumns: typeof process.stdout.columns !== 'undefined' ? process.stdout.columns : null + }, + readFileSync, + require: () => { + throw new YError(REQUIRE_ERROR) + }, + requireDirectory: () => { + throw new YError(REQUIRE_DIRECTORY_ERROR) + }, + stringWidth: (str) => { + return [...str].length + }, + y18n: y18n({ + directory: resolve(__dirname, '../../../locales'), + updateFiles: false + }) +} diff --git a/node_modules/yargs/locales/be.json b/node_modules/yargs/locales/be.json new file mode 100644 index 0000000000000000000000000000000000000000..e28fa30139366dfd6e5f1a603149aae590912775 --- /dev/null +++ b/node_modules/yargs/locales/be.json @@ -0,0 +1,46 @@ +{ + "Commands:": "Каманды:", + "Options:": "Опцыі:", + "Examples:": "Прыклады:", + "boolean": "булевы тып", + "count": "падлік", + "string": "радковы тып", + "number": "лік", + "array": "масіў", + "required": "неабходна", + "default": "па змаўчанні", + "default:": "па змаўчанні:", + "choices:": "магчымасці:", + "aliases:": "аліасы:", + "generated-value": "згенераванае значэнне", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Недастаткова неапцыйных аргументаў: ёсць %s, трэба як мінімум %s", + "other": "Недастаткова неапцыйных аргументаў: ёсць %s, трэба як мінімум %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Занадта шмат неапцыйных аргументаў: ёсць %s, максімум дапушчальна %s", + "other": "Занадта шмат неапцыйных аргументаў: ёсць %s, максімум дапушчальна %s" + }, + "Missing argument value: %s": { + "one": "Не хапае значэння аргументу: %s", + "other": "Не хапае значэнняў аргументаў: %s" + }, + "Missing required argument: %s": { + "one": "Не хапае неабходнага аргументу: %s", + "other": "Не хапае неабходных аргументаў: %s" + }, + "Unknown argument: %s": { + "one": "Невядомы аргумент: %s", + "other": "Невядомыя аргументы: %s" + }, + "Invalid values:": "Несапраўдныя значэння:", + "Argument: %s, Given: %s, Choices: %s": "Аргумент: %s, Дадзенае значэнне: %s, Магчымасці: %s", + "Argument check failed: %s": "Праверка аргументаў не ўдалася: %s", + "Implications failed:": "Дадзены аргумент патрабуе наступны дадатковы аргумент:", + "Not enough arguments following: %s": "Недастаткова наступных аргументаў: %s", + "Invalid JSON config file: %s": "Несапраўдны файл канфігурацыі JSON: %s", + "Path to JSON config file": "Шлях да файла канфігурацыі JSON", + "Show help": "Паказаць дапамогу", + "Show version number": "Паказаць нумар версіі", + "Did you mean %s?": "Вы мелі на ўвазе %s?" +} diff --git a/node_modules/yargs/locales/cs.json b/node_modules/yargs/locales/cs.json new file mode 100644 index 0000000000000000000000000000000000000000..6394875647e85093fdf5f677a7dafe73db04983e --- /dev/null +++ b/node_modules/yargs/locales/cs.json @@ -0,0 +1,51 @@ +{ + "Commands:": "Příkazy:", + "Options:": "Možnosti:", + "Examples:": "Příklady:", + "boolean": "logická hodnota", + "count": "počet", + "string": "řetězec", + "number": "číslo", + "array": "pole", + "required": "povinné", + "default": "výchozí", + "default:": "výchozí:", + "choices:": "volby:", + "aliases:": "aliasy:", + "generated-value": "generovaná-hodnota", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Nedostatek argumentů: zadáno %s, je potřeba alespoň %s", + "other": "Nedostatek argumentů: zadáno %s, je potřeba alespoň %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Příliš mnoho argumentů: zadáno %s, maximálně %s", + "other": "Příliš mnoho argumentů: zadáno %s, maximálně %s" + }, + "Missing argument value: %s": { + "one": "Chybí hodnota argumentu: %s", + "other": "Chybí hodnoty argumentů: %s" + }, + "Missing required argument: %s": { + "one": "Chybí požadovaný argument: %s", + "other": "Chybí požadované argumenty: %s" + }, + "Unknown argument: %s": { + "one": "Neznámý argument: %s", + "other": "Neznámé argumenty: %s" + }, + "Invalid values:": "Neplatné hodnoty:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Zadáno: %s, Možnosti: %s", + "Argument check failed: %s": "Kontrola argumentů se nezdařila: %s", + "Implications failed:": "Chybí závislé argumenty:", + "Not enough arguments following: %s": "Následuje nedostatek argumentů: %s", + "Invalid JSON config file: %s": "Neplatný konfigurační soubor JSON: %s", + "Path to JSON config file": "Cesta ke konfiguračnímu souboru JSON", + "Show help": "Zobrazit nápovědu", + "Show version number": "Zobrazit číslo verze", + "Did you mean %s?": "Měl jste na mysli %s?", + "Arguments %s and %s are mutually exclusive" : "Argumenty %s a %s se vzájemně vylučují", + "Positionals:": "Poziční:", + "command": "příkaz", + "deprecated": "zastaralé", + "deprecated: %s": "zastaralé: %s" +} diff --git a/node_modules/yargs/locales/de.json b/node_modules/yargs/locales/de.json new file mode 100644 index 0000000000000000000000000000000000000000..dc73ec3f020738a423cd079ed80cbbc43c353830 --- /dev/null +++ b/node_modules/yargs/locales/de.json @@ -0,0 +1,46 @@ +{ + "Commands:": "Kommandos:", + "Options:": "Optionen:", + "Examples:": "Beispiele:", + "boolean": "boolean", + "count": "Zähler", + "string": "string", + "number": "Zahl", + "array": "array", + "required": "erforderlich", + "default": "Standard", + "default:": "Standard:", + "choices:": "Möglichkeiten:", + "aliases:": "Aliase:", + "generated-value": "Generierter-Wert", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Nicht genügend Argumente ohne Optionen: %s vorhanden, mindestens %s benötigt", + "other": "Nicht genügend Argumente ohne Optionen: %s vorhanden, mindestens %s benötigt" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Zu viele Argumente ohne Optionen: %s vorhanden, maximal %s erlaubt", + "other": "Zu viele Argumente ohne Optionen: %s vorhanden, maximal %s erlaubt" + }, + "Missing argument value: %s": { + "one": "Fehlender Argumentwert: %s", + "other": "Fehlende Argumentwerte: %s" + }, + "Missing required argument: %s": { + "one": "Fehlendes Argument: %s", + "other": "Fehlende Argumente: %s" + }, + "Unknown argument: %s": { + "one": "Unbekanntes Argument: %s", + "other": "Unbekannte Argumente: %s" + }, + "Invalid values:": "Unzulässige Werte:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Gegeben: %s, Möglichkeiten: %s", + "Argument check failed: %s": "Argumente-Check fehlgeschlagen: %s", + "Implications failed:": "Fehlende abhängige Argumente:", + "Not enough arguments following: %s": "Nicht genügend Argumente nach: %s", + "Invalid JSON config file: %s": "Fehlerhafte JSON-Config Datei: %s", + "Path to JSON config file": "Pfad zur JSON-Config Datei", + "Show help": "Hilfe anzeigen", + "Show version number": "Version anzeigen", + "Did you mean %s?": "Meintest du %s?" +} diff --git a/node_modules/yargs/locales/en.json b/node_modules/yargs/locales/en.json new file mode 100644 index 0000000000000000000000000000000000000000..af096a110a2df76bee8e605b3b380c8490aa4959 --- /dev/null +++ b/node_modules/yargs/locales/en.json @@ -0,0 +1,55 @@ +{ + "Commands:": "Commands:", + "Options:": "Options:", + "Examples:": "Examples:", + "boolean": "boolean", + "count": "count", + "string": "string", + "number": "number", + "array": "array", + "required": "required", + "default": "default", + "default:": "default:", + "choices:": "choices:", + "aliases:": "aliases:", + "generated-value": "generated-value", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Not enough non-option arguments: got %s, need at least %s", + "other": "Not enough non-option arguments: got %s, need at least %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Too many non-option arguments: got %s, maximum of %s", + "other": "Too many non-option arguments: got %s, maximum of %s" + }, + "Missing argument value: %s": { + "one": "Missing argument value: %s", + "other": "Missing argument values: %s" + }, + "Missing required argument: %s": { + "one": "Missing required argument: %s", + "other": "Missing required arguments: %s" + }, + "Unknown argument: %s": { + "one": "Unknown argument: %s", + "other": "Unknown arguments: %s" + }, + "Unknown command: %s": { + "one": "Unknown command: %s", + "other": "Unknown commands: %s" + }, + "Invalid values:": "Invalid values:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Given: %s, Choices: %s", + "Argument check failed: %s": "Argument check failed: %s", + "Implications failed:": "Missing dependent arguments:", + "Not enough arguments following: %s": "Not enough arguments following: %s", + "Invalid JSON config file: %s": "Invalid JSON config file: %s", + "Path to JSON config file": "Path to JSON config file", + "Show help": "Show help", + "Show version number": "Show version number", + "Did you mean %s?": "Did you mean %s?", + "Arguments %s and %s are mutually exclusive" : "Arguments %s and %s are mutually exclusive", + "Positionals:": "Positionals:", + "command": "command", + "deprecated": "deprecated", + "deprecated: %s": "deprecated: %s" +} diff --git a/node_modules/yargs/locales/es.json b/node_modules/yargs/locales/es.json new file mode 100644 index 0000000000000000000000000000000000000000..d77b4616a211fea5f553a8c8aa5c89153e87f6d7 --- /dev/null +++ b/node_modules/yargs/locales/es.json @@ -0,0 +1,46 @@ +{ + "Commands:": "Comandos:", + "Options:": "Opciones:", + "Examples:": "Ejemplos:", + "boolean": "booleano", + "count": "cuenta", + "string": "cadena de caracteres", + "number": "número", + "array": "tabla", + "required": "requerido", + "default": "defecto", + "default:": "defecto:", + "choices:": "selección:", + "aliases:": "alias:", + "generated-value": "valor-generado", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Hacen falta argumentos no-opcionales: Número recibido %s, necesita por lo menos %s", + "other": "Hacen falta argumentos no-opcionales: Número recibido %s, necesita por lo menos %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Demasiados argumentos no-opcionales: Número recibido %s, máximo es %s", + "other": "Demasiados argumentos no-opcionales: Número recibido %s, máximo es %s" + }, + "Missing argument value: %s": { + "one": "Falta argumento: %s", + "other": "Faltan argumentos: %s" + }, + "Missing required argument: %s": { + "one": "Falta argumento requerido: %s", + "other": "Faltan argumentos requeridos: %s" + }, + "Unknown argument: %s": { + "one": "Argumento desconocido: %s", + "other": "Argumentos desconocidos: %s" + }, + "Invalid values:": "Valores inválidos:", + "Argument: %s, Given: %s, Choices: %s": "Argumento: %s, Recibido: %s, Seleccionados: %s", + "Argument check failed: %s": "Verificación de argumento ha fallado: %s", + "Implications failed:": "Implicaciones fallidas:", + "Not enough arguments following: %s": "No hay suficientes argumentos después de: %s", + "Invalid JSON config file: %s": "Archivo de configuración JSON inválido: %s", + "Path to JSON config file": "Ruta al archivo de configuración JSON", + "Show help": "Muestra ayuda", + "Show version number": "Muestra número de versión", + "Did you mean %s?": "Quisiste decir %s?" +} diff --git a/node_modules/yargs/locales/fi.json b/node_modules/yargs/locales/fi.json new file mode 100644 index 0000000000000000000000000000000000000000..481feb710a199af1660685a2cf93cac5306da3d1 --- /dev/null +++ b/node_modules/yargs/locales/fi.json @@ -0,0 +1,49 @@ +{ + "Commands:": "Komennot:", + "Options:": "Valinnat:", + "Examples:": "Esimerkkejä:", + "boolean": "totuusarvo", + "count": "lukumäärä", + "string": "merkkijono", + "number": "numero", + "array": "taulukko", + "required": "pakollinen", + "default": "oletusarvo", + "default:": "oletusarvo:", + "choices:": "vaihtoehdot:", + "aliases:": "aliakset:", + "generated-value": "generoitu-arvo", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Liian vähän argumentteja, jotka eivät ole valintoja: annettu %s, vaaditaan vähintään %s", + "other": "Liian vähän argumentteja, jotka eivät ole valintoja: annettu %s, vaaditaan vähintään %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Liikaa argumentteja, jotka eivät ole valintoja: annettu %s, sallitaan enintään %s", + "other": "Liikaa argumentteja, jotka eivät ole valintoja: annettu %s, sallitaan enintään %s" + }, + "Missing argument value: %s": { + "one": "Argumentin arvo puuttuu: %s", + "other": "Argumentin arvot puuttuvat: %s" + }, + "Missing required argument: %s": { + "one": "Pakollinen argumentti puuttuu: %s", + "other": "Pakollisia argumentteja puuttuu: %s" + }, + "Unknown argument: %s": { + "one": "Tuntematon argumentti: %s", + "other": "Tuntemattomia argumentteja: %s" + }, + "Invalid values:": "Virheelliset arvot:", + "Argument: %s, Given: %s, Choices: %s": "Argumentti: %s, Annettu: %s, Vaihtoehdot: %s", + "Argument check failed: %s": "Argumentin tarkistus epäonnistui: %s", + "Implications failed:": "Riippuvia argumentteja puuttuu:", + "Not enough arguments following: %s": "Argumentin perässä ei ole tarpeeksi argumentteja: %s", + "Invalid JSON config file: %s": "Epävalidi JSON-asetustiedosto: %s", + "Path to JSON config file": "JSON-asetustiedoston polku", + "Show help": "Näytä ohje", + "Show version number": "Näytä versionumero", + "Did you mean %s?": "Tarkoititko %s?", + "Arguments %s and %s are mutually exclusive" : "Argumentit %s ja %s eivät ole yhteensopivat", + "Positionals:": "Sijaintiparametrit:", + "command": "komento" +} diff --git a/node_modules/yargs/locales/fr.json b/node_modules/yargs/locales/fr.json new file mode 100644 index 0000000000000000000000000000000000000000..edd743f0c9420a67f020bece655987c7e9b66781 --- /dev/null +++ b/node_modules/yargs/locales/fr.json @@ -0,0 +1,53 @@ +{ + "Commands:": "Commandes :", + "Options:": "Options :", + "Examples:": "Exemples :", + "boolean": "booléen", + "count": "compteur", + "string": "chaîne de caractères", + "number": "nombre", + "array": "tableau", + "required": "requis", + "default": "défaut", + "default:": "défaut :", + "choices:": "choix :", + "aliases:": "alias :", + "generated-value": "valeur générée", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Pas assez d'arguments (hors options) : reçu %s, besoin d'au moins %s", + "other": "Pas assez d'arguments (hors options) : reçus %s, besoin d'au moins %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Trop d'arguments (hors options) : reçu %s, maximum de %s", + "other": "Trop d'arguments (hors options) : reçus %s, maximum de %s" + }, + "Missing argument value: %s": { + "one": "Argument manquant : %s", + "other": "Arguments manquants : %s" + }, + "Missing required argument: %s": { + "one": "Argument requis manquant : %s", + "other": "Arguments requis manquants : %s" + }, + "Unknown argument: %s": { + "one": "Argument inconnu : %s", + "other": "Arguments inconnus : %s" + }, + "Unknown command: %s": { + "one": "Commande inconnue : %s", + "other": "Commandes inconnues : %s" + }, + "Invalid values:": "Valeurs invalides :", + "Argument: %s, Given: %s, Choices: %s": "Argument : %s, donné : %s, choix : %s", + "Argument check failed: %s": "Echec de la vérification de l'argument : %s", + "Implications failed:": "Arguments dépendants manquants :", + "Not enough arguments following: %s": "Pas assez d'arguments après : %s", + "Invalid JSON config file: %s": "Fichier de configuration JSON invalide : %s", + "Path to JSON config file": "Chemin du fichier de configuration JSON", + "Show help": "Affiche l'aide", + "Show version number": "Affiche le numéro de version", + "Did you mean %s?": "Vouliez-vous dire %s ?", + "Arguments %s and %s are mutually exclusive" : "Les arguments %s et %s sont mutuellement exclusifs", + "Positionals:": "Arguments positionnels :", + "command": "commande" +} diff --git a/node_modules/yargs/locales/hi.json b/node_modules/yargs/locales/hi.json new file mode 100644 index 0000000000000000000000000000000000000000..a9de77cce1546c088ea42925cdd5cd642f42f3de --- /dev/null +++ b/node_modules/yargs/locales/hi.json @@ -0,0 +1,49 @@ +{ + "Commands:": "आदेश:", + "Options:": "विकल्प:", + "Examples:": "उदाहरण:", + "boolean": "सत्यता", + "count": "संख्या", + "string": "वर्णों का तार ", + "number": "अंक", + "array": "सरणी", + "required": "आवश्यक", + "default": "डिफॉल्ट", + "default:": "डिफॉल्ट:", + "choices:": "विकल्प:", + "aliases:": "उपनाम:", + "generated-value": "उत्पन्न-मूल्य", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "पर्याप्त गैर-विकल्प तर्क प्राप्त नहीं: %s प्राप्त, कम से कम %s की आवश्यकता है", + "other": "पर्याप्त गैर-विकल्प तर्क प्राप्त नहीं: %s प्राप्त, कम से कम %s की आवश्यकता है" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "बहुत सारे गैर-विकल्प तर्क: %s प्राप्त, अधिकतम %s मान्य", + "other": "बहुत सारे गैर-विकल्प तर्क: %s प्राप्त, अधिकतम %s मान्य" + }, + "Missing argument value: %s": { + "one": "कुछ तर्को के मूल्य गुम हैं: %s", + "other": "कुछ तर्को के मूल्य गुम हैं: %s" + }, + "Missing required argument: %s": { + "one": "आवश्यक तर्क गुम हैं: %s", + "other": "आवश्यक तर्क गुम हैं: %s" + }, + "Unknown argument: %s": { + "one": "अज्ञात तर्क प्राप्त: %s", + "other": "अज्ञात तर्क प्राप्त: %s" + }, + "Invalid values:": "अमान्य मूल्य:", + "Argument: %s, Given: %s, Choices: %s": "तर्क: %s, प्राप्त: %s, विकल्प: %s", + "Argument check failed: %s": "तर्क जांच विफल: %s", + "Implications failed:": "दिए गए तर्क के लिए अतिरिक्त तर्क की अपेक्षा है:", + "Not enough arguments following: %s": "निम्नलिखित के बाद पर्याप्त तर्क नहीं प्राप्त: %s", + "Invalid JSON config file: %s": "अमान्य JSON config फाइल: %s", + "Path to JSON config file": "JSON config फाइल का पथ", + "Show help": "सहायता दिखाएँ", + "Show version number": "Version संख्या दिखाएँ", + "Did you mean %s?": "क्या आपका मतलब है %s?", + "Arguments %s and %s are mutually exclusive" : "तर्क %s और %s परस्पर अनन्य हैं", + "Positionals:": "स्थानीय:", + "command": "आदेश" +} diff --git a/node_modules/yargs/locales/hu.json b/node_modules/yargs/locales/hu.json new file mode 100644 index 0000000000000000000000000000000000000000..21492d05a7c84e9e08b05459d51d6ad37088d012 --- /dev/null +++ b/node_modules/yargs/locales/hu.json @@ -0,0 +1,46 @@ +{ + "Commands:": "Parancsok:", + "Options:": "Opciók:", + "Examples:": "Példák:", + "boolean": "boolean", + "count": "számláló", + "string": "szöveg", + "number": "szám", + "array": "tömb", + "required": "kötelező", + "default": "alapértelmezett", + "default:": "alapértelmezett:", + "choices:": "lehetőségek:", + "aliases:": "aliaszok:", + "generated-value": "generált-érték", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Nincs elég nem opcionális argumentum: %s van, legalább %s kell", + "other": "Nincs elég nem opcionális argumentum: %s van, legalább %s kell" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Túl sok nem opciánlis argumentum van: %s van, maximum %s lehet", + "other": "Túl sok nem opciánlis argumentum van: %s van, maximum %s lehet" + }, + "Missing argument value: %s": { + "one": "Hiányzó argumentum érték: %s", + "other": "Hiányzó argumentum értékek: %s" + }, + "Missing required argument: %s": { + "one": "Hiányzó kötelező argumentum: %s", + "other": "Hiányzó kötelező argumentumok: %s" + }, + "Unknown argument: %s": { + "one": "Ismeretlen argumentum: %s", + "other": "Ismeretlen argumentumok: %s" + }, + "Invalid values:": "Érvénytelen érték:", + "Argument: %s, Given: %s, Choices: %s": "Argumentum: %s, Megadott: %s, Lehetőségek: %s", + "Argument check failed: %s": "Argumentum ellenőrzés sikertelen: %s", + "Implications failed:": "Implikációk sikertelenek:", + "Not enough arguments following: %s": "Nem elég argumentum követi: %s", + "Invalid JSON config file: %s": "Érvénytelen JSON konfigurációs file: %s", + "Path to JSON config file": "JSON konfigurációs file helye", + "Show help": "Súgo megjelenítése", + "Show version number": "Verziószám megjelenítése", + "Did you mean %s?": "Erre gondoltál %s?" +} diff --git a/node_modules/yargs/locales/id.json b/node_modules/yargs/locales/id.json new file mode 100644 index 0000000000000000000000000000000000000000..125867cbb0eedc13d9a5a85ce6df7c3b348ae45f --- /dev/null +++ b/node_modules/yargs/locales/id.json @@ -0,0 +1,50 @@ + +{ + "Commands:": "Perintah:", + "Options:": "Pilihan:", + "Examples:": "Contoh:", + "boolean": "boolean", + "count": "jumlah", + "number": "nomor", + "string": "string", + "array": "larik", + "required": "diperlukan", + "default": "bawaan", + "default:": "bawaan:", + "aliases:": "istilah lain:", + "choices:": "pilihan:", + "generated-value": "nilai-yang-dihasilkan", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Argumen wajib kurang: hanya %s, minimal %s", + "other": "Argumen wajib kurang: hanya %s, minimal %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Terlalu banyak argumen wajib: ada %s, maksimal %s", + "other": "Terlalu banyak argumen wajib: ada %s, maksimal %s" + }, + "Missing argument value: %s": { + "one": "Kurang argumen: %s", + "other": "Kurang argumen: %s" + }, + "Missing required argument: %s": { + "one": "Kurang argumen wajib: %s", + "other": "Kurang argumen wajib: %s" + }, + "Unknown argument: %s": { + "one": "Argumen tak diketahui: %s", + "other": "Argumen tak diketahui: %s" + }, + "Invalid values:": "Nilai-nilai tidak valid:", + "Argument: %s, Given: %s, Choices: %s": "Argumen: %s, Diberikan: %s, Pilihan: %s", + "Argument check failed: %s": "Pemeriksaan argument gagal: %s", + "Implications failed:": "Implikasi gagal:", + "Not enough arguments following: %s": "Kurang argumen untuk: %s", + "Invalid JSON config file: %s": "Berkas konfigurasi JSON tidak valid: %s", + "Path to JSON config file": "Alamat berkas konfigurasi JSON", + "Show help": "Lihat bantuan", + "Show version number": "Lihat nomor versi", + "Did you mean %s?": "Maksud Anda: %s?", + "Arguments %s and %s are mutually exclusive" : "Argumen %s dan %s saling eksklusif", + "Positionals:": "Posisional-posisional:", + "command": "perintah" +} diff --git a/node_modules/yargs/locales/it.json b/node_modules/yargs/locales/it.json new file mode 100644 index 0000000000000000000000000000000000000000..fde575618817ac6c60846ce12ac8d041c65739af --- /dev/null +++ b/node_modules/yargs/locales/it.json @@ -0,0 +1,46 @@ +{ + "Commands:": "Comandi:", + "Options:": "Opzioni:", + "Examples:": "Esempi:", + "boolean": "booleano", + "count": "contatore", + "string": "stringa", + "number": "numero", + "array": "vettore", + "required": "richiesto", + "default": "predefinito", + "default:": "predefinito:", + "choices:": "scelte:", + "aliases:": "alias:", + "generated-value": "valore generato", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Numero insufficiente di argomenti non opzione: inseriti %s, richiesti almeno %s", + "other": "Numero insufficiente di argomenti non opzione: inseriti %s, richiesti almeno %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Troppi argomenti non opzione: inseriti %s, massimo possibile %s", + "other": "Troppi argomenti non opzione: inseriti %s, massimo possibile %s" + }, + "Missing argument value: %s": { + "one": "Argomento mancante: %s", + "other": "Argomenti mancanti: %s" + }, + "Missing required argument: %s": { + "one": "Argomento richiesto mancante: %s", + "other": "Argomenti richiesti mancanti: %s" + }, + "Unknown argument: %s": { + "one": "Argomento sconosciuto: %s", + "other": "Argomenti sconosciuti: %s" + }, + "Invalid values:": "Valori non validi:", + "Argument: %s, Given: %s, Choices: %s": "Argomento: %s, Richiesto: %s, Scelte: %s", + "Argument check failed: %s": "Controllo dell'argomento fallito: %s", + "Implications failed:": "Argomenti dipendenti mancanti:", + "Not enough arguments following: %s": "Argomenti insufficienti dopo: %s", + "Invalid JSON config file: %s": "File di configurazione JSON non valido: %s", + "Path to JSON config file": "Percorso del file di configurazione JSON", + "Show help": "Mostra la schermata di aiuto", + "Show version number": "Mostra il numero di versione", + "Did you mean %s?": "Intendi forse %s?" +} diff --git a/node_modules/yargs/locales/ja.json b/node_modules/yargs/locales/ja.json new file mode 100644 index 0000000000000000000000000000000000000000..3954ae68f895ca5fdd80d55257b2f655dcf92718 --- /dev/null +++ b/node_modules/yargs/locales/ja.json @@ -0,0 +1,51 @@ +{ + "Commands:": "コマンド:", + "Options:": "オプション:", + "Examples:": "例:", + "boolean": "真偽", + "count": "カウント", + "string": "文字列", + "number": "数値", + "array": "配列", + "required": "必須", + "default": "デフォルト", + "default:": "デフォルト:", + "choices:": "選択してください:", + "aliases:": "エイリアス:", + "generated-value": "生成された値", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "オプションではない引数が %s 個では不足しています。少なくとも %s 個の引数が必要です:", + "other": "オプションではない引数が %s 個では不足しています。少なくとも %s 個の引数が必要です:" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "オプションではない引数が %s 個では多すぎます。最大で %s 個までです:", + "other": "オプションではない引数が %s 個では多すぎます。最大で %s 個までです:" + }, + "Missing argument value: %s": { + "one": "引数の値が見つかりません: %s", + "other": "引数の値が見つかりません: %s" + }, + "Missing required argument: %s": { + "one": "必須の引数が見つかりません: %s", + "other": "必須の引数が見つかりません: %s" + }, + "Unknown argument: %s": { + "one": "未知の引数です: %s", + "other": "未知の引数です: %s" + }, + "Invalid values:": "不正な値です:", + "Argument: %s, Given: %s, Choices: %s": "引数は %s です。与えられた値: %s, 選択してください: %s", + "Argument check failed: %s": "引数のチェックに失敗しました: %s", + "Implications failed:": "オプションの組み合わせで不正が生じました:", + "Not enough arguments following: %s": "次の引数が不足しています。: %s", + "Invalid JSON config file: %s": "JSONの設定ファイルが不正です: %s", + "Path to JSON config file": "JSONの設定ファイルまでのpath", + "Show help": "ヘルプを表示", + "Show version number": "バージョンを表示", + "Did you mean %s?": "もしかして %s?", + "Arguments %s and %s are mutually exclusive" : "引数 %s と %s は同時に指定できません", + "Positionals:": "位置:", + "command": "コマンド", + "deprecated": "非推奨", + "deprecated: %s": "非推奨: %s" +} diff --git a/node_modules/yargs/locales/ko.json b/node_modules/yargs/locales/ko.json new file mode 100644 index 0000000000000000000000000000000000000000..746bc89fe91299a14e567fd3866564985586e262 --- /dev/null +++ b/node_modules/yargs/locales/ko.json @@ -0,0 +1,49 @@ +{ + "Commands:": "명령:", + "Options:": "옵션:", + "Examples:": "예시:", + "boolean": "불리언", + "count": "개수", + "string": "문자열", + "number": "숫자", + "array": "배열", + "required": "필수", + "default": "기본값", + "default:": "기본값:", + "choices:": "선택지:", + "aliases:": "별칭:", + "generated-value": "생성된 값", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "옵션이 아닌 인수가 충분하지 않습니다: %s개 입력받음, 최소 %s개 입력 필요", + "other": "옵션이 아닌 인수가 충분하지 않습니다: %s개 입력받음, 최소 %s개 입력 필요" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "옵션이 아닌 인수가 너무 많습니다: %s개 입력받음, 최대 %s개 입력 가능", + "other": "옵션이 아닌 인수가 너무 많습니다: %s개 입력받음, 최대 %s개 입력 가능" + }, + "Missing argument value: %s": { + "one": "인수가 주어지지 않았습니다: %s", + "other": "인수가 주어지지 않았습니다: %s" + }, + "Missing required argument: %s": { + "one": "필수 인수가 주어지지 않았습니다: %s", + "other": "필수 인수가 주어지지 않았습니다: %s" + }, + "Unknown argument: %s": { + "one": "알 수 없는 인수입니다: %s", + "other": "알 수 없는 인수입니다: %s" + }, + "Invalid values:": "유효하지 않은 값:", + "Argument: %s, Given: %s, Choices: %s": "인수: %s, 주어진 값: %s, 선택지: %s", + "Argument check failed: %s": "인수 체크에 실패했습니다: %s", + "Implications failed:": "주어진 인수에 필요한 추가 인수가 주어지지 않았습니다:", + "Not enough arguments following: %s": "다음 인수가 주어지지 않았습니다: %s", + "Invalid JSON config file: %s": "유효하지 않은 JSON 설정 파일: %s", + "Path to JSON config file": "JSON 설정 파일 경로", + "Show help": "도움말 표시", + "Show version number": "버전 표시", + "Did you mean %s?": "%s을(를) 찾으시나요?", + "Arguments %s and %s are mutually exclusive" : "인수 %s과(와) %s은(는) 동시에 지정할 수 없습니다", + "Positionals:": "위치:", + "command": "명령" +} diff --git a/node_modules/yargs/locales/nb.json b/node_modules/yargs/locales/nb.json new file mode 100644 index 0000000000000000000000000000000000000000..6f410ed09d052d89d421d5aa07aa8b216500fbb0 --- /dev/null +++ b/node_modules/yargs/locales/nb.json @@ -0,0 +1,44 @@ +{ + "Commands:": "Kommandoer:", + "Options:": "Alternativer:", + "Examples:": "Eksempler:", + "boolean": "boolsk", + "count": "antall", + "string": "streng", + "number": "nummer", + "array": "matrise", + "required": "obligatorisk", + "default": "standard", + "default:": "standard:", + "choices:": "valg:", + "generated-value": "generert-verdi", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Ikke nok ikke-alternativ argumenter: fikk %s, trenger minst %s", + "other": "Ikke nok ikke-alternativ argumenter: fikk %s, trenger minst %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "For mange ikke-alternativ argumenter: fikk %s, maksimum %s", + "other": "For mange ikke-alternativ argumenter: fikk %s, maksimum %s" + }, + "Missing argument value: %s": { + "one": "Mangler argument verdi: %s", + "other": "Mangler argument verdier: %s" + }, + "Missing required argument: %s": { + "one": "Mangler obligatorisk argument: %s", + "other": "Mangler obligatoriske argumenter: %s" + }, + "Unknown argument: %s": { + "one": "Ukjent argument: %s", + "other": "Ukjente argumenter: %s" + }, + "Invalid values:": "Ugyldige verdier:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Gitt: %s, Valg: %s", + "Argument check failed: %s": "Argumentsjekk mislyktes: %s", + "Implications failed:": "Konsekvensene mislyktes:", + "Not enough arguments following: %s": "Ikke nok følgende argumenter: %s", + "Invalid JSON config file: %s": "Ugyldig JSON konfigurasjonsfil: %s", + "Path to JSON config file": "Bane til JSON konfigurasjonsfil", + "Show help": "Vis hjelp", + "Show version number": "Vis versjonsnummer" +} diff --git a/node_modules/yargs/locales/nl.json b/node_modules/yargs/locales/nl.json new file mode 100644 index 0000000000000000000000000000000000000000..9ff95c5594cb5a3e7ea849273913d8b88a50f53c --- /dev/null +++ b/node_modules/yargs/locales/nl.json @@ -0,0 +1,49 @@ +{ + "Commands:": "Commando's:", + "Options:": "Opties:", + "Examples:": "Voorbeelden:", + "boolean": "booleaans", + "count": "aantal", + "string": "string", + "number": "getal", + "array": "lijst", + "required": "verplicht", + "default": "standaard", + "default:": "standaard:", + "choices:": "keuzes:", + "aliases:": "aliassen:", + "generated-value": "gegenereerde waarde", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Niet genoeg niet-optie-argumenten: %s gekregen, minstens %s nodig", + "other": "Niet genoeg niet-optie-argumenten: %s gekregen, minstens %s nodig" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Te veel niet-optie-argumenten: %s gekregen, maximum is %s", + "other": "Te veel niet-optie-argumenten: %s gekregen, maximum is %s" + }, + "Missing argument value: %s": { + "one": "Missende argumentwaarde: %s", + "other": "Missende argumentwaarden: %s" + }, + "Missing required argument: %s": { + "one": "Missend verplicht argument: %s", + "other": "Missende verplichte argumenten: %s" + }, + "Unknown argument: %s": { + "one": "Onbekend argument: %s", + "other": "Onbekende argumenten: %s" + }, + "Invalid values:": "Ongeldige waarden:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Gegeven: %s, Keuzes: %s", + "Argument check failed: %s": "Argumentcontrole mislukt: %s", + "Implications failed:": "Ontbrekende afhankelijke argumenten:", + "Not enough arguments following: %s": "Niet genoeg argumenten na: %s", + "Invalid JSON config file: %s": "Ongeldig JSON-config-bestand: %s", + "Path to JSON config file": "Pad naar JSON-config-bestand", + "Show help": "Toon help", + "Show version number": "Toon versienummer", + "Did you mean %s?": "Bedoelde u misschien %s?", + "Arguments %s and %s are mutually exclusive": "Argumenten %s en %s kunnen niet tegelijk gebruikt worden", + "Positionals:": "Positie-afhankelijke argumenten", + "command": "commando" +} diff --git a/node_modules/yargs/locales/nn.json b/node_modules/yargs/locales/nn.json new file mode 100644 index 0000000000000000000000000000000000000000..24479ac946ceab9e5fe788b60862b6f7b9633b54 --- /dev/null +++ b/node_modules/yargs/locales/nn.json @@ -0,0 +1,44 @@ +{ + "Commands:": "Kommandoar:", + "Options:": "Alternativ:", + "Examples:": "Døme:", + "boolean": "boolsk", + "count": "mengd", + "string": "streng", + "number": "nummer", + "array": "matrise", + "required": "obligatorisk", + "default": "standard", + "default:": "standard:", + "choices:": "val:", + "generated-value": "generert-verdi", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Ikkje nok ikkje-alternativ argument: fekk %s, treng minst %s", + "other": "Ikkje nok ikkje-alternativ argument: fekk %s, treng minst %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "For mange ikkje-alternativ argument: fekk %s, maksimum %s", + "other": "For mange ikkje-alternativ argument: fekk %s, maksimum %s" + }, + "Missing argument value: %s": { + "one": "Manglar argumentverdi: %s", + "other": "Manglar argumentverdiar: %s" + }, + "Missing required argument: %s": { + "one": "Manglar obligatorisk argument: %s", + "other": "Manglar obligatoriske argument: %s" + }, + "Unknown argument: %s": { + "one": "Ukjent argument: %s", + "other": "Ukjende argument: %s" + }, + "Invalid values:": "Ugyldige verdiar:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Gjeve: %s, Val: %s", + "Argument check failed: %s": "Argumentsjekk mislukkast: %s", + "Implications failed:": "Konsekvensane mislukkast:", + "Not enough arguments following: %s": "Ikkje nok fylgjande argument: %s", + "Invalid JSON config file: %s": "Ugyldig JSON konfigurasjonsfil: %s", + "Path to JSON config file": "Bane til JSON konfigurasjonsfil", + "Show help": "Vis hjelp", + "Show version number": "Vis versjonsnummer" +} diff --git a/node_modules/yargs/locales/pirate.json b/node_modules/yargs/locales/pirate.json new file mode 100644 index 0000000000000000000000000000000000000000..dcb5cb75377d70d5e4783199e54bda11eae259cd --- /dev/null +++ b/node_modules/yargs/locales/pirate.json @@ -0,0 +1,13 @@ +{ + "Commands:": "Choose yer command:", + "Options:": "Options for me hearties!", + "Examples:": "Ex. marks the spot:", + "required": "requi-yar-ed", + "Missing required argument: %s": { + "one": "Ye be havin' to set the followin' argument land lubber: %s", + "other": "Ye be havin' to set the followin' arguments land lubber: %s" + }, + "Show help": "Parlay this here code of conduct", + "Show version number": "'Tis the version ye be askin' fer", + "Arguments %s and %s are mutually exclusive" : "Yon scurvy dogs %s and %s be as bad as rum and a prudish wench" +} diff --git a/node_modules/yargs/locales/pl.json b/node_modules/yargs/locales/pl.json new file mode 100644 index 0000000000000000000000000000000000000000..a41d4bd50f5b1b385f2677cfadb246c4b76b3e23 --- /dev/null +++ b/node_modules/yargs/locales/pl.json @@ -0,0 +1,49 @@ +{ + "Commands:": "Polecenia:", + "Options:": "Opcje:", + "Examples:": "Przykłady:", + "boolean": "boolean", + "count": "ilość", + "string": "ciąg znaków", + "number": "liczba", + "array": "tablica", + "required": "wymagany", + "default": "domyślny", + "default:": "domyślny:", + "choices:": "dostępne:", + "aliases:": "aliasy:", + "generated-value": "wygenerowana-wartość", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Niewystarczająca ilość argumentów: otrzymano %s, wymagane co najmniej %s", + "other": "Niewystarczająca ilość argumentów: otrzymano %s, wymagane co najmniej %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Zbyt duża ilość argumentów: otrzymano %s, wymagane co najwyżej %s", + "other": "Zbyt duża ilość argumentów: otrzymano %s, wymagane co najwyżej %s" + }, + "Missing argument value: %s": { + "one": "Brak wartości dla argumentu: %s", + "other": "Brak wartości dla argumentów: %s" + }, + "Missing required argument: %s": { + "one": "Brak wymaganego argumentu: %s", + "other": "Brak wymaganych argumentów: %s" + }, + "Unknown argument: %s": { + "one": "Nieznany argument: %s", + "other": "Nieznane argumenty: %s" + }, + "Invalid values:": "Nieprawidłowe wartości:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Otrzymano: %s, Dostępne: %s", + "Argument check failed: %s": "Weryfikacja argumentów nie powiodła się: %s", + "Implications failed:": "Założenia nie zostały spełnione:", + "Not enough arguments following: %s": "Niewystarczająca ilość argumentów następujących po: %s", + "Invalid JSON config file: %s": "Nieprawidłowy plik konfiguracyjny JSON: %s", + "Path to JSON config file": "Ścieżka do pliku konfiguracyjnego JSON", + "Show help": "Pokaż pomoc", + "Show version number": "Pokaż numer wersji", + "Did you mean %s?": "Czy chodziło Ci o %s?", + "Arguments %s and %s are mutually exclusive": "Argumenty %s i %s wzajemnie się wykluczają", + "Positionals:": "Pozycyjne:", + "command": "polecenie" +} diff --git a/node_modules/yargs/locales/pt.json b/node_modules/yargs/locales/pt.json new file mode 100644 index 0000000000000000000000000000000000000000..0c8ac99c82f4ab25025b42274bfdfbf386f46a02 --- /dev/null +++ b/node_modules/yargs/locales/pt.json @@ -0,0 +1,45 @@ +{ + "Commands:": "Comandos:", + "Options:": "Opções:", + "Examples:": "Exemplos:", + "boolean": "boolean", + "count": "contagem", + "string": "cadeia de caracteres", + "number": "número", + "array": "arranjo", + "required": "requerido", + "default": "padrão", + "default:": "padrão:", + "choices:": "escolhas:", + "generated-value": "valor-gerado", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Argumentos insuficientes não opcionais: Argumento %s, necessário pelo menos %s", + "other": "Argumentos insuficientes não opcionais: Argumento %s, necessário pelo menos %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Excesso de argumentos não opcionais: recebido %s, máximo de %s", + "other": "Excesso de argumentos não opcionais: recebido %s, máximo de %s" + }, + "Missing argument value: %s": { + "one": "Falta valor de argumento: %s", + "other": "Falta valores de argumento: %s" + }, + "Missing required argument: %s": { + "one": "Falta argumento obrigatório: %s", + "other": "Faltando argumentos obrigatórios: %s" + }, + "Unknown argument: %s": { + "one": "Argumento desconhecido: %s", + "other": "Argumentos desconhecidos: %s" + }, + "Invalid values:": "Valores inválidos:", + "Argument: %s, Given: %s, Choices: %s": "Argumento: %s, Dado: %s, Escolhas: %s", + "Argument check failed: %s": "Verificação de argumento falhou: %s", + "Implications failed:": "Implicações falharam:", + "Not enough arguments following: %s": "Insuficientes argumentos a seguir: %s", + "Invalid JSON config file: %s": "Arquivo de configuração em JSON esta inválido: %s", + "Path to JSON config file": "Caminho para o arquivo de configuração em JSON", + "Show help": "Mostra ajuda", + "Show version number": "Mostra número de versão", + "Arguments %s and %s are mutually exclusive" : "Argumentos %s e %s são mutualmente exclusivos" +} diff --git a/node_modules/yargs/locales/pt_BR.json b/node_modules/yargs/locales/pt_BR.json new file mode 100644 index 0000000000000000000000000000000000000000..eae1ec60d2bde9a5283a3dbc2720f4caa08341f4 --- /dev/null +++ b/node_modules/yargs/locales/pt_BR.json @@ -0,0 +1,48 @@ +{ + "Commands:": "Comandos:", + "Options:": "Opções:", + "Examples:": "Exemplos:", + "boolean": "booleano", + "count": "contagem", + "string": "string", + "number": "número", + "array": "array", + "required": "obrigatório", + "default:": "padrão:", + "choices:": "opções:", + "aliases:": "sinônimos:", + "generated-value": "valor-gerado", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Argumentos insuficientes: Argumento %s, necessário pelo menos %s", + "other": "Argumentos insuficientes: Argumento %s, necessário pelo menos %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Excesso de argumentos: recebido %s, máximo de %s", + "other": "Excesso de argumentos: recebido %s, máximo de %s" + }, + "Missing argument value: %s": { + "one": "Falta valor de argumento: %s", + "other": "Falta valores de argumento: %s" + }, + "Missing required argument: %s": { + "one": "Falta argumento obrigatório: %s", + "other": "Faltando argumentos obrigatórios: %s" + }, + "Unknown argument: %s": { + "one": "Argumento desconhecido: %s", + "other": "Argumentos desconhecidos: %s" + }, + "Invalid values:": "Valores inválidos:", + "Argument: %s, Given: %s, Choices: %s": "Argumento: %s, Dado: %s, Opções: %s", + "Argument check failed: %s": "Verificação de argumento falhou: %s", + "Implications failed:": "Implicações falharam:", + "Not enough arguments following: %s": "Argumentos insuficientes a seguir: %s", + "Invalid JSON config file: %s": "Arquivo JSON de configuração inválido: %s", + "Path to JSON config file": "Caminho para o arquivo JSON de configuração", + "Show help": "Exibe ajuda", + "Show version number": "Exibe a versão", + "Did you mean %s?": "Você quis dizer %s?", + "Arguments %s and %s are mutually exclusive" : "Argumentos %s e %s são mutualmente exclusivos", + "Positionals:": "Posicionais:", + "command": "comando" +} diff --git a/node_modules/yargs/locales/ru.json b/node_modules/yargs/locales/ru.json new file mode 100644 index 0000000000000000000000000000000000000000..d5c9e323b83c578b4182b0a489bd2bfe4b284f78 --- /dev/null +++ b/node_modules/yargs/locales/ru.json @@ -0,0 +1,51 @@ +{ + "Commands:": "Команды:", + "Options:": "Опции:", + "Examples:": "Примеры:", + "boolean": "булевый тип", + "count": "подсчет", + "string": "строковой тип", + "number": "число", + "array": "массив", + "required": "необходимо", + "default": "по умолчанию", + "default:": "по умолчанию:", + "choices:": "возможности:", + "aliases:": "алиасы:", + "generated-value": "генерированное значение", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Недостаточно неопционных аргументов: есть %s, нужно как минимум %s", + "other": "Недостаточно неопционных аргументов: есть %s, нужно как минимум %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Слишком много неопционных аргументов: есть %s, максимум допустимо %s", + "other": "Слишком много неопционных аргументов: есть %s, максимум допустимо %s" + }, + "Missing argument value: %s": { + "one": "Не хватает значения аргумента: %s", + "other": "Не хватает значений аргументов: %s" + }, + "Missing required argument: %s": { + "one": "Не хватает необходимого аргумента: %s", + "other": "Не хватает необходимых аргументов: %s" + }, + "Unknown argument: %s": { + "one": "Неизвестный аргумент: %s", + "other": "Неизвестные аргументы: %s" + }, + "Invalid values:": "Недействительные значения:", + "Argument: %s, Given: %s, Choices: %s": "Аргумент: %s, Данное значение: %s, Возможности: %s", + "Argument check failed: %s": "Проверка аргументов не удалась: %s", + "Implications failed:": "Данный аргумент требует следующий дополнительный аргумент:", + "Not enough arguments following: %s": "Недостаточно следующих аргументов: %s", + "Invalid JSON config file: %s": "Недействительный файл конфигурации JSON: %s", + "Path to JSON config file": "Путь к файлу конфигурации JSON", + "Show help": "Показать помощь", + "Show version number": "Показать номер версии", + "Did you mean %s?": "Вы имели в виду %s?", + "Arguments %s and %s are mutually exclusive": "Аргументы %s и %s являются взаимоисключающими", + "Positionals:": "Позиционные аргументы:", + "command": "команда", + "deprecated": "устар.", + "deprecated: %s": "устар.: %s" +} diff --git a/node_modules/yargs/locales/th.json b/node_modules/yargs/locales/th.json new file mode 100644 index 0000000000000000000000000000000000000000..33b048e2a9275dd540d62aa1e38b07c113b6d9e5 --- /dev/null +++ b/node_modules/yargs/locales/th.json @@ -0,0 +1,46 @@ +{ + "Commands:": "คอมมาน", + "Options:": "ออฟชั่น", + "Examples:": "ตัวอย่าง", + "boolean": "บูลีน", + "count": "นับ", + "string": "สตริง", + "number": "ตัวเลข", + "array": "อาเรย์", + "required": "จำเป็น", + "default": "ค่าเริ่มต้", + "default:": "ค่าเริ่มต้น", + "choices:": "ตัวเลือก", + "aliases:": "เอเลียส", + "generated-value": "ค่าที่ถูกสร้างขึ้น", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "ใส่อาร์กิวเมนต์ไม่ครบตามจำนวนที่กำหนด: ใส่ค่ามาจำนวน %s ค่า, แต่ต้องการอย่างน้อย %s ค่า", + "other": "ใส่อาร์กิวเมนต์ไม่ครบตามจำนวนที่กำหนด: ใส่ค่ามาจำนวน %s ค่า, แต่ต้องการอย่างน้อย %s ค่า" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "ใส่อาร์กิวเมนต์เกินจำนวนที่กำหนด: ใส่ค่ามาจำนวน %s ค่า, แต่ต้องการมากที่สุด %s ค่า", + "other": "ใส่อาร์กิวเมนต์เกินจำนวนที่กำหนด: ใส่ค่ามาจำนวน %s ค่า, แต่ต้องการมากที่สุด %s ค่า" + }, + "Missing argument value: %s": { + "one": "ค่าอาร์กิวเมนต์ที่ขาดไป: %s", + "other": "ค่าอาร์กิวเมนต์ที่ขาดไป: %s" + }, + "Missing required argument: %s": { + "one": "อาร์กิวเมนต์จำเป็นที่ขาดไป: %s", + "other": "อาร์กิวเมนต์จำเป็นที่ขาดไป: %s" + }, + "Unknown argument: %s": { + "one": "อาร์กิวเมนต์ที่ไม่รู้จัก: %s", + "other": "อาร์กิวเมนต์ที่ไม่รู้จัก: %s" + }, + "Invalid values:": "ค่าไม่ถูกต้อง:", + "Argument: %s, Given: %s, Choices: %s": "อาร์กิวเมนต์: %s, ได้รับ: %s, ตัวเลือก: %s", + "Argument check failed: %s": "ตรวจสอบพบอาร์กิวเมนต์ที่ไม่ถูกต้อง: %s", + "Implications failed:": "Implications ไม่สำเร็จ:", + "Not enough arguments following: %s": "ใส่อาร์กิวเมนต์ไม่ครบ: %s", + "Invalid JSON config file: %s": "ไฟล์คอนฟิค JSON ไม่ถูกต้อง: %s", + "Path to JSON config file": "พาทไฟล์คอนฟิค JSON", + "Show help": "ขอความช่วยเหลือ", + "Show version number": "แสดงตัวเลขเวอร์ชั่น", + "Did you mean %s?": "คุณหมายถึง %s?" +} diff --git a/node_modules/yargs/locales/tr.json b/node_modules/yargs/locales/tr.json new file mode 100644 index 0000000000000000000000000000000000000000..0d0d2ccd8fa5867fb2e929a30c5ae5ca1cb45616 --- /dev/null +++ b/node_modules/yargs/locales/tr.json @@ -0,0 +1,48 @@ +{ + "Commands:": "Komutlar:", + "Options:": "Seçenekler:", + "Examples:": "Örnekler:", + "boolean": "boolean", + "count": "sayı", + "string": "string", + "number": "numara", + "array": "array", + "required": "zorunlu", + "default": "varsayılan", + "default:": "varsayılan:", + "choices:": "seçimler:", + "aliases:": "takma adlar:", + "generated-value": "oluşturulan-değer", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Seçenek dışı argümanlar yetersiz: %s bulundu, %s gerekli", + "other": "Seçenek dışı argümanlar yetersiz: %s bulundu, %s gerekli" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Seçenek dışı argümanlar gereğinden fazla: %s bulundu, azami %s", + "other": "Seçenek dışı argümanlar gereğinden fazla: %s bulundu, azami %s" + }, + "Missing argument value: %s": { + "one": "Eksik argüman değeri: %s", + "other": "Eksik argüman değerleri: %s" + }, + "Missing required argument: %s": { + "one": "Eksik zorunlu argüman: %s", + "other": "Eksik zorunlu argümanlar: %s" + }, + "Unknown argument: %s": { + "one": "Bilinmeyen argüman: %s", + "other": "Bilinmeyen argümanlar: %s" + }, + "Invalid values:": "Geçersiz değerler:", + "Argument: %s, Given: %s, Choices: %s": "Argüman: %s, Verilen: %s, Seçimler: %s", + "Argument check failed: %s": "Argüman kontrolü başarısız oldu: %s", + "Implications failed:": "Sonuçlar başarısız oldu:", + "Not enough arguments following: %s": "%s için yeterli argüman bulunamadı", + "Invalid JSON config file: %s": "Geçersiz JSON yapılandırma dosyası: %s", + "Path to JSON config file": "JSON yapılandırma dosya konumu", + "Show help": "Yardım detaylarını göster", + "Show version number": "Versiyon detaylarını göster", + "Did you mean %s?": "Bunu mu demek istediniz: %s?", + "Positionals:": "Sıralılar:", + "command": "komut" +} diff --git a/node_modules/yargs/locales/uk_UA.json b/node_modules/yargs/locales/uk_UA.json new file mode 100644 index 0000000000000000000000000000000000000000..0af0e99cb11ce6c121cae3576a02665751b8e6a2 --- /dev/null +++ b/node_modules/yargs/locales/uk_UA.json @@ -0,0 +1,51 @@ +{ + "Commands:": "Команди:", + "Options:": "Опції:", + "Examples:": "Приклади:", + "boolean": "boolean", + "count": "кількість", + "string": "строка", + "number": "число", + "array": "масива", + "required": "обов'язково", + "default": "за замовчуванням", + "default:": "за замовчуванням:", + "choices:": "доступні варіанти:", + "aliases:": "псевдоніми:", + "generated-value": "згенероване значення", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Недостатньо аргументів: наразі %s, потрібно %s або більше", + "other": "Недостатньо аргументів: наразі %s, потрібно %s або більше" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Забагато аргументів: наразі %s, максимум %s", + "other": "Too many non-option arguments: наразі %s, максимум of %s" + }, + "Missing argument value: %s": { + "one": "Відсутнє значення для аргументу: %s", + "other": "Відсутні значення для аргументу: %s" + }, + "Missing required argument: %s": { + "one": "Відсутній обов'язковий аргумент: %s", + "other": "Відсутні обов'язкові аргументи: %s" + }, + "Unknown argument: %s": { + "one": "Аргумент %s не підтримується", + "other": "Аргументи %s не підтримуються" + }, + "Invalid values:": "Некоректні значення:", + "Argument: %s, Given: %s, Choices: %s": "Аргумент: %s, Введено: %s, Доступні варіанти: %s", + "Argument check failed: %s": "Аргумент не пройшов перевірку: %s", + "Implications failed:": "Відсутні залежні аргументи:", + "Not enough arguments following: %s": "Не достатньо аргументів після: %s", + "Invalid JSON config file: %s": "Некоректний JSON-файл конфігурації: %s", + "Path to JSON config file": "Шлях до JSON-файлу конфігурації", + "Show help": "Показати довідку", + "Show version number": "Показати версію", + "Did you mean %s?": "Можливо, ви мали на увазі %s?", + "Arguments %s and %s are mutually exclusive" : "Аргументи %s та %s взаємовиключні", + "Positionals:": "Позиційні:", + "command": "команда", + "deprecated": "застарілий", + "deprecated: %s": "застарілий: %s" +} diff --git a/node_modules/yargs/locales/uz.json b/node_modules/yargs/locales/uz.json new file mode 100644 index 0000000000000000000000000000000000000000..0d0716819b5e8de0fe7a43d377e1ec6084cd0da7 --- /dev/null +++ b/node_modules/yargs/locales/uz.json @@ -0,0 +1,52 @@ +{ + "Commands:": "Buyruqlar:", + "Options:": "Imkoniyatlar:", + "Examples:": "Misollar:", + "boolean": "boolean", + "count": "sanoq", + "string": "satr", + "number": "raqam", + "array": "massiv", + "required": "majburiy", + "default": "boshlang'ich", + "default:": "boshlang'ich:", + "choices:": "tanlovlar:", + "aliases:": "taxalluslar:", + "generated-value": "yaratilgan-qiymat", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "No-imkoniyat argumentlar yetarli emas: berilgan %s, minimum %s", + "other": "No-imkoniyat argumentlar yetarli emas: berilgan %s, minimum %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "No-imkoniyat argumentlar juda ko'p: berilgan %s, maksimum %s", + "other": "No-imkoniyat argumentlar juda ko'p: got %s, maksimum %s" + }, + "Missing argument value: %s": { + "one": "Argument qiymati berilmagan: %s", + "other": "Argument qiymatlari berilmagan: %s" + }, + "Missing required argument: %s": { + "one": "Majburiy argument berilmagan: %s", + "other": "Majburiy argumentlar berilmagan: %s" + }, + "Unknown argument: %s": { + "one": "Noma'lum argument berilmagan: %s", + "other": "Noma'lum argumentlar berilmagan: %s" + }, + "Invalid values:": "Nosoz qiymatlar:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Berilgan: %s, Tanlovlar: %s", + "Argument check failed: %s": "Muvaffaqiyatsiz argument tekshiruvi: %s", + "Implications failed:": "Bog'liq argumentlar berilmagan:", + "Not enough arguments following: %s": "Quyidagi argumentlar yetarli emas: %s", + "Invalid JSON config file: %s": "Nosoz JSON konfiguratsiya fayli: %s", + "Path to JSON config file": "JSON konfiguratsiya fayli joylashuvi", + "Show help": "Yordam ko'rsatish", + "Show version number": "Versiyani ko'rsatish", + "Did you mean %s?": "%s ni nazarda tutyapsizmi?", + "Arguments %s and %s are mutually exclusive" : "%s va %s argumentlari alohida", + "Positionals:": "Positsionallar:", + "command": "buyruq", + "deprecated": "eskirgan", + "deprecated: %s": "eskirgan: %s" + } + \ No newline at end of file diff --git a/node_modules/yargs/locales/zh_CN.json b/node_modules/yargs/locales/zh_CN.json new file mode 100644 index 0000000000000000000000000000000000000000..257d26babccd72cc3042db74b65a6339b7fa6172 --- /dev/null +++ b/node_modules/yargs/locales/zh_CN.json @@ -0,0 +1,48 @@ +{ + "Commands:": "命令:", + "Options:": "选项:", + "Examples:": "示例:", + "boolean": "布尔", + "count": "计数", + "string": "字符串", + "number": "数字", + "array": "数组", + "required": "必需", + "default": "默认值", + "default:": "默认值:", + "choices:": "可选值:", + "generated-value": "生成的值", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "缺少 non-option 参数:传入了 %s 个, 至少需要 %s 个", + "other": "缺少 non-option 参数:传入了 %s 个, 至少需要 %s 个" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "non-option 参数过多:传入了 %s 个, 最大允许 %s 个", + "other": "non-option 参数过多:传入了 %s 个, 最大允许 %s 个" + }, + "Missing argument value: %s": { + "one": "没有给此选项指定值:%s", + "other": "没有给这些选项指定值:%s" + }, + "Missing required argument: %s": { + "one": "缺少必须的选项:%s", + "other": "缺少这些必须的选项:%s" + }, + "Unknown argument: %s": { + "one": "无法识别的选项:%s", + "other": "无法识别这些选项:%s" + }, + "Invalid values:": "无效的选项值:", + "Argument: %s, Given: %s, Choices: %s": "选项名称: %s, 传入的值: %s, 可选的值:%s", + "Argument check failed: %s": "选项值验证失败:%s", + "Implications failed:": "缺少依赖的选项:", + "Not enough arguments following: %s": "没有提供足够的值给此选项:%s", + "Invalid JSON config file: %s": "无效的 JSON 配置文件:%s", + "Path to JSON config file": "JSON 配置文件的路径", + "Show help": "显示帮助信息", + "Show version number": "显示版本号", + "Did you mean %s?": "是指 %s?", + "Arguments %s and %s are mutually exclusive" : "选项 %s 和 %s 是互斥的", + "Positionals:": "位置:", + "command": "命令" +} diff --git a/node_modules/yargs/locales/zh_TW.json b/node_modules/yargs/locales/zh_TW.json new file mode 100644 index 0000000000000000000000000000000000000000..e38495d3a238525c8eb1372eac9d14bbd28a4eb8 --- /dev/null +++ b/node_modules/yargs/locales/zh_TW.json @@ -0,0 +1,51 @@ +{ + "Commands:": "命令:", + "Options:": "選項:", + "Examples:": "範例:", + "boolean": "布林", + "count": "次數", + "string": "字串", + "number": "數字", + "array": "陣列", + "required": "必填", + "default": "預設值", + "default:": "預設值:", + "choices:": "可選值:", + "aliases:": "別名:", + "generated-value": "生成的值", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "non-option 引數不足:只傳入了 %s 個, 至少要 %s 個", + "other": "non-option 引數不足:只傳入了 %s 個, 至少要 %s 個" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "non-option 引數過多:傳入了 %s 個, 但最多 %s 個", + "other": "non-option 引數過多:傳入了 %s 個, 但最多 %s 個" + }, + "Missing argument value: %s": { + "one": "此引數無指定值:%s", + "other": "這些引數無指定值:%s" + }, + "Missing required argument: %s": { + "one": "缺少必須的引數:%s", + "other": "缺少這些必須的引數:%s" + }, + "Unknown argument: %s": { + "one": "未知的引數:%s", + "other": "未知的引數:%s" + }, + "Invalid values:": "無效的選項值:", + "Argument: %s, Given: %s, Choices: %s": "引數名稱: %s, 傳入的值: %s, 可選的值:%s", + "Argument check failed: %s": "引數驗證失敗:%s", + "Implications failed:": "缺少依賴引數:", + "Not enough arguments following: %s": "沒有提供足夠的值給此引數:%s", + "Invalid JSON config file: %s": "無效的 JSON 設置文件:%s", + "Path to JSON config file": "JSON 設置文件的路徑", + "Show help": "顯示說明", + "Show version number": "顯示版本", + "Did you mean %s?": "您是指 %s 嗎?", + "Arguments %s and %s are mutually exclusive" : "引數 %s 和 %s 互斥", + "Positionals:": "位置:", + "command": "命令", + "deprecated": "已淘汰", + "deprecated: %s": "已淘汰:%s" + } diff --git a/node_modules/yargs/package.json b/node_modules/yargs/package.json new file mode 100644 index 0000000000000000000000000000000000000000..72d530e97a60a0fd65eb1547b586da626522f34e --- /dev/null +++ b/node_modules/yargs/package.json @@ -0,0 +1,160 @@ +{ + "_from": "yargs@^17.7.2", + "_id": "yargs@17.7.2", + "_inBundle": false, + "_integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", + "_location": "/yargs", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "yargs@^17.7.2", + "name": "yargs", + "escapedName": "yargs", + "rawSpec": "^17.7.2", + "saveSpec": null, + "fetchSpec": "^17.7.2" + }, + "_requiredBy": [ + "/msw" + ], + "_resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", + "_shasum": "991df39aca675a192b816e1e0363f9d75d2aa269", + "_spec": "yargs@^17.7.2", + "_where": "/Users/sylvainfiloni/Documents/HuggingFace_Projects/live-vision/node_modules/msw", + "bugs": { + "url": "https://github.com/yargs/yargs/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Yargs Contributors", + "url": "https://github.com/yargs/yargs/graphs/contributors" + } + ], + "dependencies": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + }, + "deprecated": false, + "description": "yargs the modern, pirate-themed, successor to optimist.", + "devDependencies": { + "@types/chai": "^4.2.11", + "@types/mocha": "^9.0.0", + "@types/node": "^18.0.0", + "c8": "^7.7.0", + "chai": "^4.2.0", + "chalk": "^4.0.0", + "coveralls": "^3.0.9", + "cpr": "^3.0.1", + "cross-env": "^7.0.2", + "cross-spawn": "^7.0.0", + "eslint": "^7.23.0", + "gts": "^3.0.0", + "hashish": "0.0.4", + "mocha": "^9.0.0", + "rimraf": "^3.0.2", + "rollup": "^2.23.0", + "rollup-plugin-cleanup": "^3.1.1", + "rollup-plugin-terser": "^7.0.2", + "rollup-plugin-ts": "^2.0.4", + "typescript": "^4.0.2", + "which": "^2.0.0", + "yargs-test-extends": "^1.0.1" + }, + "engines": { + "node": ">=12" + }, + "exports": { + "./package.json": "./package.json", + ".": [ + { + "import": "./index.mjs", + "require": "./index.cjs" + }, + "./index.cjs" + ], + "./helpers": { + "import": "./helpers/helpers.mjs", + "require": "./helpers/index.js" + }, + "./browser": { + "import": "./browser.mjs", + "types": "./browser.d.ts" + }, + "./yargs": [ + { + "import": "./yargs.mjs", + "require": "./yargs" + }, + "./yargs" + ] + }, + "files": [ + "browser.mjs", + "browser.d.ts", + "index.cjs", + "helpers/*.js", + "helpers/*", + "index.mjs", + "yargs", + "yargs.mjs", + "build", + "locales", + "LICENSE", + "lib/platform-shims/*.mjs", + "!*.d.ts", + "!**/*.d.ts" + ], + "homepage": "https://yargs.js.org/", + "keywords": [ + "argument", + "args", + "option", + "parser", + "parsing", + "cli", + "command" + ], + "license": "MIT", + "main": "./index.cjs", + "module": "./index.mjs", + "name": "yargs", + "repository": { + "type": "git", + "url": "git+https://github.com/yargs/yargs.git" + }, + "scripts": { + "build:cjs": "rollup -c rollup.config.cjs", + "check": "gts lint && npm run check:js", + "check:js": "eslint . --ext cjs --ext mjs --ext js", + "clean": "gts clean", + "compile": "rimraf build && tsc", + "coverage": "c8 report --check-coverage", + "fix": "gts fix && npm run fix:js", + "fix:js": "eslint . --ext cjs --ext mjs --ext js --fix", + "postbuild:cjs": "rimraf ./build/index.cjs.d.ts", + "postcompile": "npm run build:cjs", + "posttest": "npm run check", + "prepare": "npm run compile", + "pretest": "npm run compile -- -p tsconfig.test.json && cross-env NODE_ENV=test npm run build:cjs", + "test": "c8 mocha --enable-source-maps ./test/*.cjs --require ./test/before.cjs --timeout=12000 --check-leaks", + "test:esm": "c8 mocha --enable-source-maps ./test/esm/*.mjs --check-leaks" + }, + "type": "module", + "version": "17.7.2", + "warnings": [ + { + "code": "ENOTSUP", + "required": { + "node": ">=12" + }, + "pkgid": "yargs@17.7.2" + } + ] +} diff --git a/node_modules/yargs/yargs b/node_modules/yargs/yargs new file mode 100644 index 0000000000000000000000000000000000000000..8460d10a675a4e6c68c7fe7f29ccf70b22e676aa --- /dev/null +++ b/node_modules/yargs/yargs @@ -0,0 +1,9 @@ +// TODO: consolidate on using a helpers file at some point in the future, which +// is the approach currently used to export Parser and applyExtends for ESM: +const {applyExtends, cjsPlatformShim, Parser, Yargs, processArgv} = require('./build/index.cjs') +Yargs.applyExtends = (config, cwd, mergeExtends) => { + return applyExtends(config, cwd, mergeExtends, cjsPlatformShim) +} +Yargs.hideBin = processArgv.hideBin +Yargs.Parser = Parser +module.exports = Yargs diff --git a/node_modules/yargs/yargs.mjs b/node_modules/yargs/yargs.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6d9f390c171ff656620ac31db541b8a9fcee086d --- /dev/null +++ b/node_modules/yargs/yargs.mjs @@ -0,0 +1,10 @@ +// TODO: consolidate on using a helpers file at some point in the future, which +// is the approach currently used to export Parser and applyExtends for ESM: +import pkg from './build/index.cjs'; +const {applyExtends, cjsPlatformShim, Parser, processArgv, Yargs} = pkg; +Yargs.applyExtends = (config, cwd, mergeExtends) => { + return applyExtends(config, cwd, mergeExtends, cjsPlatformShim); +}; +Yargs.hideBin = processArgv.hideBin; +Yargs.Parser = Parser; +export default Yargs; diff --git a/package-lock.json b/package-lock.json index 1c01d24aaab58d67875c21523bb6a02f41682bd3..20d518dcf4b0b42e3cc5265a305888811a75bece 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,976 +1,1098 @@ { - "name": "live-vision", - "version": "1.0.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "live-vision", - "version": "1.0.0", - "license": "MIT", - "dependencies": { - "@gradio/client": "^0.10.1", - "dotenv": "^4.0.0", - "eventsource": "^2.0.2", - "express": "^4.18.2", - "socket.io": "^4.5.4" - } - }, - "node_modules/@gradio/client": { - "version": "0.10.1", - "resolved": "https://registry.npmjs.org/@gradio/client/-/client-0.10.1.tgz", - "integrity": "sha512-C3uWIWEqlpTuG3sfPw3K3+26Fkr+jXPL8U2lC1u7DlBm25rHdGMVX17o8ApW7XcFtznfaLceVtpnDPkDpQTJlw==", - "dependencies": { - "bufferutil": "^4.0.7", - "semiver": "^1.1.0", - "ws": "^8.13.0" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@socket.io/component-emitter": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.0.tgz", - "integrity": "sha512-+9jVqKhRSpsc591z5vX+X5Yyw+he/HCB4iQ/RYxw35CEPaY1gnsNE43nf9n9AaYjAQrTiI/mOwKUKdUs9vf7Xg==" - }, - "node_modules/@types/cookie": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.4.1.tgz", - "integrity": "sha512-XW/Aa8APYr6jSVVA1y/DEIZX0/GMKLEVekNG727R8cs56ahETkRAy/3DR7+fJyh7oUgGwNQaRfXCun0+KbWY7Q==" - }, - "node_modules/@types/cors": { - "version": "2.8.17", - "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.17.tgz", - "integrity": "sha512-8CGDvrBj1zgo2qE+oS3pOCyYNqCPryMWY2bGfwA0dcfopWGgxs+78df0Rs3rc9THP4JkOhLsAa+15VdpAqkcUA==", - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@types/node": { - "version": "20.11.6", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.6.tgz", - "integrity": "sha512-+EOokTnksGVgip2PbYbr3xnR7kZigh4LbybAfBAw5BpnQ+FqBYUsvCEjYd70IXKlbohQ64mzEYmMtlWUY8q//Q==", - "dependencies": { - "undici-types": "~5.26.4" - } - }, - "node_modules/accepts": { - "version": "1.3.8", - "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", - "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", - "dependencies": { - "mime-types": "~2.1.34", - "negotiator": "0.6.3" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/array-flatten": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", - "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==" - }, - "node_modules/base64id": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/base64id/-/base64id-2.0.0.tgz", - "integrity": "sha512-lGe34o6EHj9y3Kts9R4ZYs/Gr+6N7MCaMlIFA3F1R2O5/m7K06AxfSeO5530PEERE6/WyEg3lsuyw4GHlPZHog==", - "engines": { - "node": "^4.5.0 || >= 5.9" - } - }, - "node_modules/body-parser": { - "version": "1.20.1", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.1.tgz", - "integrity": "sha512-jWi7abTbYwajOytWCQc37VulmWiRae5RyTpaCyDcS5/lMdtwSz5lOpDE67srw/HYe35f1z3fDQw+3txg7gNtWw==", - "dependencies": { - "bytes": "3.1.2", - "content-type": "~1.0.4", - "debug": "2.6.9", - "depd": "2.0.0", - "destroy": "1.2.0", - "http-errors": "2.0.0", - "iconv-lite": "0.4.24", - "on-finished": "2.4.1", - "qs": "6.11.0", - "raw-body": "2.5.1", - "type-is": "~1.6.18", - "unpipe": "1.0.0" - }, - "engines": { - "node": ">= 0.8", - "npm": "1.2.8000 || >= 1.4.16" - } - }, - "node_modules/bufferutil": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/bufferutil/-/bufferutil-4.0.8.tgz", - "integrity": "sha512-4T53u4PdgsXqKaIctwF8ifXlRTTmEPJ8iEPWFdGZvcf7sbwYo6FKFEX9eNNAnzFZ7EzJAQ3CJeOtCRA4rDp7Pw==", - "hasInstallScript": true, - "dependencies": { - "node-gyp-build": "^4.3.0" - }, - "engines": { - "node": ">=6.14.2" - } - }, - "node_modules/bytes": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", - "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/call-bind": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.5.tgz", - "integrity": "sha512-C3nQxfFZxFRVoJoGKKI8y3MOEo129NQ+FgQ08iye+Mk4zNZZGdjfs06bVTr+DBSlA66Q2VEcMki/cUCP4SercQ==", - "dependencies": { - "function-bind": "^1.1.2", - "get-intrinsic": "^1.2.1", - "set-function-length": "^1.1.1" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/content-disposition": { - "version": "0.5.4", - "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", - "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", - "dependencies": { - "safe-buffer": "5.2.1" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/content-type": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", - "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/cookie": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.5.0.tgz", - "integrity": "sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/cookie-signature": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", - "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==" - }, - "node_modules/cors": { - "version": "2.8.5", - "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", - "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", - "dependencies": { - "object-assign": "^4", - "vary": "^1" - }, - "engines": { - "node": ">= 0.10" - } - }, - "node_modules/debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "dependencies": { - "ms": "2.0.0" - } - }, - "node_modules/define-data-property": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.1.tgz", - "integrity": "sha512-E7uGkTzkk1d0ByLeSc6ZsFS79Axg+m1P/VsgYsxHgiuc3tFSj+MjMIwe90FC4lOAZzNBdY7kkO2P2wKdsQ1vgQ==", - "dependencies": { - "get-intrinsic": "^1.2.1", - "gopd": "^1.0.1", - "has-property-descriptors": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/depd": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", - "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/destroy": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", - "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", - "engines": { - "node": ">= 0.8", - "npm": "1.2.8000 || >= 1.4.16" - } - }, - "node_modules/dotenv": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-4.0.0.tgz", - "integrity": "sha512-XcaMACOr3JMVcEv0Y/iUM2XaOsATRZ3U1In41/1jjK6vJZ2PZbQ1bzCG8uvaByfaBpl9gqc9QWJovpUGBXLLYQ==", - "engines": { - "node": ">=4.6.0" - } - }, - "node_modules/ee-first": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", - "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==" - }, - "node_modules/encodeurl": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", - "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/engine.io": { - "version": "6.5.4", - "resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.5.4.tgz", - "integrity": "sha512-KdVSDKhVKyOi+r5uEabrDLZw2qXStVvCsEB/LN3mw4WFi6Gx50jTyuxYVCwAAC0U46FdnzP/ScKRBTXb/NiEOg==", - "dependencies": { - "@types/cookie": "^0.4.1", - "@types/cors": "^2.8.12", - "@types/node": ">=10.0.0", - "accepts": "~1.3.4", - "base64id": "2.0.0", - "cookie": "~0.4.1", - "cors": "~2.8.5", - "debug": "~4.3.1", - "engine.io-parser": "~5.2.1", - "ws": "~8.11.0" - }, - "engines": { - "node": ">=10.2.0" - } - }, - "node_modules/engine.io-parser": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.2.1.tgz", - "integrity": "sha512-9JktcM3u18nU9N2Lz3bWeBgxVgOKpw7yhRaoxQA3FUDZzzw+9WlA6p4G4u0RixNkg14fH7EfEc/RhpurtiROTQ==", - "engines": { - "node": ">=10.0.0" - } - }, - "node_modules/engine.io/node_modules/cookie": { - "version": "0.4.2", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.2.tgz", - "integrity": "sha512-aSWTXFzaKWkvHO1Ny/s+ePFpvKsPnjc551iI41v3ny/ow6tBG5Vd+FuqGNhh1LxOmVzOlGUriIlOaokOvhaStA==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/engine.io/node_modules/debug": { - "version": "4.3.4", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", - "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", - "dependencies": { - "ms": "2.1.2" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/engine.io/node_modules/ms": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" - }, - "node_modules/engine.io/node_modules/ws": { - "version": "8.11.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.11.0.tgz", - "integrity": "sha512-HPG3wQd9sNQoT9xHyNCXoDUa+Xw/VevmY9FoHyQ+g+rrMn4j6FB4np7Z0OhdTgjx6MgQLK7jwSy1YecU1+4Asg==", - "engines": { - "node": ">=10.0.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": "^5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - }, - "node_modules/escape-html": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", - "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==" - }, - "node_modules/etag": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", - "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/eventsource": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-2.0.2.tgz", - "integrity": "sha512-IzUmBGPR3+oUG9dUeXynyNmf91/3zUSJg1lCktzKw47OXuhco54U3r9B7O4XX+Rb1Itm9OZ2b0RkTs10bICOxA==", - "engines": { - "node": ">=12.0.0" - } - }, - "node_modules/express": { - "version": "4.18.2", - "resolved": "https://registry.npmjs.org/express/-/express-4.18.2.tgz", - "integrity": "sha512-5/PsL6iGPdfQ/lKM1UuielYgv3BUoJfz1aUwU9vHZ+J7gyvwdQXFEBIEIaxeGf0GIcreATNyBExtalisDbuMqQ==", - "dependencies": { - "accepts": "~1.3.8", - "array-flatten": "1.1.1", - "body-parser": "1.20.1", - "content-disposition": "0.5.4", - "content-type": "~1.0.4", - "cookie": "0.5.0", - "cookie-signature": "1.0.6", - "debug": "2.6.9", - "depd": "2.0.0", - "encodeurl": "~1.0.2", - "escape-html": "~1.0.3", - "etag": "~1.8.1", - "finalhandler": "1.2.0", - "fresh": "0.5.2", - "http-errors": "2.0.0", - "merge-descriptors": "1.0.1", - "methods": "~1.1.2", - "on-finished": "2.4.1", - "parseurl": "~1.3.3", - "path-to-regexp": "0.1.7", - "proxy-addr": "~2.0.7", - "qs": "6.11.0", - "range-parser": "~1.2.1", - "safe-buffer": "5.2.1", - "send": "0.18.0", - "serve-static": "1.15.0", - "setprototypeof": "1.2.0", - "statuses": "2.0.1", - "type-is": "~1.6.18", - "utils-merge": "1.0.1", - "vary": "~1.1.2" - }, - "engines": { - "node": ">= 0.10.0" - } - }, - "node_modules/finalhandler": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.2.0.tgz", - "integrity": "sha512-5uXcUVftlQMFnWC9qu/svkWv3GTd2PfUhK/3PLkYNAe7FbqJMt3515HaxE6eRL74GdsriiwujiawdaB1BpEISg==", - "dependencies": { - "debug": "2.6.9", - "encodeurl": "~1.0.2", - "escape-html": "~1.0.3", - "on-finished": "2.4.1", - "parseurl": "~1.3.3", - "statuses": "2.0.1", - "unpipe": "~1.0.0" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/forwarded": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", - "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/fresh": { - "version": "0.5.2", - "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", - "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/function-bind": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", - "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/get-intrinsic": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.2.tgz", - "integrity": "sha512-0gSo4ml/0j98Y3lngkFEot/zhiCeWsbYIlZ+uZOVgzLyLaUw7wxUL+nCTP0XJvJg1AXulJRI3UJi8GsbDuxdGA==", - "dependencies": { - "function-bind": "^1.1.2", - "has-proto": "^1.0.1", - "has-symbols": "^1.0.3", - "hasown": "^2.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/gopd": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", - "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==", - "dependencies": { - "get-intrinsic": "^1.1.3" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/has-property-descriptors": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.1.tgz", - "integrity": "sha512-VsX8eaIewvas0xnvinAe9bw4WfIeODpGYikiWYLH+dma0Jw6KHYqWiWfhQlgOVK8D6PvjubK5Uc4P0iIhIcNVg==", - "dependencies": { - "get-intrinsic": "^1.2.2" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/has-proto": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.0.1.tgz", - "integrity": "sha512-7qE+iP+O+bgF9clE5+UoBFzE65mlBiVj3tKCrlNQ0Ogwm0BjpT/gK4SlLYDMybDh5I3TCTKnPPa0oMG7JDYrhg==", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/has-symbols": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", - "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/hasown": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.0.tgz", - "integrity": "sha512-vUptKVTpIJhcczKBbgnS+RtcuYMB8+oNzPK2/Hp3hanz8JmpATdmmgLgSaadVREkDm+e2giHwY3ZRkyjSIDDFA==", - "dependencies": { - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/http-errors": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", - "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", - "dependencies": { - "depd": "2.0.0", - "inherits": "2.0.4", - "setprototypeof": "1.2.0", - "statuses": "2.0.1", - "toidentifier": "1.0.1" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/iconv-lite": { - "version": "0.4.24", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", - "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" - }, - "node_modules/ipaddr.js": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", - "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", - "engines": { - "node": ">= 0.10" - } - }, - "node_modules/media-typer": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", - "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/merge-descriptors": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", - "integrity": "sha512-cCi6g3/Zr1iqQi6ySbseM1Xvooa98N0w31jzUYrXPX2xqObmFGHJ0tQ5u74H3mVh7wLouTseZyYIq39g8cNp1w==" - }, - "node_modules/methods": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", - "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mime": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", - "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", - "bin": { - "mime": "cli.js" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/mime-db": { - "version": "1.52.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", - "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mime-types": { - "version": "2.1.35", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", - "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", - "dependencies": { - "mime-db": "1.52.0" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" - }, - "node_modules/negotiator": { - "version": "0.6.3", - "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", - "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/node-gyp-build": { - "version": "4.8.0", - "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.0.tgz", - "integrity": "sha512-u6fs2AEUljNho3EYTJNBfImO5QTo/J/1Etd+NVdCj7qWKUSN/bSLkZwhDv7I+w/MSC6qJ4cknepkAYykDdK8og==", - "bin": { - "node-gyp-build": "bin.js", - "node-gyp-build-optional": "optional.js", - "node-gyp-build-test": "build-test.js" - } - }, - "node_modules/object-assign": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", - "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/object-inspect": { - "version": "1.13.1", - "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.1.tgz", - "integrity": "sha512-5qoj1RUiKOMsCCNLV1CBiPYE10sziTsnmNxkAI/rZhiD63CF7IqdFGC/XzjWjpSgLf0LxXX3bDFIh0E18f6UhQ==", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/on-finished": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", - "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", - "dependencies": { - "ee-first": "1.1.1" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/parseurl": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", - "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/path-to-regexp": { - "version": "0.1.7", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", - "integrity": "sha512-5DFkuoqlv1uYQKxy8omFBeJPQcdoE07Kv2sferDCrAq1ohOU+MSDswDIbnx3YAM60qIOnYa53wBhXW0EbMonrQ==" - }, - "node_modules/proxy-addr": { - "version": "2.0.7", - "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", - "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", - "dependencies": { - "forwarded": "0.2.0", - "ipaddr.js": "1.9.1" - }, - "engines": { - "node": ">= 0.10" - } - }, - "node_modules/qs": { - "version": "6.11.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.11.0.tgz", - "integrity": "sha512-MvjoMCJwEarSbUYk5O+nmoSzSutSsTwF85zcHPQ9OrlFoZOYIjaqBAJIqIXjptyD5vThxGq52Xu/MaJzRkIk4Q==", - "dependencies": { - "side-channel": "^1.0.4" - }, - "engines": { - "node": ">=0.6" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/range-parser": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", - "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/raw-body": { - "version": "2.5.1", - "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.1.tgz", - "integrity": "sha512-qqJBtEyVgS0ZmPGdCFPWJ3FreoqvG4MVQln/kCgF7Olq95IbOp0/BWyMwbdtn4VTvkM8Y7khCQ2Xgk/tcrCXig==", - "dependencies": { - "bytes": "3.1.2", - "http-errors": "2.0.0", - "iconv-lite": "0.4.24", - "unpipe": "1.0.0" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ] - }, - "node_modules/safer-buffer": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" - }, - "node_modules/semiver": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/semiver/-/semiver-1.1.0.tgz", - "integrity": "sha512-QNI2ChmuioGC1/xjyYwyZYADILWyW6AmS1UH6gDj/SFUUUS4MBAWs/7mxnkRPc/F4iHezDP+O8t0dO8WHiEOdg==", - "engines": { - "node": ">=6" - } - }, - "node_modules/send": { - "version": "0.18.0", - "resolved": "https://registry.npmjs.org/send/-/send-0.18.0.tgz", - "integrity": "sha512-qqWzuOjSFOuqPjFe4NOsMLafToQQwBSOEpS+FwEt3A2V3vKubTquT3vmLTQpFgMXp8AlFWFuP1qKaJZOtPpVXg==", - "dependencies": { - "debug": "2.6.9", - "depd": "2.0.0", - "destroy": "1.2.0", - "encodeurl": "~1.0.2", - "escape-html": "~1.0.3", - "etag": "~1.8.1", - "fresh": "0.5.2", - "http-errors": "2.0.0", - "mime": "1.6.0", - "ms": "2.1.3", - "on-finished": "2.4.1", - "range-parser": "~1.2.1", - "statuses": "2.0.1" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/send/node_modules/ms": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" - }, - "node_modules/serve-static": { - "version": "1.15.0", - "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.15.0.tgz", - "integrity": "sha512-XGuRDNjXUijsUL0vl6nSD7cwURuzEgglbOaFuZM9g3kwDXOWVTck0jLzjPzGD+TazWbboZYu52/9/XPdUgne9g==", - "dependencies": { - "encodeurl": "~1.0.2", - "escape-html": "~1.0.3", - "parseurl": "~1.3.3", - "send": "0.18.0" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/set-function-length": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.0.tgz", - "integrity": "sha512-4DBHDoyHlM1IRPGYcoxexgh67y4ueR53FKV1yyxwFMY7aCqcN/38M1+SwZ/qJQ8iLv7+ck385ot4CcisOAPT9w==", - "dependencies": { - "define-data-property": "^1.1.1", - "function-bind": "^1.1.2", - "get-intrinsic": "^1.2.2", - "gopd": "^1.0.1", - "has-property-descriptors": "^1.0.1" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/setprototypeof": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", - "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" - }, - "node_modules/side-channel": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz", - "integrity": "sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==", - "dependencies": { - "call-bind": "^1.0.0", - "get-intrinsic": "^1.0.2", - "object-inspect": "^1.9.0" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/socket.io": { - "version": "4.7.4", - "resolved": "https://registry.npmjs.org/socket.io/-/socket.io-4.7.4.tgz", - "integrity": "sha512-DcotgfP1Zg9iP/dH9zvAQcWrE0TtbMVwXmlV4T4mqsvY+gw+LqUGPfx2AoVyRk0FLME+GQhufDMyacFmw7ksqw==", - "dependencies": { - "accepts": "~1.3.4", - "base64id": "~2.0.0", - "cors": "~2.8.5", - "debug": "~4.3.2", - "engine.io": "~6.5.2", - "socket.io-adapter": "~2.5.2", - "socket.io-parser": "~4.2.4" - }, - "engines": { - "node": ">=10.2.0" - } - }, - "node_modules/socket.io-adapter": { - "version": "2.5.2", - "resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-2.5.2.tgz", - "integrity": "sha512-87C3LO/NOMc+eMcpcxUBebGjkpMDkNBS9tf7KJqcDsmL936EChtVva71Dw2q4tQcuVC+hAUy4an2NO/sYXmwRA==", - "dependencies": { - "ws": "~8.11.0" - } - }, - "node_modules/socket.io-adapter/node_modules/ws": { - "version": "8.11.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.11.0.tgz", - "integrity": "sha512-HPG3wQd9sNQoT9xHyNCXoDUa+Xw/VevmY9FoHyQ+g+rrMn4j6FB4np7Z0OhdTgjx6MgQLK7jwSy1YecU1+4Asg==", - "engines": { - "node": ">=10.0.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": "^5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - }, - "node_modules/socket.io-parser": { - "version": "4.2.4", - "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.4.tgz", - "integrity": "sha512-/GbIKmo8ioc+NIWIhwdecY0ge+qVBSMdgxGygevmdHj24bsfgtCmcUUcQ5ZzcylGFHsN3k4HB4Cgkl96KVnuew==", - "dependencies": { - "@socket.io/component-emitter": "~3.1.0", - "debug": "~4.3.1" - }, - "engines": { - "node": ">=10.0.0" - } - }, - "node_modules/socket.io-parser/node_modules/debug": { - "version": "4.3.4", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", - "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", - "dependencies": { - "ms": "2.1.2" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/socket.io-parser/node_modules/ms": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" - }, - "node_modules/socket.io/node_modules/debug": { - "version": "4.3.4", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", - "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", - "dependencies": { - "ms": "2.1.2" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/socket.io/node_modules/ms": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" - }, - "node_modules/statuses": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", - "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/toidentifier": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", - "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", - "engines": { - "node": ">=0.6" - } - }, - "node_modules/type-is": { - "version": "1.6.18", - "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", - "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", - "dependencies": { - "media-typer": "0.3.0", - "mime-types": "~2.1.24" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/undici-types": { - "version": "5.26.5", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", - "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==" - }, - "node_modules/unpipe": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", - "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/utils-merge": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", - "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", - "engines": { - "node": ">= 0.4.0" - } - }, - "node_modules/vary": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", - "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/ws": { - "version": "8.16.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.16.0.tgz", - "integrity": "sha512-HS0c//TP7Ina87TfiPUz1rQzMhHrl/SG2guqRcTOIUYD2q8uhUdNHZYJUaQ8aTGPzCh+c6oawMKW35nFl1dxyQ==", - "engines": { - "node": ">=10.0.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": ">=5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } + "name": "live-vision", + "version": "1.0.0", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "@bundled-es-modules/cookie": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@bundled-es-modules/cookie/-/cookie-2.0.0.tgz", + "integrity": "sha512-Or6YHg/kamKHpxULAdSqhGqnWFneIXu1NKvvfBBzKGwpVsYuFIQ5aBPHDnnoR3ghW1nvSkALd+EF9iMtY7Vjxw==", + "requires": { + "cookie": "^0.5.0" + }, + "dependencies": { + "cookie": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.5.0.tgz", + "integrity": "sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw==" + } + } + }, + "@bundled-es-modules/statuses": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@bundled-es-modules/statuses/-/statuses-1.0.1.tgz", + "integrity": "sha512-yn7BklA5acgcBr+7w064fGV+SGIFySjCKpqjcWgBAIfrAkY+4GQTJJHQMeT3V/sgz23VTEVV8TtOmkvJAhFVfg==", + "requires": { + "statuses": "^2.0.1" + } + }, + "@gradio/client": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@gradio/client/-/client-1.1.1.tgz", + "integrity": "sha512-6Hzc+/wmNRkodefp0bvfOBQbEakwg31Ye9IVOjfoHkvunHoIzjupM+1m7VwhQXt8pMCjOw8Hc7zhvwnwy6f5GQ==", + "requires": { + "@types/eventsource": "^1.1.15", + "bufferutil": "^4.0.7", + "eventsource": "^2.0.2", + "fetch-event-stream": "^0.1.5", + "msw": "^2.2.1", + "semiver": "^1.1.0", + "textlinestream": "^1.1.1", + "typescript": "^5.0.0", + "ws": "^8.13.0" + } + }, + "@inquirer/confirm": { + "version": "3.1.10", + "resolved": "https://registry.npmjs.org/@inquirer/confirm/-/confirm-3.1.10.tgz", + "integrity": "sha512-/aAHu83Njy6yf44T+ZrRPUkMcUqprrOiIKsyMvf9jOV+vF5BNb2ja1aLP33MK36W8eaf91MTL/mU/e6METuENg==", + "requires": { + "@inquirer/core": "^8.2.3", + "@inquirer/type": "^1.3.3" + } + }, + "@inquirer/core": { + "version": "8.2.3", + "resolved": "https://registry.npmjs.org/@inquirer/core/-/core-8.2.3.tgz", + "integrity": "sha512-WrpDVPAaxJQjHid3Ra4FhUO70YBzkHSYVyW5X48L5zHYdudoPISJqTRRWSeamHfaXda7PNNaC5Py5MEo7QwBNA==", + "requires": { + "@inquirer/figures": "^1.0.3", + "@inquirer/type": "^1.3.3", + "@types/mute-stream": "^0.0.4", + "@types/node": "^20.14.6", + "@types/wrap-ansi": "^3.0.0", + "ansi-escapes": "^4.3.2", + "chalk": "^4.1.2", + "cli-spinners": "^2.9.2", + "cli-width": "^4.1.0", + "mute-stream": "^1.0.0", + "signal-exit": "^4.1.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^6.2.0" + } + }, + "@inquirer/figures": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@inquirer/figures/-/figures-1.0.3.tgz", + "integrity": "sha512-ErXXzENMH5pJt5/ssXV0DfWUZqly8nGzf0UcBV9xTnP+KyffE2mqyxIMBrZ8ijQck2nU0TQm40EQB53YreyWHw==" + }, + "@inquirer/type": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@inquirer/type/-/type-1.3.3.tgz", + "integrity": "sha512-xTUt0NulylX27/zMx04ZYar/kr1raaiFTVvQ5feljQsiAgdm0WPj4S73/ye0fbslh+15QrIuDvfCXTek7pMY5A==" + }, + "@mswjs/cookies": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@mswjs/cookies/-/cookies-1.1.1.tgz", + "integrity": "sha512-W68qOHEjx1iD+4VjQudlx26CPIoxmIAtK4ZCexU0/UJBG6jYhcuyzKJx+Iw8uhBIGd9eba64XgWVgo20it1qwA==" + }, + "@mswjs/interceptors": { + "version": "0.29.1", + "resolved": "https://registry.npmjs.org/@mswjs/interceptors/-/interceptors-0.29.1.tgz", + "integrity": "sha512-3rDakgJZ77+RiQUuSK69t1F0m8BQKA8Vh5DCS5V0DWvNY67zob2JhhQrhCO0AKLGINTRSFd1tBaHcJTkhefoSw==", + "requires": { + "@open-draft/deferred-promise": "^2.2.0", + "@open-draft/logger": "^0.3.0", + "@open-draft/until": "^2.0.0", + "is-node-process": "^1.2.0", + "outvariant": "^1.2.1", + "strict-event-emitter": "^0.5.1" + } + }, + "@open-draft/deferred-promise": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@open-draft/deferred-promise/-/deferred-promise-2.2.0.tgz", + "integrity": "sha512-CecwLWx3rhxVQF6V4bAgPS5t+So2sTbPgAzafKkVizyi7tlwpcFpdFqq+wqF2OwNBmqFuu6tOyouTuxgpMfzmA==" + }, + "@open-draft/logger": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@open-draft/logger/-/logger-0.3.0.tgz", + "integrity": "sha512-X2g45fzhxH238HKO4xbSr7+wBS8Fvw6ixhTDuvLd5mqh6bJJCFAPwU9mPDxbcrRtfxv4u5IHCEH77BmxvXmmxQ==", + "requires": { + "is-node-process": "^1.2.0", + "outvariant": "^1.4.0" + } + }, + "@open-draft/until": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@open-draft/until/-/until-2.1.0.tgz", + "integrity": "sha512-U69T3ItWHvLwGg5eJ0n3I62nWuE6ilHlmz7zM0npLBRvPRd7e6NYmg54vvRtP5mZG7kZqZCFVdsTWo7BPtBujg==" + }, + "@socket.io/component-emitter": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz", + "integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==" + }, + "@types/cookie": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.4.1.tgz", + "integrity": "sha512-XW/Aa8APYr6jSVVA1y/DEIZX0/GMKLEVekNG727R8cs56ahETkRAy/3DR7+fJyh7oUgGwNQaRfXCun0+KbWY7Q==" + }, + "@types/cors": { + "version": "2.8.17", + "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.17.tgz", + "integrity": "sha512-8CGDvrBj1zgo2qE+oS3pOCyYNqCPryMWY2bGfwA0dcfopWGgxs+78df0Rs3rc9THP4JkOhLsAa+15VdpAqkcUA==", + "requires": { + "@types/node": "*" + } + }, + "@types/eventsource": { + "version": "1.1.15", + "resolved": "https://registry.npmjs.org/@types/eventsource/-/eventsource-1.1.15.tgz", + "integrity": "sha512-XQmGcbnxUNa06HR3VBVkc9+A2Vpi9ZyLJcdS5dwaQQ/4ZMWFO+5c90FnMUpbtMZwB/FChoYHwuVg8TvkECacTA==" + }, + "@types/mute-stream": { + "version": "0.0.4", + "resolved": "https://registry.npmjs.org/@types/mute-stream/-/mute-stream-0.0.4.tgz", + "integrity": "sha512-CPM9nzrCPPJHQNA9keH9CVkVI+WR5kMa+7XEs5jcGQ0VoAGnLv242w8lIVgwAEfmE4oufJRaTc9PNLQl0ioAow==", + "requires": { + "@types/node": "*" + } + }, + "@types/node": { + "version": "20.14.8", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.14.8.tgz", + "integrity": "sha512-DO+2/jZinXfROG7j7WKFn/3C6nFwxy2lLpgLjEXJz+0XKphZlTLJ14mo8Vfg8X5BWN6XjyESXq+LcYdT7tR3bA==", + "requires": { + "undici-types": "~5.26.4" + } + }, + "@types/statuses": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@types/statuses/-/statuses-2.0.5.tgz", + "integrity": "sha512-jmIUGWrAiwu3dZpxntxieC+1n/5c3mjrImkmOSQ2NC5uP6cYO4aAZDdSmRcI5C1oiTmqlZGHC+/NmJrKogbP5A==" + }, + "@types/wrap-ansi": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/wrap-ansi/-/wrap-ansi-3.0.0.tgz", + "integrity": "sha512-ltIpx+kM7g/MLRZfkbL7EsCEjfzCcScLpkg37eXEtx5kmrAKBkTJwd1GIAjDSL8wTpM6Hzn5YO4pSb91BEwu1g==" + }, + "accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "requires": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + } + }, + "ansi-escapes": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", + "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", + "requires": { + "type-fest": "^0.21.3" + }, + "dependencies": { + "type-fest": { + "version": "0.21.3", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", + "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==" + } + } + }, + "ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==" + }, + "ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "requires": { + "color-convert": "^2.0.1" + } + }, + "array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==" + }, + "base64id": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/base64id/-/base64id-2.0.0.tgz", + "integrity": "sha512-lGe34o6EHj9y3Kts9R4ZYs/Gr+6N7MCaMlIFA3F1R2O5/m7K06AxfSeO5530PEERE6/WyEg3lsuyw4GHlPZHog==" + }, + "body-parser": { + "version": "1.20.2", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.2.tgz", + "integrity": "sha512-ml9pReCu3M61kGlqoTm2umSXTlRTuGTx0bfYj+uIUKKYycG5NtSbeetV3faSU6R7ajOPw0g/J1PvK4qNy7s5bA==", + "requires": { + "bytes": "3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "on-finished": "2.4.1", + "qs": "6.11.0", + "raw-body": "2.5.2", + "type-is": "~1.6.18", + "unpipe": "1.0.0" + } + }, + "bufferutil": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/bufferutil/-/bufferutil-4.0.8.tgz", + "integrity": "sha512-4T53u4PdgsXqKaIctwF8ifXlRTTmEPJ8iEPWFdGZvcf7sbwYo6FKFEX9eNNAnzFZ7EzJAQ3CJeOtCRA4rDp7Pw==", + "requires": { + "node-gyp-build": "^4.3.0" + } + }, + "bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==" + }, + "call-bind": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.7.tgz", + "integrity": "sha512-GHTSNSYICQ7scH7sZ+M2rFopRoLh8t2bLSW6BbgrtLsahOIB5iyAVJf9GjWK3cYTDaMj4XdBpM1cA6pIS0Kv2w==", + "requires": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "set-function-length": "^1.2.1" + } + }, + "chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "cli-spinners": { + "version": "2.9.2", + "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-2.9.2.tgz", + "integrity": "sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg==" + }, + "cli-width": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-4.1.0.tgz", + "integrity": "sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ==" + }, + "cliui": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", + "requires": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + }, + "dependencies": { + "wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "requires": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + } + } + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, + "content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "requires": { + "safe-buffer": "5.2.1" + } + }, + "content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==" + }, + "cookie": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.6.0.tgz", + "integrity": "sha512-U71cyTamuh1CRNCfpGY6to28lxvNwPG4Guz/EVjgf3Jmzv0vlDp1atT9eS5dDjMYHucpHbWns6Lwf3BKz6svdw==" + }, + "cookie-signature": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==" + }, + "cors": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", + "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", + "requires": { + "object-assign": "^4", + "vary": "^1" + } + }, + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "requires": { + "ms": "2.0.0" + } + }, + "define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "requires": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + } + }, + "depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==" + }, + "destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==" + }, + "dotenv": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-4.0.0.tgz", + "integrity": "sha512-XcaMACOr3JMVcEv0Y/iUM2XaOsATRZ3U1In41/1jjK6vJZ2PZbQ1bzCG8uvaByfaBpl9gqc9QWJovpUGBXLLYQ==" + }, + "ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==" + }, + "emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" + }, + "encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==" + }, + "engine.io": { + "version": "6.5.5", + "resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.5.5.tgz", + "integrity": "sha512-C5Pn8Wk+1vKBoHghJODM63yk8MvrO9EWZUfkAt5HAqIgPE4/8FF0PEGHXtEd40l223+cE5ABWuPzm38PHFXfMA==", + "requires": { + "@types/cookie": "^0.4.1", + "@types/cors": "^2.8.12", + "@types/node": ">=10.0.0", + "accepts": "~1.3.4", + "base64id": "2.0.0", + "cookie": "~0.4.1", + "cors": "~2.8.5", + "debug": "~4.3.1", + "engine.io-parser": "~5.2.1", + "ws": "~8.17.1" + }, + "dependencies": { + "cookie": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.2.tgz", + "integrity": "sha512-aSWTXFzaKWkvHO1Ny/s+ePFpvKsPnjc551iI41v3ny/ow6tBG5Vd+FuqGNhh1LxOmVzOlGUriIlOaokOvhaStA==" + }, + "debug": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.5.tgz", + "integrity": "sha512-pt0bNEmneDIvdL1Xsd9oDQ/wrQRkXDT4AUWlNZNPKvW5x/jyO9VFXkJUP07vQ2upmw5PlaITaPKc31jK13V+jg==", + "requires": { + "ms": "2.1.2" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + } + } + }, + "engine.io-parser": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.2.2.tgz", + "integrity": "sha512-RcyUFKA93/CXH20l4SoVvzZfrSDMOTUS3bWVpTt2FuFP+XYrL8i8oonHP7WInRyVHXh0n/ORtoeiE1os+8qkSw==" + }, + "es-define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.0.tgz", + "integrity": "sha512-jxayLKShrEqqzJ0eumQbVhTYQM27CfT1T35+gCgDFoL82JLsXqTJ76zv6A0YLOgEnLUMvLzsDsGIrl8NFpT2gQ==", + "requires": { + "get-intrinsic": "^1.2.4" + } + }, + "es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==" + }, + "escalade": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.2.tgz", + "integrity": "sha512-ErCHMCae19vR8vQGe50xIsVomy19rg6gFu3+r3jkEO46suLMWBksvVyoGgQV+jOfl84ZSOSlmv6Gxa89PmTGmA==" + }, + "escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==" + }, + "etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==" + }, + "eventsource": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-2.0.2.tgz", + "integrity": "sha512-IzUmBGPR3+oUG9dUeXynyNmf91/3zUSJg1lCktzKw47OXuhco54U3r9B7O4XX+Rb1Itm9OZ2b0RkTs10bICOxA==" + }, + "express": { + "version": "4.19.2", + "resolved": "https://registry.npmjs.org/express/-/express-4.19.2.tgz", + "integrity": "sha512-5T6nhjsT+EOMzuck8JjBHARTHfMht0POzlA60WV2pMD3gyXw2LZnZ+ueGdNxG+0calOJcWKbpFcuzLZ91YWq9Q==", + "requires": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "1.20.2", + "content-disposition": "0.5.4", + "content-type": "~1.0.4", + "cookie": "0.6.0", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "1.2.0", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "merge-descriptors": "1.0.1", + "methods": "~1.1.2", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "0.1.7", + "proxy-addr": "~2.0.7", + "qs": "6.11.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "0.18.0", + "serve-static": "1.15.0", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + } + }, + "fetch-event-stream": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/fetch-event-stream/-/fetch-event-stream-0.1.5.tgz", + "integrity": "sha512-V1PWovkspxQfssq/NnxoEyQo1DV+MRK/laPuPblIZmSjMN8P5u46OhlFQznSr9p/t0Sp8Uc6SbM3yCMfr0KU8g==" + }, + "finalhandler": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.2.0.tgz", + "integrity": "sha512-5uXcUVftlQMFnWC9qu/svkWv3GTd2PfUhK/3PLkYNAe7FbqJMt3515HaxE6eRL74GdsriiwujiawdaB1BpEISg==", + "requires": { + "debug": "2.6.9", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "statuses": "2.0.1", + "unpipe": "~1.0.0" + } + }, + "forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==" + }, + "fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==" + }, + "function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==" + }, + "get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==" + }, + "get-intrinsic": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.4.tgz", + "integrity": "sha512-5uYhsJH8VJBTv7oslg4BznJYhDoRI6waYCxMmCdnTrcCrHA/fCFKoTFz2JKKE0HdDFUF7/oQuhzumXJK7paBRQ==", + "requires": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3", + "hasown": "^2.0.0" + } + }, + "gopd": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", + "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==", + "requires": { + "get-intrinsic": "^1.1.3" + } + }, + "graphql": { + "version": "16.9.0", + "resolved": "https://registry.npmjs.org/graphql/-/graphql-16.9.0.tgz", + "integrity": "sha512-GGTKBX4SD7Wdb8mqeDLni2oaRGYQWjWHGKPQ24ZMnUtKfcsVoiv4uX8+LJr1K6U5VW2Lu1BwJnj7uiori0YtRw==" + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==" + }, + "has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "requires": { + "es-define-property": "^1.0.0" + } + }, + "has-proto": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.0.3.tgz", + "integrity": "sha512-SJ1amZAJUiZS+PhsVLf5tGydlaVB8EdFpaSO4gmiUKUOxk8qzn5AIy4ZeJUmh22znIdk/uMAUT2pl3FxzVUH+Q==" + }, + "has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==" + }, + "hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "requires": { + "function-bind": "^1.1.2" + } + }, + "headers-polyfill": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/headers-polyfill/-/headers-polyfill-4.0.3.tgz", + "integrity": "sha512-IScLbePpkvO846sIwOtOTDjutRMWdXdJmXdMvk6gCBHxFO8d+QKOQedyZSxFTTFYRSmlgSTDtXqqq4pcenBXLQ==" + }, + "http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "requires": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + } + }, + "iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "requires": { + "safer-buffer": ">= 2.1.2 < 3" + } + }, + "inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==" + }, + "is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==" + }, + "is-node-process": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/is-node-process/-/is-node-process-1.2.0.tgz", + "integrity": "sha512-Vg4o6/fqPxIjtxgUH5QLJhwZ7gW5diGCVlXpuUfELC62CuxM1iHcRe51f2W1FDy04Ai4KJkagKjx3XaqyfRKXw==" + }, + "media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==" + }, + "merge-descriptors": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", + "integrity": "sha512-cCi6g3/Zr1iqQi6ySbseM1Xvooa98N0w31jzUYrXPX2xqObmFGHJ0tQ5u74H3mVh7wLouTseZyYIq39g8cNp1w==" + }, + "methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==" + }, + "mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==" + }, + "mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==" + }, + "mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "requires": { + "mime-db": "1.52.0" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + }, + "msw": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/msw/-/msw-2.3.1.tgz", + "integrity": "sha512-ocgvBCLn/5l3jpl1lssIb3cniuACJLoOfZu01e3n5dbJrpA5PeeWn28jCLgQDNt6d7QT8tF2fYRzm9JoEHtiig==", + "requires": { + "@bundled-es-modules/cookie": "^2.0.0", + "@bundled-es-modules/statuses": "^1.0.1", + "@inquirer/confirm": "^3.0.0", + "@mswjs/cookies": "^1.1.0", + "@mswjs/interceptors": "^0.29.0", + "@open-draft/until": "^2.1.0", + "@types/cookie": "^0.6.0", + "@types/statuses": "^2.0.4", + "chalk": "^4.1.2", + "graphql": "^16.8.1", + "headers-polyfill": "^4.0.2", + "is-node-process": "^1.2.0", + "outvariant": "^1.4.2", + "path-to-regexp": "^6.2.0", + "strict-event-emitter": "^0.5.1", + "type-fest": "^4.9.0", + "yargs": "^17.7.2" + }, + "dependencies": { + "@types/cookie": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.6.0.tgz", + "integrity": "sha512-4Kh9a6B2bQciAhf7FSuMRRkUWecJgJu9nPnx3yzpsfXX/c50REIqpHY4C82bXP90qrLtXtkDxTZosYO3UpOwlA==" + }, + "path-to-regexp": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-6.2.2.tgz", + "integrity": "sha512-GQX3SSMokngb36+whdpRXE+3f9V8UzyAorlYvOGx87ufGHehNTn5lCxrKtLyZ4Yl/wEKnNnr98ZzOwwDZV5ogw==" + } + } + }, + "mute-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-1.0.0.tgz", + "integrity": "sha512-avsJQhyd+680gKXyG/sQc0nXaC6rBkPOfyHYcFb9+hdkqQkR9bdnkJ0AMZhke0oesPqIO+mFFJ+IdBc7mst4IA==" + }, + "negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==" + }, + "node-gyp-build": { + "version": "4.8.1", + "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.1.tgz", + "integrity": "sha512-OSs33Z9yWr148JZcbZd5WiAXhh/n9z8TxQcdMhIOlpN9AhWpLfvVFO73+m77bBABQMaY9XSvIa+qk0jlI7Gcaw==" + }, + "object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==" + }, + "object-inspect": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.2.tgz", + "integrity": "sha512-IRZSRuzJiynemAXPYtPe5BoI/RESNYR7TYm50MC5Mqbd3Jmw5y790sErYw3V6SryFJD64b74qQQs9wn5Bg/k3g==" + }, + "on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "requires": { + "ee-first": "1.1.1" + } + }, + "outvariant": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/outvariant/-/outvariant-1.4.2.tgz", + "integrity": "sha512-Ou3dJ6bA/UJ5GVHxah4LnqDwZRwAmWxrG3wtrHrbGnP4RnLCtA64A4F+ae7Y8ww660JaddSoArUR5HjipWSHAQ==" + }, + "parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==" + }, + "path-to-regexp": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", + "integrity": "sha512-5DFkuoqlv1uYQKxy8omFBeJPQcdoE07Kv2sferDCrAq1ohOU+MSDswDIbnx3YAM60qIOnYa53wBhXW0EbMonrQ==" + }, + "proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "requires": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + } + }, + "qs": { + "version": "6.11.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.11.0.tgz", + "integrity": "sha512-MvjoMCJwEarSbUYk5O+nmoSzSutSsTwF85zcHPQ9OrlFoZOYIjaqBAJIqIXjptyD5vThxGq52Xu/MaJzRkIk4Q==", + "requires": { + "side-channel": "^1.0.4" + } + }, + "range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==" + }, + "raw-body": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz", + "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", + "requires": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + } + }, + "require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==" + }, + "safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==" + }, + "safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + }, + "semiver": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/semiver/-/semiver-1.1.0.tgz", + "integrity": "sha512-QNI2ChmuioGC1/xjyYwyZYADILWyW6AmS1UH6gDj/SFUUUS4MBAWs/7mxnkRPc/F4iHezDP+O8t0dO8WHiEOdg==" + }, + "send": { + "version": "0.18.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.18.0.tgz", + "integrity": "sha512-qqWzuOjSFOuqPjFe4NOsMLafToQQwBSOEpS+FwEt3A2V3vKubTquT3vmLTQpFgMXp8AlFWFuP1qKaJZOtPpVXg==", + "requires": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "2.4.1", + "range-parser": "~1.2.1", + "statuses": "2.0.1" + }, + "dependencies": { + "ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + } + } + }, + "serve-static": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.15.0.tgz", + "integrity": "sha512-XGuRDNjXUijsUL0vl6nSD7cwURuzEgglbOaFuZM9g3kwDXOWVTck0jLzjPzGD+TazWbboZYu52/9/XPdUgne9g==", + "requires": { + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.18.0" + } + }, + "set-function-length": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "requires": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + } + }, + "setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" + }, + "side-channel": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz", + "integrity": "sha512-fDW/EZ6Q9RiO8eFG8Hj+7u/oW+XrPTIChwCOM2+th2A6OblDtYYIpve9m+KvI9Z4C9qSEXlaGR6bTEYHReuglA==", + "requires": { + "call-bind": "^1.0.7", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.4", + "object-inspect": "^1.13.1" + } + }, + "signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==" + }, + "socket.io": { + "version": "4.7.5", + "resolved": "https://registry.npmjs.org/socket.io/-/socket.io-4.7.5.tgz", + "integrity": "sha512-DmeAkF6cwM9jSfmp6Dr/5/mfMwb5Z5qRrSXLpo3Fq5SqyU8CMF15jIN4ZhfSwu35ksM1qmHZDQ/DK5XTccSTvA==", + "requires": { + "accepts": "~1.3.4", + "base64id": "~2.0.0", + "cors": "~2.8.5", + "debug": "~4.3.2", + "engine.io": "~6.5.2", + "socket.io-adapter": "~2.5.2", + "socket.io-parser": "~4.2.4" + }, + "dependencies": { + "debug": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.5.tgz", + "integrity": "sha512-pt0bNEmneDIvdL1Xsd9oDQ/wrQRkXDT4AUWlNZNPKvW5x/jyO9VFXkJUP07vQ2upmw5PlaITaPKc31jK13V+jg==", + "requires": { + "ms": "2.1.2" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + } + } + }, + "socket.io-adapter": { + "version": "2.5.5", + "resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-2.5.5.tgz", + "integrity": "sha512-eLDQas5dzPgOWCk9GuuJC2lBqItuhKI4uxGgo9aIV7MYbk2h9Q6uULEh8WBzThoI7l+qU9Ast9fVUmkqPP9wYg==", + "requires": { + "debug": "~4.3.4", + "ws": "~8.17.1" + }, + "dependencies": { + "debug": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.5.tgz", + "integrity": "sha512-pt0bNEmneDIvdL1Xsd9oDQ/wrQRkXDT4AUWlNZNPKvW5x/jyO9VFXkJUP07vQ2upmw5PlaITaPKc31jK13V+jg==", + "requires": { + "ms": "2.1.2" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + } + } + }, + "socket.io-parser": { + "version": "4.2.4", + "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.4.tgz", + "integrity": "sha512-/GbIKmo8ioc+NIWIhwdecY0ge+qVBSMdgxGygevmdHj24bsfgtCmcUUcQ5ZzcylGFHsN3k4HB4Cgkl96KVnuew==", + "requires": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.3.1" + }, + "dependencies": { + "debug": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.5.tgz", + "integrity": "sha512-pt0bNEmneDIvdL1Xsd9oDQ/wrQRkXDT4AUWlNZNPKvW5x/jyO9VFXkJUP07vQ2upmw5PlaITaPKc31jK13V+jg==", + "requires": { + "ms": "2.1.2" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" } + } + }, + "statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==" + }, + "strict-event-emitter": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/strict-event-emitter/-/strict-event-emitter-0.5.1.tgz", + "integrity": "sha512-vMgjE/GGEPEFnhFub6pa4FmJBRBVOLpIII2hvCZ8Kzb7K0hlHo7mQv6xYrBvCL2LtAIBwFUK8wvuJgTVSQ5MFQ==" + }, + "string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "requires": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + } + }, + "strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "requires": { + "ansi-regex": "^5.0.1" + } + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "requires": { + "has-flag": "^4.0.0" + } + }, + "textlinestream": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/textlinestream/-/textlinestream-1.1.1.tgz", + "integrity": "sha512-iBHbi7BQxrFmwZUQJsT0SjNzlLLsXhvW/kg7EyOMVMBIrlnj/qYofwo1LVLZi+3GbUEo96Iu2eqToI2+lZoAEQ==" + }, + "toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==" + }, + "type-fest": { + "version": "4.20.1", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-4.20.1.tgz", + "integrity": "sha512-R6wDsVsoS9xYOpy8vgeBlqpdOyzJ12HNfQhC/aAKWM3YoCV9TtunJzh/QpkMgeDhkoynDcw5f1y+qF9yc/HHyg==" + }, + "type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "requires": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + } + }, + "typescript": { + "version": "5.5.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.5.2.tgz", + "integrity": "sha512-NcRtPEOsPFFWjobJEtfihkLCZCXZt/os3zf8nTxjVH3RvTSxjrCamJpbExGvYOF+tFHc3pA65qpdwPbzjohhew==" + }, + "undici-types": { + "version": "5.26.5", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", + "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==" + }, + "unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==" + }, + "utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==" + }, + "vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==" + }, + "wrap-ansi": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", + "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", + "requires": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + } + }, + "ws": { + "version": "8.17.1", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.17.1.tgz", + "integrity": "sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ==" + }, + "y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==" + }, + "yargs": { + "version": "17.7.2", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", + "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", + "requires": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + } + }, + "yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==" } + } } diff --git a/package.json b/package.json index 740680f9cf417900d1ed3f5b0cb5b19ed3ab0cce..4ebaab8926c8a340574b352f1d320e85d1cf55ac 100644 --- a/package.json +++ b/package.json @@ -1,23 +1,23 @@ { - "name": "live-vision", - "version": "1.0.0", - "description": "", - "main": "index.mjs", - "type": "module", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "repository": { - "type": "git", - "url": "https://huggingface.co/spaces/fffiloni/live-vision" - }, - "author": "", - "license": "MIT", - "dependencies": { - "@gradio/client": "^0.10.1", - "dotenv": "^4.0.0", - "eventsource": "^2.0.2", - "express": "^4.18.2", - "socket.io": "^4.5.4" - } - } \ No newline at end of file + "name": "live-vision", + "version": "1.0.0", + "description": "", + "main": "index.mjs", + "type": "module", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "https://huggingface.co/spaces/fffiloni/live-vision" + }, + "author": "", + "license": "MIT", + "dependencies": { + "@gradio/client": "^1.1.1", + "dotenv": "^4.0.0", + "eventsource": "^2.0.2", + "express": "^4.18.2", + "socket.io": "^4.5.4" + } +}